org.el 816 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496
  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-2022 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
  6. ;; Maintainer: Bastien Guerry <bzg@gnu.org>
  7. ;; Keywords: outlines, hypermedia, calendar, wp
  8. ;; Homepage: https://orgmode.org
  9. ;; Package-Requires: ((emacs "25.1"))
  10. ;; Version: 9.5.5
  11. ;; This file is part of GNU Emacs.
  12. ;;
  13. ;; GNU Emacs is free software: you can redistribute it and/or modify
  14. ;; it under the terms of the GNU General Public License as published by
  15. ;; the Free Software Foundation, either version 3 of the License, or
  16. ;; (at your option) any later version.
  17. ;; GNU Emacs is distributed in the hope that it will be useful,
  18. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. ;; GNU General Public License for more details.
  21. ;; You should have received a copy of the GNU General Public License
  22. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  23. ;;
  24. ;;; Commentary:
  25. ;;
  26. ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
  27. ;; project planning with a fast and effective plain-text system.
  28. ;;
  29. ;; Org mode develops organizational tasks around NOTES files that
  30. ;; contain information about projects as plain text. Org mode is
  31. ;; implemented on top of outline-mode, which makes it possible to keep
  32. ;; the content of large files well structured. Visibility cycling and
  33. ;; structure editing help to work with the tree. Tables are easily
  34. ;; created with a built-in table editor. Org mode supports ToDo
  35. ;; items, deadlines, time stamps, and scheduling. It dynamically
  36. ;; compiles entries into an agenda that utilizes and smoothly
  37. ;; integrates much of the Emacs calendar and diary. Plain text
  38. ;; URL-like links connect to websites, emails, Usenet messages, BBDB
  39. ;; entries, and any files related to the projects. For printing and
  40. ;; sharing of notes, an Org file can be exported as a structured ASCII
  41. ;; file, as HTML, or (todo and agenda items only) as an iCalendar
  42. ;; file. It can also serve as a publishing tool for a set of linked
  43. ;; webpages.
  44. ;;
  45. ;; Installation and Activation
  46. ;; ---------------------------
  47. ;; See the corresponding sections in the manual at
  48. ;;
  49. ;; https://orgmode.org/org.html#Installation
  50. ;;
  51. ;; Documentation
  52. ;; -------------
  53. ;; The documentation of Org mode can be found in the TeXInfo file. The
  54. ;; distribution also contains a PDF version of it. At the homepage of
  55. ;; Org mode, you can read the same text online as HTML. There is also an
  56. ;; excellent reference card made by Philip Rooke. This card can be found
  57. ;; in the doc/ directory.
  58. ;;
  59. ;; A list of recent changes can be found at
  60. ;; https://orgmode.org/Changes.html
  61. ;;
  62. ;;; Code:
  63. (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
  64. (defvar org-inlinetask-min-level)
  65. ;;;; Require other packages
  66. (require 'cl-lib)
  67. (eval-when-compile (require 'gnus-sum))
  68. (require 'calendar)
  69. (require 'find-func)
  70. (require 'format-spec)
  71. (or (eq this-command 'eval-buffer)
  72. (condition-case nil
  73. (load (concat (file-name-directory load-file-name)
  74. "org-loaddefs")
  75. nil t nil t)
  76. (error
  77. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  78. (sit-for 3)
  79. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  80. (sit-for 3))))
  81. (eval-and-compile (require 'org-macs))
  82. (require 'org-compat)
  83. (require 'org-keys)
  84. (require 'ol)
  85. (require 'oc)
  86. (require 'oc-basic)
  87. (require 'org-table)
  88. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  89. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  90. (defvar org-outline-regexp "\\*+ "
  91. "Regexp to match Org headlines.")
  92. (defvar org-outline-regexp-bol "^\\*+ "
  93. "Regexp to match Org headlines.
  94. This is similar to `org-outline-regexp' but additionally makes
  95. sure that we are at the beginning of the line.")
  96. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  97. "Matches a headline, putting stars and text into groups.
  98. Stars are put in group 1 and the trimmed body in group 2.")
  99. (declare-function calendar-check-holidays "holidays" (date))
  100. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  101. (declare-function cdlatex-math-symbol "ext:cdlatex")
  102. (declare-function Info-goto-node "info" (nodename &optional fork strict-case))
  103. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  104. (declare-function org-add-archive-files "org-archive" (files))
  105. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  106. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
  107. (declare-function org-agenda-redo "org-agenda" (&optional all))
  108. (declare-function org-agenda-remove-restriction-lock "org-agenda" (&optional noupdate))
  109. (declare-function org-archive-subtree "org-archive" (&optional find-done))
  110. (declare-function org-archive-subtree-default "org-archive" ())
  111. (declare-function org-archive-to-archive-sibling "org-archive" ())
  112. (declare-function org-attach "org-attach" ())
  113. (declare-function org-attach-dir "org-attach"
  114. (&optional create-if-not-exists-p no-fs-check))
  115. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  116. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  117. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  118. (declare-function org-clock-auto-clockout "org-clock" ())
  119. (declare-function org-clock-cancel "org-clock" ())
  120. (declare-function org-clock-display "org-clock" (&optional arg))
  121. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  122. (declare-function org-clock-goto "org-clock" (&optional select))
  123. (declare-function org-clock-in "org-clock" (&optional select start-time))
  124. (declare-function org-clock-in-last "org-clock" (&optional arg))
  125. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  126. (declare-function org-clock-out-if-current "org-clock" ())
  127. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  128. (declare-function org-clock-report "org-clock" (&optional arg))
  129. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  130. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  131. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  132. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  133. (declare-function org-clock-update-time-maybe "org-clock" ())
  134. (declare-function org-clocktable-shift "org-clock" (dir n))
  135. (declare-function org-columns-quit "org-colview" ())
  136. (declare-function org-columns-insert-dblock "org-colview" ())
  137. (declare-function org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  138. (declare-function org-duration-to-minutes "org-duration" (duration &optional canonical))
  139. (declare-function org-element-at-point "org-element" ())
  140. (declare-function org-element-cache-refresh "org-element" (pos))
  141. (declare-function org-element-cache-reset "org-element" (&optional all))
  142. (declare-function org-element-contents "org-element" (element))
  143. (declare-function org-element-context "org-element" (&optional element))
  144. (declare-function org-element-copy "org-element" (datum))
  145. (declare-function org-element-create "org-element" (type &optional props &rest children))
  146. (declare-function org-element-extract-element "org-element" (element))
  147. (declare-function org-element-insert-before "org-element" (element location))
  148. (declare-function org-element-interpret-data "org-element" (data))
  149. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  150. (declare-function org-element-link-parser "org-element" ())
  151. (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion with-affiliated))
  152. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  153. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  154. (declare-function org-element-parse-secondary-string "org-element" (string restriction &optional parent))
  155. (declare-function org-element-property "org-element" (property element))
  156. (declare-function org-element-put-property "org-element" (element property value))
  157. (declare-function org-element-restriction "org-element" (element))
  158. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  159. (declare-function org-element-timestamp-parser "org-element" ())
  160. (declare-function org-element-type "org-element" (element))
  161. (declare-function org-export-dispatch "ox" (&optional arg))
  162. (declare-function org-export-get-backend "ox" (name))
  163. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  164. (declare-function org-feed-goto-inbox "org-feed" (feed))
  165. (declare-function org-feed-update-all "org-feed" ())
  166. (declare-function org-goto "org-goto" (&optional alternative-interface))
  167. (declare-function org-id-find-id-file "org-id" (id))
  168. (declare-function org-id-get-create "org-id" (&optional force))
  169. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  170. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  171. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  172. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  173. (declare-function org-num-mode "org-num" (&optional arg))
  174. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  175. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  176. (declare-function org-timer "org-timer" (&optional restart no-insert))
  177. (declare-function org-timer-item "org-timer" (&optional arg))
  178. (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
  179. (declare-function org-timer-set-timer "org-timer" (&optional opt))
  180. (declare-function org-timer-start "org-timer" (&optional offset))
  181. (declare-function org-timer-stop "org-timer" ())
  182. (declare-function org-toggle-archive-tag "org-archive" (&optional find-done))
  183. (declare-function org-update-radio-target-regexp "ol" ())
  184. (defvar org-element-paragraph-separate)
  185. (defvar org-element--timestamp-regexp)
  186. (defvar org-indent-indentation-per-level)
  187. (defvar org-radio-target-regexp)
  188. (defvar org-target-link-regexp)
  189. (defvar org-target-regexp)
  190. (defvar org-id-overriding-file-name)
  191. ;; load languages based on value of `org-babel-load-languages'
  192. (defvar org-babel-load-languages)
  193. (defvar crm-separator) ; dynamically scoped param
  194. ;;;###autoload
  195. (defun org-babel-do-load-languages (sym value)
  196. "Load the languages defined in `org-babel-load-languages'."
  197. (set-default sym value)
  198. (dolist (pair org-babel-load-languages)
  199. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  200. (if active
  201. (require (intern (concat "ob-" lang)))
  202. (fmakunbound
  203. (intern (concat "org-babel-execute:" lang)))
  204. (fmakunbound
  205. (intern (concat "org-babel-expand-body:" lang)))))))
  206. ;;;###autoload
  207. (defun org-babel-load-file (file &optional compile)
  208. "Load Emacs Lisp source code blocks in the Org FILE.
  209. This function exports the source code using `org-babel-tangle'
  210. and then loads the resulting file using `load-file'. With
  211. optional prefix argument COMPILE, the tangled Emacs Lisp file is
  212. byte-compiled before it is loaded."
  213. (interactive "fFile to load: \nP")
  214. (let ((tangled-file (concat (file-name-sans-extension file) ".el")))
  215. ;; Tangle only if the Org file is newer than the Elisp file.
  216. (unless (org-file-newer-than-p
  217. tangled-file
  218. (file-attribute-modification-time
  219. (file-attributes (file-truename file))))
  220. (org-babel-tangle-file file
  221. tangled-file
  222. (rx string-start
  223. (or "emacs-lisp" "elisp")
  224. string-end)))
  225. (if compile
  226. (progn
  227. (byte-compile-file tangled-file)
  228. (load-file (byte-compile-dest-file tangled-file))
  229. (message "Compiled and loaded %s" tangled-file))
  230. (load-file tangled-file)
  231. (message "Loaded %s" tangled-file))))
  232. (defcustom org-babel-load-languages '((emacs-lisp . t))
  233. "Languages which can be evaluated in Org buffers.
  234. \\<org-mode-map>
  235. This list can be used to load support for any of the languages
  236. below. Each language will depend on a different set of system
  237. executables and/or Emacs modes.
  238. When a language is \"loaded\", code blocks in that language can
  239. be evaluated with `org-babel-execute-src-block', which is bound
  240. by default to \\[org-ctrl-c-ctrl-c].
  241. The `org-babel-no-eval-on-ctrl-c-ctrl-c' option can be set to
  242. remove code block evaluation from \\[org-ctrl-c-ctrl-c]. By
  243. default, only Emacs Lisp is loaded, since it has no specific
  244. requirement."
  245. :group 'org-babel
  246. :set 'org-babel-do-load-languages
  247. :version "24.1"
  248. :type '(alist :tag "Babel Languages"
  249. :key-type
  250. (choice
  251. (const :tag "Awk" awk)
  252. (const :tag "C" C)
  253. (const :tag "R" R)
  254. (const :tag "Calc" calc)
  255. (const :tag "Clojure" clojure)
  256. (const :tag "CSS" css)
  257. (const :tag "Ditaa" ditaa)
  258. (const :tag "Dot" dot)
  259. (const :tag "Emacs Lisp" emacs-lisp)
  260. (const :tag "Forth" forth)
  261. (const :tag "Fortran" fortran)
  262. (const :tag "Gnuplot" gnuplot)
  263. (const :tag "Haskell" haskell)
  264. (const :tag "Java" java)
  265. (const :tag "Javascript" js)
  266. (const :tag "LaTeX" latex)
  267. (const :tag "Lilypond" lilypond)
  268. (const :tag "Lisp" lisp)
  269. (const :tag "Makefile" makefile)
  270. (const :tag "Maxima" maxima)
  271. (const :tag "Matlab" matlab)
  272. (const :tag "Ocaml" ocaml)
  273. (const :tag "Octave" octave)
  274. (const :tag "Org" org)
  275. (const :tag "Perl" perl)
  276. (const :tag "Pico Lisp" picolisp)
  277. (const :tag "PlantUML" plantuml)
  278. (const :tag "Python" python)
  279. (const :tag "Ruby" ruby)
  280. (const :tag "Sass" sass)
  281. (const :tag "Scala" scala)
  282. (const :tag "Scheme" scheme)
  283. (const :tag "Screen" screen)
  284. (const :tag "Shell Script" shell)
  285. (const :tag "Sql" sql)
  286. (const :tag "Sqlite" sqlite)
  287. (const :tag "Stan" stan))
  288. :value-type (boolean :tag "Activate" :value t)))
  289. ;;;; Customization variables
  290. (defcustom org-clone-delete-id nil
  291. "Remove ID property of clones of a subtree.
  292. When non-nil, clones of a subtree don't inherit the ID property.
  293. Otherwise they inherit the ID property with a new unique
  294. identifier."
  295. :type 'boolean
  296. :version "24.1"
  297. :group 'org-id)
  298. ;;; Version
  299. (org-check-version)
  300. ;;;###autoload
  301. (defun org-version (&optional here full message)
  302. "Show the Org version.
  303. Interactively, or when MESSAGE is non-nil, show it in echo area.
  304. With prefix argument, or when HERE is non-nil, insert it at point.
  305. In non-interactive uses, a reduced version string is output unless
  306. FULL is given."
  307. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  308. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  309. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  310. (load-suffixes (list ".el"))
  311. (org-install-dir
  312. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  313. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  314. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  315. (let* ((load-suffixes save-load-suffixes)
  316. (release (org-release))
  317. (git-version (org-git-version))
  318. (version (format "Org mode version %s (%s @ %s)"
  319. release
  320. git-version
  321. (if org-install-dir
  322. (if (string= org-dir org-install-dir)
  323. org-install-dir
  324. (concat "mixed installation! "
  325. org-install-dir
  326. " and "
  327. org-dir))
  328. "org-loaddefs.el can not be found!")))
  329. (version1 (if full version release)))
  330. (when here (insert version1))
  331. (when message (message "%s" version1))
  332. version1)))
  333. (defconst org-version (org-version))
  334. ;;; Syntax Constants
  335. ;;;; Comments
  336. (defconst org-comment-regexp
  337. (rx (seq bol (zero-or-more (any "\t ")) "#" (or " " eol)))
  338. "Regular expression for comment lines.")
  339. ;;;; Keyword
  340. (defconst org-keyword-regexp "^[ \t]*#\\+\\(\\S-+?\\):[ \t]*\\(.*\\)$"
  341. "Regular expression for keyword-lines.")
  342. ;;;; Block
  343. (defconst org-block-regexp
  344. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  345. "Regular expression for hiding blocks.")
  346. (defconst org-dblock-start-re
  347. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  348. "Matches the start line of a dynamic block, with parameters.")
  349. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  350. "Matches the end of a dynamic block.")
  351. ;;;; Timestamp
  352. (defconst org-ts--internal-regexp
  353. (rx (seq
  354. (= 4 digit) "-" (= 2 digit) "-" (= 2 digit)
  355. (optional " " (*? nonl))))
  356. "Regular expression matching the innards of a time stamp.")
  357. (defconst org-ts-regexp (format "<\\(%s\\)>" org-ts--internal-regexp)
  358. "Regular expression for fast time stamp matching.")
  359. (defconst org-ts-regexp-inactive
  360. (format "\\[\\(%s\\)\\]" org-ts--internal-regexp)
  361. "Regular expression for fast inactive time stamp matching.")
  362. (defconst org-ts-regexp-both (format "[[<]\\(%s\\)[]>]" org-ts--internal-regexp)
  363. "Regular expression for fast time stamp matching.")
  364. (defconst org-ts-regexp0
  365. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  366. "Regular expression matching time strings for analysis.
  367. This one does not require the space after the date, so it can be used
  368. on a string that terminates immediately after the date.")
  369. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  370. "Regular expression matching time strings for analysis.")
  371. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  372. "Regular expression matching time stamps, with groups.")
  373. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  374. "Regular expression matching time stamps (also [..]), with groups.")
  375. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  376. "Regular expression matching a time stamp range.")
  377. (defconst org-tr-regexp-both
  378. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  379. "Regular expression matching a time stamp range.")
  380. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  381. org-ts-regexp "\\)?")
  382. "Regular expression matching a time stamp or time stamp range.")
  383. (defconst org-tsr-regexp-both
  384. (concat org-ts-regexp-both "\\(--?-?"
  385. org-ts-regexp-both "\\)?")
  386. "Regular expression matching a time stamp or time stamp range.
  387. The time stamps may be either active or inactive.")
  388. (defconst org-repeat-re
  389. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\
  390. \\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  391. "Regular expression for specifying repeated events.
  392. After a match, group 1 contains the repeat expression.")
  393. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  394. "Formats for `format-time-string' which are used for time stamps.")
  395. ;;;; Clock and Planning
  396. (defconst org-clock-string "CLOCK:"
  397. "String used as prefix for timestamps clocking work hours on an item.")
  398. (defvar org-closed-string "CLOSED:"
  399. "String used as the prefix for timestamps logging closing a TODO entry.")
  400. (defvar org-deadline-string "DEADLINE:"
  401. "String to mark deadline entries.
  402. \\<org-mode-map>
  403. A deadline is this string, followed by a time stamp. It must be
  404. a word, terminated by a colon. You can insert a schedule keyword
  405. and a timestamp with `\\[org-deadline]'.")
  406. (defvar org-scheduled-string "SCHEDULED:"
  407. "String to mark scheduled TODO entries.
  408. \\<org-mode-map>
  409. A schedule is this string, followed by a time stamp. It must be
  410. a word, terminated by a colon. You can insert a schedule keyword
  411. and a timestamp with `\\[org-schedule]'.")
  412. (defconst org-ds-keyword-length
  413. (+ 2
  414. (apply #'max
  415. (mapcar #'length
  416. (list org-deadline-string org-scheduled-string
  417. org-clock-string org-closed-string))))
  418. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  419. (defconst org-planning-line-re
  420. (concat "^[ \t]*"
  421. (regexp-opt
  422. (list org-closed-string org-deadline-string org-scheduled-string)
  423. t))
  424. "Matches a line with planning info.
  425. Matched keyword is in group 1.")
  426. (defconst org-clock-line-re
  427. (concat "^[ \t]*" org-clock-string)
  428. "Matches a line with clock info.")
  429. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  430. "Matches the DEADLINE keyword.")
  431. (defconst org-deadline-time-regexp
  432. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  433. "Matches the DEADLINE keyword together with a time stamp.")
  434. (defconst org-deadline-time-hour-regexp
  435. (concat "\\<" org-deadline-string
  436. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
  437. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  438. (defconst org-deadline-line-regexp
  439. (concat "\\<\\(" org-deadline-string "\\).*")
  440. "Matches the DEADLINE keyword and the rest of the line.")
  441. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  442. "Matches the SCHEDULED keyword.")
  443. (defconst org-scheduled-time-regexp
  444. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  445. "Matches the SCHEDULED keyword together with a time stamp.")
  446. (defconst org-scheduled-time-hour-regexp
  447. (concat "\\<" org-scheduled-string
  448. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
  449. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  450. (defconst org-closed-time-regexp
  451. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  452. "Matches the CLOSED keyword together with a time stamp.")
  453. (defconst org-keyword-time-regexp
  454. (concat "\\<"
  455. (regexp-opt
  456. (list org-scheduled-string org-deadline-string org-closed-string
  457. org-clock-string)
  458. t)
  459. " *[[<]\\([^]>]+\\)[]>]")
  460. "Matches any of the 4 keywords, together with the time stamp.")
  461. (defconst org-keyword-time-not-clock-regexp
  462. (concat
  463. "\\<"
  464. (regexp-opt
  465. (list org-scheduled-string org-deadline-string org-closed-string) t)
  466. " *[[<]\\([^]>]+\\)[]>]")
  467. "Matches any of the 3 keywords, together with the time stamp.")
  468. (defconst org-all-time-keywords
  469. (mapcar (lambda (w) (substring w 0 -1))
  470. (list org-scheduled-string org-deadline-string
  471. org-clock-string org-closed-string))
  472. "List of time keywords.")
  473. ;;;; Drawer
  474. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  475. "Matches first or last line of a hidden block.
  476. Group 1 contains drawer's name or \"END\".")
  477. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  478. "Regular expression matching the first line of a property drawer.")
  479. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  480. "Regular expression matching the last line of a property drawer.")
  481. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  482. "Regular expression matching the first line of a clock drawer.")
  483. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  484. "Regular expression matching the last line of a clock drawer.")
  485. (defconst org-logbook-drawer-re
  486. (rx (seq bol (0+ (any "\t ")) ":LOGBOOK:" (0+ (any "\t ")) "\n"
  487. (*? (0+ nonl) "\n")
  488. (0+ (any "\t ")) ":END:" (0+ (any "\t ")) eol))
  489. "Matches an entire LOGBOOK drawer.")
  490. (defconst org-property-drawer-re
  491. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  492. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  493. "[ \t]*:END:[ \t]*$")
  494. "Matches an entire property drawer.")
  495. (defconst org-clock-drawer-re
  496. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  497. org-clock-drawer-end-re "\\)\n?")
  498. "Matches an entire clock drawer.")
  499. ;;;; Headline
  500. (defconst org-heading-keyword-regexp-format
  501. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  502. "Printf format for a regexp matching a headline with some keyword.
  503. This regexp will match the headline of any node which has the
  504. exact keyword that is put into the format. The keyword isn't in
  505. any group by default, but the stars and the body are.")
  506. (defconst org-heading-keyword-maybe-regexp-format
  507. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  508. "Printf format for a regexp matching a headline, possibly with some keyword.
  509. This regexp can match any headline with the specified keyword, or
  510. without a keyword. The keyword isn't in any group by default,
  511. but the stars and the body are.")
  512. (defconst org-archive-tag "ARCHIVE"
  513. "The tag that marks a subtree as archived.
  514. An archived subtree does not open during visibility cycling, and does
  515. not contribute to the agenda listings.")
  516. (defconst org-tag-re "[[:alnum:]_@#%]+"
  517. "Regexp matching a single tag.")
  518. (defconst org-tag-group-re "[ \t]+\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  519. "Regexp matching the tag group at the end of a line, with leading spaces.
  520. Tags are stored in match group 1. Match group 2 stores the tags
  521. without the enclosing colons.")
  522. (defconst org-tag-line-re
  523. "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  524. "Regexp matching tags in a headline.
  525. Tags are stored in match group 1. Match group 2 stores the tags
  526. without the enclosing colons.")
  527. (eval-and-compile
  528. (defconst org-comment-string "COMMENT"
  529. "Entries starting with this keyword will never be exported.
  530. \\<org-mode-map>
  531. An entry can be toggled between COMMENT and normal with
  532. `\\[org-toggle-comment]'."))
  533. ;;;; LaTeX Environments and Fragments
  534. (defconst org-latex-regexps
  535. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  536. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  537. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  538. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  539. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  540. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  541. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  542. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  543. "Regular expressions for matching embedded LaTeX.")
  544. ;;;; Node Property
  545. (defconst org-effort-property "Effort"
  546. "The property that is being used to keep track of effort estimates.
  547. Effort estimates given in this property need to be in the format
  548. defined in org-duration.el.")
  549. ;;; The custom variables
  550. (defgroup org nil
  551. "Outline-based notes management and organizer."
  552. :tag "Org"
  553. :group 'outlines
  554. :group 'calendar)
  555. (defcustom org-mode-hook nil
  556. "Mode hook for Org mode, run after the mode was turned on."
  557. :group 'org
  558. :type 'hook)
  559. (defcustom org-load-hook nil
  560. "Hook that is run after org.el has been loaded."
  561. :group 'org
  562. :type 'hook)
  563. (make-obsolete-variable
  564. 'org-load-hook
  565. "use `with-eval-after-load' instead." "9.5")
  566. (defcustom org-log-buffer-setup-hook nil
  567. "Hook that is run after an Org log buffer is created."
  568. :group 'org
  569. :version "24.1"
  570. :type 'hook)
  571. (defvar org-modules) ; defined below
  572. (defvar org-modules-loaded nil
  573. "Have the modules been loaded already?")
  574. ;;;###autoload
  575. (defun org-load-modules-maybe (&optional force)
  576. "Load all extensions listed in `org-modules'."
  577. (when (or force (not org-modules-loaded))
  578. (dolist (ext org-modules)
  579. (condition-case nil (require ext)
  580. (error (message "Problems while trying to load feature `%s'" ext))))
  581. (setq org-modules-loaded t)))
  582. (defun org-set-modules (var value)
  583. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  584. (set var value)
  585. (when (featurep 'org)
  586. (org-load-modules-maybe 'force)
  587. (org-element-cache-reset 'all)))
  588. (defcustom org-modules '(ol-doi ol-w3m ol-bbdb ol-bibtex ol-docview ol-gnus ol-info ol-irc ol-mhe ol-rmail ol-eww)
  589. "Modules that should always be loaded together with org.el.
  590. If a description starts with <C>, the file is not part of Emacs and Org mode,
  591. so loading it will require that you have properly installed org-contrib
  592. package from NonGNU Emacs Lisp Package Archive
  593. https://elpa.nongnu.org/nongnu/org-contrib.html
  594. You can also use this system to load external packages (i.e. neither Org
  595. core modules, nor org-contrib modules). Just add symbols
  596. to the end of the list. If the package is called org-xyz.el, then you need
  597. to add the symbol `xyz', and the package must have a call to:
  598. (provide \\='org-xyz)
  599. For export specific modules, see also `org-export-backends'."
  600. :group 'org
  601. :set 'org-set-modules
  602. :package-version '(Org . "9.5")
  603. :type
  604. '(set :greedy t
  605. (const :tag " bbdb: Links to BBDB entries" ol-bbdb)
  606. (const :tag " bibtex: Links to BibTeX entries" ol-bibtex)
  607. (const :tag " crypt: Encryption of subtrees" org-crypt)
  608. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  609. (const :tag " docview: Links to Docview buffers" ol-docview)
  610. (const :tag " doi: Links to DOI references" ol-doi)
  611. (const :tag " eww: Store link to URL of Eww" ol-eww)
  612. (const :tag " gnus: Links to GNUS folders/messages" ol-gnus)
  613. (const :tag " habit: Track your consistency with habits" org-habit)
  614. (const :tag " id: Global IDs for identifying entries" org-id)
  615. (const :tag " info: Links to Info nodes" ol-info)
  616. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  617. (const :tag " irc: Links to IRC/ERC chat sessions" ol-irc)
  618. (const :tag " mhe: Links to MHE folders/messages" ol-mhe)
  619. (const :tag " mouse: Additional mouse support" org-mouse)
  620. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  621. (const :tag " rmail: Links to RMAIL folders/messages" ol-rmail)
  622. (const :tag " tempo: Fast completion for structures" org-tempo)
  623. (const :tag " w3m: Special cut/paste from w3m to Org mode." ol-w3m)
  624. (const :tag " eshell: Links to working directories in Eshell" ol-eshell)
  625. (const :tag "C annotate-file: Annotate a file with Org syntax" org-annotate-file)
  626. (const :tag "C bookmark: Links to bookmarks" ol-bookmark)
  627. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  628. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  629. (const :tag "C collector: Collect properties into tables" org-collector)
  630. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  631. (const :tag "C elisp-symbol: Links to emacs-lisp symbols" ol-elisp-symbol)
  632. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  633. (const :tag "C eval: Include command output as text" org-eval)
  634. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  635. (const :tag "C git-link: Links to specific file version" ol-git-link)
  636. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  637. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  638. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  639. (const :tag "C mac-iCal: Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  640. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  641. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  642. (const :tag "C man: Links to man pages in Org mode" ol-man)
  643. (const :tag "C mew: Links to Mew folders/messages" ol-mew)
  644. (const :tag "C notify: Notifications for Org mode" org-notify)
  645. (const :tag "C notmuch: Provide Org links to notmuch searches or messages" ol-notmuch)
  646. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  647. (const :tag "C registry: A registry for Org links" org-registry)
  648. (const :tag "C screen: Visit screen sessions through links" org-screen)
  649. (const :tag "C screenshot: Take and manage screenshots in Org files" org-screenshot)
  650. (const :tag "C secretary: Team management with Org" org-secretary)
  651. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  652. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  653. (const :tag "C track: Keep up with Org mode development" org-track)
  654. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  655. (const :tag "C vm: Links to VM folders/messages" ol-vm)
  656. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  657. (const :tag "C wl: Links to Wanderlust folders/messages" ol-wl)
  658. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  659. (defvar org-export-registered-backends) ; From ox.el.
  660. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  661. (declare-function org-export-backend-name "ox" (backend) t)
  662. (defcustom org-export-backends '(ascii html icalendar latex odt)
  663. "List of export back-ends that should be always available.
  664. If a description starts with <C>, the file is not part of Emacs and Org mode,
  665. so loading it will require that you have properly installed org-contrib
  666. package from NonGNU Emacs Lisp Package Archive
  667. https://elpa.nongnu.org/nongnu/org-contrib.html
  668. Unlike to `org-modules', libraries in this list will not be
  669. loaded along with Org, but only once the export framework is
  670. needed.
  671. This variable needs to be set before org.el is loaded. If you
  672. need to make a change while Emacs is running, use the customize
  673. interface or run the following code, where VAL stands for the new
  674. value of the variable, after updating it:
  675. (progn
  676. (setq org-export-registered-backends
  677. (cl-remove-if-not
  678. (lambda (backend)
  679. (let ((name (org-export-backend-name backend)))
  680. (or (memq name val)
  681. (catch \\='parentp
  682. (dolist (b val)
  683. (and (org-export-derived-backend-p b name)
  684. (throw \\='parentp t)))))))
  685. org-export-registered-backends))
  686. (let ((new-list (mapcar #\\='org-export-backend-name
  687. org-export-registered-backends)))
  688. (dolist (backend val)
  689. (cond
  690. ((not (load (format \"ox-%s\" backend) t t))
  691. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  692. backend))
  693. ((not (memq backend new-list)) (push backend new-list))))
  694. (set-default \\='org-export-backends new-list)))
  695. Adding a back-end to this list will also pull the back-end it
  696. depends on, if any."
  697. :group 'org
  698. :group 'org-export
  699. :version "26.1"
  700. :package-version '(Org . "9.0")
  701. :initialize 'custom-initialize-set
  702. :set (lambda (var val)
  703. (if (not (featurep 'ox)) (set-default var val)
  704. ;; Any back-end not required anymore (not present in VAL and not
  705. ;; a parent of any back-end in the new value) is removed from the
  706. ;; list of registered back-ends.
  707. (setq org-export-registered-backends
  708. (cl-remove-if-not
  709. (lambda (backend)
  710. (let ((name (org-export-backend-name backend)))
  711. (or (memq name val)
  712. (catch 'parentp
  713. (dolist (b val)
  714. (and (org-export-derived-backend-p b name)
  715. (throw 'parentp t)))))))
  716. org-export-registered-backends))
  717. ;; Now build NEW-LIST of both new back-ends and required
  718. ;; parents.
  719. (let ((new-list (mapcar #'org-export-backend-name
  720. org-export-registered-backends)))
  721. (dolist (backend val)
  722. (cond
  723. ((not (load (format "ox-%s" backend) t t))
  724. (message "Problems while trying to load export back-end `%s'"
  725. backend))
  726. ((not (memq backend new-list)) (push backend new-list))))
  727. ;; Set VAR to that list with fixed dependencies.
  728. (set-default var new-list))))
  729. :type '(set :greedy t
  730. (const :tag " ascii Export buffer to ASCII format" ascii)
  731. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  732. (const :tag " html Export buffer to HTML format" html)
  733. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  734. (const :tag " latex Export buffer to LaTeX format" latex)
  735. (const :tag " man Export buffer to MAN format" man)
  736. (const :tag " md Export buffer to Markdown format" md)
  737. (const :tag " odt Export buffer to ODT format" odt)
  738. (const :tag " org Export buffer to Org format" org)
  739. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  740. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  741. (const :tag "C deck Export buffer to deck.js presentations" deck)
  742. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  743. (const :tag "C groff Export buffer to Groff format" groff)
  744. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  745. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  746. (const :tag "C s5 Export buffer to s5 presentations" s5)
  747. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  748. (eval-after-load 'ox
  749. '(dolist (backend org-export-backends)
  750. (condition-case nil (require (intern (format "ox-%s" backend)))
  751. (error (message "Problems while trying to load export back-end `%s'"
  752. backend)))))
  753. (defcustom org-support-shift-select nil
  754. "Non-nil means make shift-cursor commands select text when possible.
  755. \\<org-mode-map>
  756. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  757. start selecting a region, or enlarge regions started in this way.
  758. In Org mode, in special contexts, these same keys are used for
  759. other purposes, important enough to compete with shift selection.
  760. Org tries to balance these needs by supporting `shift-select-mode'
  761. outside these special contexts, under control of this variable.
  762. The default of this variable is nil, to avoid confusing behavior. Shifted
  763. cursor keys will then execute Org commands in the following contexts:
  764. - on a headline, changing TODO state (left/right) and priority (up/down)
  765. - on a time stamp, changing the time
  766. - in a plain list item, changing the bullet type
  767. - in a property definition line, switching between allowed values
  768. - in the BEGIN line of a clock table (changing the time block).
  769. - in a table, moving the cell in the specified direction.
  770. Outside these contexts, the commands will throw an error.
  771. When this variable is t and the cursor is not in a special
  772. context, Org mode will support shift-selection for making and
  773. enlarging regions. To make this more effective, the bullet
  774. cycling will no longer happen anywhere in an item line, but only
  775. if the cursor is exactly on the bullet.
  776. If you set this variable to the symbol `always', then the keys
  777. will not be special in headlines, property lines, item lines, and
  778. table cells, to make shift selection work there as well. If this is
  779. what you want, you can use the following alternative commands:
  780. `\\[org-todo]' and `\\[org-priority]' \
  781. to change TODO state and priority,
  782. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  783. can be used to switch TODO sets,
  784. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  785. and properties can be edited by hand or in column view.
  786. However, when the cursor is on a timestamp, shift-cursor commands
  787. will still edit the time stamp - this is just too good to give up."
  788. :group 'org
  789. :type '(choice
  790. (const :tag "Never" nil)
  791. (const :tag "When outside special context" t)
  792. (const :tag "Everywhere except timestamps" always)))
  793. (defcustom org-loop-over-headlines-in-active-region t
  794. "Shall some commands act upon headlines in the active region?
  795. When set to t, some commands will be performed in all headlines
  796. within the active region.
  797. When set to `start-level', some commands will be performed in all
  798. headlines within the active region, provided that these headlines
  799. are of the same level than the first one.
  800. When set to a string, those commands will be performed on the
  801. matching headlines within the active region. Such string must be
  802. a tags/property/todo match as it is used in the agenda tags view.
  803. The list of commands is: `org-schedule', `org-deadline',
  804. `org-todo', `org-set-tags-command', `org-archive-subtree',
  805. `org-archive-set-tag', `org-toggle-archive-tag' and
  806. `org-archive-to-archive-sibling'. The archiving commands skip
  807. already archived entries.
  808. See `org-agenda-loop-over-headlines-in-active-region' for the
  809. equivalent option for agenda views."
  810. :type '(choice (const :tag "Don't loop" nil)
  811. (const :tag "All headlines in active region" t)
  812. (const :tag "In active region, headlines at the same level than the first one" start-level)
  813. (string :tag "Tags/Property/Todo matcher"))
  814. :package-version '(Org . "9.4")
  815. :group 'org-todo
  816. :group 'org-archive)
  817. (defcustom org-startup-folded 'showeverything
  818. "Non-nil means entering Org mode will switch to OVERVIEW.
  819. This can also be configured on a per-file basis by adding one of
  820. the following lines anywhere in the buffer:
  821. #+STARTUP: fold (or `overview', this is equivalent)
  822. #+STARTUP: nofold (or `showall', this is equivalent)
  823. #+STARTUP: content
  824. #+STARTUP: show<n>levels (<n> = 2..5)
  825. #+STARTUP: showeverything
  826. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  827. to ignore this option when Org opens agenda files for the first
  828. time."
  829. :group 'org-startup
  830. :package-version '(Org . "9.4")
  831. :type '(choice
  832. (const :tag "nofold: show all" nil)
  833. (const :tag "fold: overview" t)
  834. (const :tag "fold: show two levels" show2levels)
  835. (const :tag "fold: show three levels" show3levels)
  836. (const :tag "fold: show four levels" show4evels)
  837. (const :tag "fold: show five levels" show5levels)
  838. (const :tag "content: all headlines" content)
  839. (const :tag "show everything, even drawers" showeverything)))
  840. (defcustom org-startup-truncated t
  841. "Non-nil means entering Org mode will set `truncate-lines'.
  842. This is useful since some lines containing links can be very long and
  843. uninteresting. Also tables look terrible when wrapped.
  844. The variable `org-startup-truncated' allows to configure
  845. truncation for Org mode different to the other modes that use the
  846. variable `truncate-lines' and as a shortcut instead of putting
  847. the variable `truncate-lines' into the `org-mode-hook'. If one
  848. wants to configure truncation for Org mode not statically but
  849. dynamically e.g. in a hook like `ediff-prepare-buffer-hook' then
  850. the variable `truncate-lines' has to be used because in such a
  851. case it is too late to set the variable `org-startup-truncated'."
  852. :group 'org-startup
  853. :type 'boolean)
  854. (defcustom org-startup-indented nil
  855. "Non-nil means turn on `org-indent-mode' on startup.
  856. This can also be configured on a per-file basis by adding one of
  857. the following lines anywhere in the buffer:
  858. #+STARTUP: indent
  859. #+STARTUP: noindent"
  860. :group 'org-structure
  861. :type '(choice
  862. (const :tag "Not" nil)
  863. (const :tag "Globally (slow on startup in large files)" t)))
  864. (defcustom org-startup-numerated nil
  865. "Non-nil means turn on `org-num-mode' on startup.
  866. This can also be configured on a per-file basis by adding one of
  867. the following lines anywhere in the buffer:
  868. #+STARTUP: num
  869. #+STARTUP: nonum"
  870. :group 'org-structure
  871. :package-version '(Org . "9.4")
  872. :type '(choice
  873. (const :tag "Not" nil)
  874. (const :tag "Globally" t)))
  875. (defcustom org-use-sub-superscripts t
  876. "Non-nil means interpret \"_\" and \"^\" for display.
  877. If you want to control how Org exports those characters, see
  878. `org-export-with-sub-superscripts'.
  879. When this option is turned on, you can use TeX-like syntax for
  880. sub- and superscripts within the buffer. Several characters after
  881. \"_\" or \"^\" will be considered as a single item - so grouping
  882. with {} is normally not needed. For example, the following things
  883. will be parsed as single sub- or superscripts:
  884. 10^24 or 10^tau several digits will be considered 1 item.
  885. 10^-12 or 10^-tau a leading sign with digits or a word
  886. x^2-y^3 will be read as x^2 - y^3, because items are
  887. terminated by almost any nonword/nondigit char.
  888. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  889. Still, ambiguity is possible. So when in doubt, use {} to enclose
  890. the sub/superscript. If you set this variable to the symbol `{}',
  891. the braces are *required* in order to trigger interpretations as
  892. sub/superscript. This can be helpful in documents that need \"_\"
  893. frequently in plain text."
  894. :group 'org-startup
  895. :version "24.4"
  896. :package-version '(Org . "8.0")
  897. :type '(choice
  898. (const :tag "Always interpret" t)
  899. (const :tag "Only with braces" {})
  900. (const :tag "Never interpret" nil)))
  901. (defcustom org-startup-with-beamer-mode nil
  902. "Non-nil means turn on `org-beamer-mode' on startup.
  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: beamer"
  906. :group 'org-startup
  907. :version "24.1"
  908. :type 'boolean)
  909. (defcustom org-startup-align-all-tables nil
  910. "Non-nil means align all tables when visiting a file.
  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: align
  914. #+STARTUP: noalign"
  915. :group 'org-startup
  916. :type 'boolean)
  917. (defcustom org-startup-shrink-all-tables nil
  918. "Non-nil means shrink all table columns with a width cookie.
  919. This can also be configured on a per-file basis by adding one of
  920. the following lines anywhere in the buffer:
  921. #+STARTUP: shrink"
  922. :group 'org-startup
  923. :type 'boolean
  924. :version "27.1"
  925. :package-version '(Org . "9.2")
  926. :safe #'booleanp)
  927. (defcustom org-startup-with-inline-images nil
  928. "Non-nil means show inline images when loading a new Org file.
  929. This can also be configured on a per-file basis by adding one of
  930. the following lines anywhere in the buffer:
  931. #+STARTUP: inlineimages
  932. #+STARTUP: noinlineimages"
  933. :group 'org-startup
  934. :version "24.1"
  935. :type 'boolean)
  936. (defcustom org-startup-with-latex-preview nil
  937. "Non-nil means preview LaTeX fragments when loading a new Org file.
  938. This can also be configured on a per-file basis by adding one of
  939. the following lines anywhere in the buffer:
  940. #+STARTUP: latexpreview
  941. #+STARTUP: nolatexpreview"
  942. :group 'org-startup
  943. :version "24.4"
  944. :package-version '(Org . "8.0")
  945. :type 'boolean)
  946. (defcustom org-insert-mode-line-in-empty-file nil
  947. "Non-nil means insert the first line setting Org mode in empty files.
  948. When the function `org-mode' is called interactively in an empty file, this
  949. normally means that the file name does not automatically trigger Org mode.
  950. To ensure that the file will always be in Org mode in the future, a
  951. line enforcing Org mode will be inserted into the buffer, if this option
  952. has been set."
  953. :group 'org-startup
  954. :type 'boolean)
  955. (defcustom org-ellipsis nil
  956. "The ellipsis to use in the Org mode outline.
  957. When nil, just use the standard three dots. When a non-empty string,
  958. use that string instead.
  959. The change affects only Org mode (which will then use its own display table).
  960. Changing this requires executing `\\[org-mode]' in a buffer to become
  961. effective. It cannot be set as a local variable."
  962. :group 'org-startup
  963. :type '(choice (const :tag "Default" nil)
  964. (string :tag "String" :value "...#")))
  965. (defvar org-display-table nil
  966. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  967. (defcustom org-directory "~/org"
  968. "Directory with Org files.
  969. This is just a default location to look for Org files. There is no need
  970. at all to put your files into this directory. It is used in the
  971. following situations:
  972. 1. When a capture template specifies a target file that is not an
  973. absolute path. The path will then be interpreted relative to
  974. `org-directory'
  975. 2. When the value of variable `org-agenda-files' is a single file, any
  976. relative paths in this file will be taken as relative to
  977. `org-directory'."
  978. :group 'org-refile
  979. :group 'org-capture
  980. :type 'directory)
  981. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  982. "Default target for storing notes.
  983. Used as a fall back file for org-capture.el, for templates that
  984. do not specify a target file."
  985. :group 'org-refile
  986. :group 'org-capture
  987. :type 'file)
  988. (defcustom org-reverse-note-order nil
  989. "Non-nil means store new notes at the beginning of a file or entry.
  990. When nil, new notes will be filed to the end of a file or entry.
  991. This can also be a list with cons cells of regular expressions that
  992. are matched against file names, and values."
  993. :group 'org-capture
  994. :group 'org-refile
  995. :type '(choice
  996. (const :tag "Reverse always" t)
  997. (const :tag "Reverse never" nil)
  998. (repeat :tag "By file name regexp"
  999. (cons regexp boolean))))
  1000. (defgroup org-keywords nil
  1001. "Keywords in Org mode."
  1002. :tag "Org Keywords"
  1003. :group 'org)
  1004. (defcustom org-closed-keep-when-no-todo nil
  1005. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  1006. :group 'org-todo
  1007. :group 'org-keywords
  1008. :version "24.4"
  1009. :package-version '(Org . "8.0")
  1010. :type 'boolean)
  1011. (defgroup org-structure nil
  1012. "Options concerning the general structure of Org files."
  1013. :tag "Org Structure"
  1014. :group 'org)
  1015. (defgroup org-reveal-location nil
  1016. "Options about how to make context of a location visible."
  1017. :tag "Org Reveal Location"
  1018. :group 'org-structure)
  1019. (defcustom org-show-context-detail '((agenda . local)
  1020. (bookmark-jump . lineage)
  1021. (isearch . lineage)
  1022. (default . ancestors))
  1023. "Alist between context and visibility span when revealing a location.
  1024. \\<org-mode-map>Some actions may move point into invisible
  1025. locations. As a consequence, Org always exposes a neighborhood
  1026. around point. How much is shown depends on the initial action,
  1027. or context. Valid contexts are
  1028. agenda when exposing an entry from the agenda
  1029. org-goto when using the command `org-goto' (`\\[org-goto]')
  1030. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  1031. tags-tree when constructing a sparse tree based on tags matches
  1032. link-search when exposing search matches associated with a link
  1033. mark-goto when exposing the jump goal of a mark
  1034. bookmark-jump when exposing a bookmark location
  1035. isearch when exiting from an incremental search
  1036. default default for all contexts not set explicitly
  1037. Allowed visibility spans are
  1038. minimal show current headline; if point is not on headline,
  1039. also show entry
  1040. local show current headline, entry and next headline
  1041. ancestors show current headline and its direct ancestors; if
  1042. point is not on headline, also show entry
  1043. ancestors-full show current subtree and its direct ancestors
  1044. lineage show current headline, its direct ancestors and all
  1045. their children; if point is not on headline, also show
  1046. entry and first child
  1047. tree show current headline, its direct ancestors and all
  1048. their children; if point is not on headline, also show
  1049. entry and all children
  1050. canonical show current headline, its direct ancestors along with
  1051. their entries and children; if point is not located on
  1052. the headline, also show current entry and all children
  1053. As special cases, a nil or t value means show all contexts in
  1054. `minimal' or `canonical' view, respectively.
  1055. Some views can make displayed information very compact, but also
  1056. make it harder to edit the location of the match. In such
  1057. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  1058. more context."
  1059. :group 'org-reveal-location
  1060. :version "26.1"
  1061. :package-version '(Org . "9.0")
  1062. :type '(choice
  1063. (const :tag "Canonical" t)
  1064. (const :tag "Minimal" nil)
  1065. (repeat :greedy t :tag "Individual contexts"
  1066. (cons
  1067. (choice :tag "Context"
  1068. (const agenda)
  1069. (const org-goto)
  1070. (const occur-tree)
  1071. (const tags-tree)
  1072. (const link-search)
  1073. (const mark-goto)
  1074. (const bookmark-jump)
  1075. (const isearch)
  1076. (const default))
  1077. (choice :tag "Detail level"
  1078. (const minimal)
  1079. (const local)
  1080. (const ancestors)
  1081. (const ancestors-full)
  1082. (const lineage)
  1083. (const tree)
  1084. (const canonical))))))
  1085. (defcustom org-indirect-buffer-display 'other-window
  1086. "How should indirect tree buffers be displayed?
  1087. This applies to indirect buffers created with the commands
  1088. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1089. Valid values are:
  1090. current-window Display in the current window
  1091. other-window Just display in another window.
  1092. dedicated-frame Create one new frame, and re-use it each time.
  1093. new-frame Make a new frame each time. Note that in this case
  1094. previously-made indirect buffers are kept, and you need to
  1095. kill these buffers yourself."
  1096. :group 'org-structure
  1097. :group 'org-agenda-windows
  1098. :type '(choice
  1099. (const :tag "In current window" current-window)
  1100. (const :tag "In current frame, other window" other-window)
  1101. (const :tag "Each time a new frame" new-frame)
  1102. (const :tag "One dedicated frame" dedicated-frame)))
  1103. (defconst org-file-apps-gnu
  1104. '((remote . emacs)
  1105. (system . mailcap)
  1106. (t . mailcap))
  1107. "Default file applications on a UNIX or GNU/Linux system.
  1108. See `org-file-apps'.")
  1109. (defconst org-file-apps-macos
  1110. '((remote . emacs)
  1111. (system . "open %s")
  1112. ("ps.gz" . "gv %s")
  1113. ("eps.gz" . "gv %s")
  1114. ("dvi" . "xdvi %s")
  1115. ("fig" . "xfig %s")
  1116. (t . "open %s"))
  1117. "Default file applications on a macOS system.
  1118. The system \"open\" is known as a default, but we use X11 applications
  1119. for some files for which the OS does not have a good default.
  1120. See `org-file-apps'.")
  1121. (defconst org-file-apps-windowsnt
  1122. (list '(remote . emacs)
  1123. (cons 'system (lambda (file _path)
  1124. (with-no-warnings (w32-shell-execute "open" file))))
  1125. (cons t (lambda (file _path)
  1126. (with-no-warnings (w32-shell-execute "open" file)))))
  1127. "Default file applications on a Windows NT system.
  1128. The system \"open\" is used for most files.
  1129. See `org-file-apps'.")
  1130. (defcustom org-file-apps
  1131. '((auto-mode . emacs)
  1132. (directory . emacs)
  1133. ("\\.mm\\'" . default)
  1134. ("\\.x?html?\\'" . default)
  1135. ("\\.pdf\\'" . default))
  1136. "Applications for opening `file:path' items in a document.
  1137. \\<org-mode-map>
  1138. Org mode uses system defaults for different file types, but you
  1139. can use this variable to set the application for a given file
  1140. extension. The entries in this list are cons cells where the car
  1141. identifies files and the cdr the corresponding command.
  1142. Possible values for the file identifier are:
  1143. \"string\" A string as a file identifier can be interpreted in different
  1144. ways, depending on its contents:
  1145. - Alphanumeric characters only:
  1146. Match links with this file extension.
  1147. Example: (\"pdf\" . \"evince %s\")
  1148. to open PDFs with evince.
  1149. - Regular expression: Match links where the
  1150. filename matches the regexp. If you want to
  1151. use groups here, use shy groups.
  1152. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1153. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1154. to open *.html and *.xhtml with firefox.
  1155. - Regular expression which contains (non-shy) groups:
  1156. Match links where the whole link, including \"::\", and
  1157. anything after that, matches the regexp.
  1158. In a custom command string, %1, %2, etc. are replaced with
  1159. the parts of the link that were matched by the groups.
  1160. For backwards compatibility, if a command string is given
  1161. that does not use any of the group matches, this case is
  1162. handled identically to the second one (i.e. match against
  1163. file name only).
  1164. In a custom function, you can access the group matches with
  1165. (match-string n link).
  1166. Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
  1167. \"evince -p %1 %s\")
  1168. to open [[file:document.pdf::5]] with evince at page 5.
  1169. `directory' Matches a directory
  1170. `remote' Matches a remote file, accessible through tramp.
  1171. Remote files most likely should be visited through Emacs
  1172. because external applications cannot handle such paths.
  1173. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1174. so all files Emacs knows how to handle. Using this with
  1175. command `emacs' will open most files in Emacs. Beware that this
  1176. will also open html files inside Emacs, unless you add
  1177. (\"html\" . default) to the list as well.
  1178. `system' The system command to open files, like `open' on Windows
  1179. and macOS, and mailcap under GNU/Linux. This is the command
  1180. that will be selected if you call `org-open-at-point' with a
  1181. double prefix argument (`\\[universal-argument] \
  1182. \\[universal-argument] \\[org-open-at-point]').
  1183. t Default for files not matched by any of the other options.
  1184. Possible values for the command are:
  1185. `emacs' The file will be visited by the current Emacs process.
  1186. `default' Use the default application for this file type, which is the
  1187. association for t in the list, most likely in the system-specific
  1188. part. This can be used to overrule an unwanted setting in the
  1189. system-specific variable.
  1190. `system' Use the system command for opening files, like \"open\".
  1191. This command is specified by the entry whose car is `system'.
  1192. Most likely, the system-specific version of this variable
  1193. does define this command, but you can overrule/replace it
  1194. here.
  1195. `mailcap' Use command specified in the mailcaps.
  1196. string A command to be executed by a shell; %s will be replaced
  1197. by the path to the file.
  1198. function A Lisp function, which will be called with two arguments:
  1199. the file path and the original link string, without the
  1200. \"file:\" prefix.
  1201. For more examples, see the system specific constants
  1202. `org-file-apps-macos'
  1203. `org-file-apps-windowsnt'
  1204. `org-file-apps-gnu'."
  1205. :group 'org
  1206. :package-version '(Org . "9.4")
  1207. :type '(repeat
  1208. (cons (choice :value ""
  1209. (string :tag "Extension")
  1210. (const :tag "System command to open files" system)
  1211. (const :tag "Default for unrecognized files" t)
  1212. (const :tag "Remote file" remote)
  1213. (const :tag "Links to a directory" directory)
  1214. (const :tag "Any files that have Emacs modes"
  1215. auto-mode))
  1216. (choice :value ""
  1217. (const :tag "Visit with Emacs" emacs)
  1218. (const :tag "Use default" default)
  1219. (const :tag "Use the system command" system)
  1220. (string :tag "Command")
  1221. (function :tag "Function")))))
  1222. (defcustom org-open-non-existing-files nil
  1223. "Non-nil means `org-open-file' opens non-existing files.
  1224. When nil, an error is thrown.
  1225. This variable applies only to external applications because they
  1226. might choke on non-existing files. If the link is to a file that
  1227. will be opened in Emacs, the variable is ignored."
  1228. :group 'org
  1229. :type 'boolean
  1230. :safe #'booleanp)
  1231. (defcustom org-open-directory-means-index-dot-org nil
  1232. "When non-nil a link to a directory really means to \"index.org\".
  1233. When nil, following a directory link runs Dired or opens
  1234. a finder/explorer window on that directory."
  1235. :group 'org
  1236. :type 'boolean
  1237. :safe #'booleanp)
  1238. (defcustom org-bookmark-names-plist
  1239. '(:last-capture "org-capture-last-stored"
  1240. :last-refile "org-refile-last-stored"
  1241. :last-capture-marker "org-capture-last-stored-marker")
  1242. "Names for bookmarks automatically set by some Org commands.
  1243. This can provide strings as names for a number of bookmarks Org sets
  1244. automatically. The following keys are currently implemented:
  1245. :last-capture
  1246. :last-capture-marker
  1247. :last-refile
  1248. When a key does not show up in the property list, the corresponding bookmark
  1249. is not set."
  1250. :group 'org-structure
  1251. :type 'plist)
  1252. (defgroup org-cycle nil
  1253. "Options concerning visibility cycling in Org mode."
  1254. :tag "Org Cycle"
  1255. :group 'org-structure)
  1256. (defcustom org-cycle-skip-children-state-if-no-children t
  1257. "Non-nil means skip CHILDREN state in entries that don't have any."
  1258. :group 'org-cycle
  1259. :type 'boolean)
  1260. (defcustom org-cycle-max-level nil
  1261. "Maximum level which should still be subject to visibility cycling.
  1262. Levels higher than this will, for cycling, be treated as text, not a headline.
  1263. When `org-odd-levels-only' is set, a value of N in this variable actually
  1264. means 2N-1 stars as the limiting headline.
  1265. When nil, cycle all levels.
  1266. Note that the limiting level of cycling is also influenced by
  1267. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1268. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1269. than its value."
  1270. :group 'org-cycle
  1271. :type '(choice
  1272. (const :tag "No limit" nil)
  1273. (integer :tag "Maximum level")))
  1274. (defcustom org-hide-block-startup nil
  1275. "Non-nil means entering Org mode will fold all blocks.
  1276. This can also be set in on a per-file basis with
  1277. #+STARTUP: hideblocks
  1278. #+STARTUP: showblocks"
  1279. :group 'org-startup
  1280. :group 'org-cycle
  1281. :type 'boolean)
  1282. (defcustom org-cycle-global-at-bob nil
  1283. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1284. This makes it possible to do global cycling without having to use `S-TAB'
  1285. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1286. line of the buffer
  1287. must not be a headline -- it may be empty or some other text.
  1288. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1289. sure the cursor stays at the beginning of the buffer.
  1290. When this option is nil, don't do anything special at the beginning of
  1291. the buffer."
  1292. :group 'org-cycle
  1293. :type 'boolean)
  1294. (defcustom org-cycle-level-after-item/entry-creation t
  1295. "Non-nil means cycle entry level or item indentation in new empty entries.
  1296. When the cursor is at the end of an empty headline, i.e., with only stars
  1297. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1298. and then all possible ancestor states, before returning to the original state.
  1299. This makes data entry extremely fast: M-RET to create a new headline,
  1300. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1301. When the cursor is at the end of an empty plain list item, one TAB will
  1302. make it a subitem, two or more tabs will back up to make this an item
  1303. higher up in the item hierarchy."
  1304. :group 'org-cycle
  1305. :type 'boolean)
  1306. (defcustom org-cycle-emulate-tab t
  1307. "Where should `org-cycle' emulate TAB.
  1308. nil Never
  1309. white Only in completely white lines
  1310. whitestart Only at the beginning of lines, before the first non-white char
  1311. t Everywhere except in headlines
  1312. exc-hl-bol Everywhere except at the start of a headline
  1313. If TAB is used in a place where it does not emulate TAB, the current subtree
  1314. visibility is cycled."
  1315. :group 'org-cycle
  1316. :type '(choice (const :tag "Never" nil)
  1317. (const :tag "Only in completely white lines" white)
  1318. (const :tag "Before first char in a line" whitestart)
  1319. (const :tag "Everywhere except in headlines" t)
  1320. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1321. (defcustom org-cycle-separator-lines 2
  1322. "Number of empty lines needed to keep an empty line between collapsed trees.
  1323. If you leave an empty line between the end of a subtree and the following
  1324. headline, this empty line is hidden when the subtree is folded.
  1325. Org mode will leave (exactly) one empty line visible if the number of
  1326. empty lines is equal or larger to the number given in this variable.
  1327. So the default 2 means at least 2 empty lines after the end of a subtree
  1328. are needed to produce free space between a collapsed subtree and the
  1329. following headline.
  1330. If the number is negative, and the number of empty lines is at least -N,
  1331. all empty lines are shown.
  1332. Special case: when 0, never leave empty lines in collapsed view."
  1333. :group 'org-cycle
  1334. :type 'integer)
  1335. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1336. (defcustom org-pre-cycle-hook nil
  1337. "Hook that is run before visibility cycling is happening.
  1338. The function(s) in this hook must accept a single argument which indicates
  1339. the new state that will be set right after running this hook. The
  1340. argument is a symbol. Before a global state change, it can have the values
  1341. `overview', `content', or `all'. Before a local state change, it can have
  1342. the values `folded', `children', or `subtree'."
  1343. :group 'org-cycle
  1344. :type 'hook)
  1345. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1346. org-cycle-hide-drawers
  1347. org-cycle-show-empty-lines
  1348. org-optimize-window-after-visibility-change)
  1349. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1350. The function(s) in this hook must accept a single argument which indicates
  1351. the new state that was set by the most recent `org-cycle' command. The
  1352. argument is a symbol. After a global state change, it can have the values
  1353. `overview', `contents', or `all'. After a local state change, it can have
  1354. the values `folded', `children', or `subtree'."
  1355. :group 'org-cycle
  1356. :package-version '(Org . "9.4")
  1357. :type 'hook)
  1358. (defgroup org-edit-structure nil
  1359. "Options concerning structure editing in Org mode."
  1360. :tag "Org Edit Structure"
  1361. :group 'org-structure)
  1362. (defcustom org-odd-levels-only nil
  1363. "Non-nil means skip even levels and only use odd levels for the outline.
  1364. This has the effect that two stars are being added/taken away in
  1365. promotion/demotion commands. It also influences how levels are
  1366. handled by the exporters.
  1367. Changing it requires restart of `font-lock-mode' to become effective
  1368. for fontification also in regions already fontified.
  1369. You may also set this on a per-file basis by adding one of the following
  1370. lines to the buffer:
  1371. #+STARTUP: odd
  1372. #+STARTUP: oddeven"
  1373. :group 'org-edit-structure
  1374. :group 'org-appearance
  1375. :type 'boolean)
  1376. (defcustom org-adapt-indentation nil
  1377. "Non-nil means adapt indentation to outline node level.
  1378. When set to t, Org assumes that you write outlines by indenting
  1379. text in each node to align with the headline, after the stars.
  1380. When this variable is set to `headline-data', Org only adapts the
  1381. indentation of the data lines right below the headline, such as
  1382. planning/clock lines and property/logbook drawers.
  1383. The following issues are influenced by this variable:
  1384. - The indentation is increased by one space in a demotion
  1385. command, and decreased by one in a promotion command. However,
  1386. in the latter case, if shifting some line in the entry body
  1387. would alter document structure (e.g., insert a new headline),
  1388. indentation is not changed at all.
  1389. - Property drawers and planning information is inserted indented
  1390. when this variable is set. When nil, they will not be indented.
  1391. - TAB indents a line relative to current level. The lines below
  1392. a headline will be indented when this variable is set to t.
  1393. Note that this is all about true indentation, by adding and
  1394. removing space characters. See also \"org-indent.el\" which does
  1395. level-dependent indentation in a virtual way, i.e. at display
  1396. time in Emacs."
  1397. :group 'org-edit-structure
  1398. :type '(choice
  1399. (const :tag "Adapt indentation for all lines" t)
  1400. (const :tag "Adapt indentation for headline data lines"
  1401. headline-data)
  1402. (const :tag "Do not adapt indentation at all" nil))
  1403. :safe (lambda (x) (memq x '(t nil headline-data))))
  1404. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1405. (defcustom org-special-ctrl-a/e nil
  1406. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1407. When t, `C-a' will bring back the cursor to the beginning of the
  1408. headline text, i.e. after the stars and after a possible TODO
  1409. keyword. In an item, this will be the position after bullet and
  1410. check-box, if any. When the cursor is already at that position,
  1411. another `C-a' will bring it to the beginning of the line.
  1412. `C-e' will jump to the end of the headline, ignoring the presence
  1413. of tags in the headline. A second `C-e' will then jump to the
  1414. true end of the line, after any tags. This also means that, when
  1415. this variable is non-nil, `C-e' also will never jump beyond the
  1416. end of the heading of a folded section, i.e. not after the
  1417. ellipses.
  1418. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1419. normally, going to the true line boundary first. Only a directly
  1420. following, identical keypress will bring the cursor to the
  1421. special positions.
  1422. This may also be a cons cell where the behavior for `C-a' and
  1423. `C-e' is set separately."
  1424. :group 'org-edit-structure
  1425. :type '(choice
  1426. (const :tag "off" nil)
  1427. (const :tag "on: after stars/bullet and before tags first" t)
  1428. (const :tag "reversed: true line boundary first" reversed)
  1429. (cons :tag "Set C-a and C-e separately"
  1430. (choice :tag "Special C-a"
  1431. (const :tag "off" nil)
  1432. (const :tag "on: after stars/bullet first" t)
  1433. (const :tag "reversed: before stars/bullet first" reversed))
  1434. (choice :tag "Special C-e"
  1435. (const :tag "off" nil)
  1436. (const :tag "on: before tags first" t)
  1437. (const :tag "reversed: after tags first" reversed)))))
  1438. (defcustom org-special-ctrl-k nil
  1439. "Non-nil means `C-k' will behave specially in headlines.
  1440. When nil, `C-k' will call the default `kill-line' command.
  1441. When t, the following will happen while the cursor is in the headline:
  1442. - When at the beginning of a headline, kill the entire subtree.
  1443. - When in the middle of the headline text, kill the text up to the tags.
  1444. - When after the headline text and before the tags, kill all the tags."
  1445. :group 'org-edit-structure
  1446. :type 'boolean)
  1447. (defcustom org-ctrl-k-protect-subtree nil
  1448. "Non-nil means, do not delete a hidden subtree with `C-k'.
  1449. When set to the symbol `error', simply throw an error when `C-k' is
  1450. used to kill (part-of) a headline that has hidden text behind it.
  1451. Any other non-nil value will result in a query to the user, if it is
  1452. OK to kill that hidden subtree. When nil, kill without remorse."
  1453. :group 'org-edit-structure
  1454. :version "24.1"
  1455. :type '(choice
  1456. (const :tag "Do not protect hidden subtrees" nil)
  1457. (const :tag "Protect hidden subtrees with a security query" t)
  1458. (const :tag "Never kill a hidden subtree with C-k" error)))
  1459. (defcustom org-special-ctrl-o t
  1460. "Non-nil means, make `open-line' (\\[open-line]) insert a row in tables."
  1461. :group 'org-edit-structure
  1462. :type 'boolean)
  1463. (defcustom org-catch-invisible-edits nil
  1464. "Check if in invisible region before inserting or deleting a character.
  1465. Valid values are:
  1466. nil Do not check, so just do invisible edits.
  1467. error Throw an error and do nothing.
  1468. show Make point visible, and do the requested edit.
  1469. show-and-error Make point visible, then throw an error and abort the edit.
  1470. smart Make point visible, and do insertion/deletion if it is
  1471. adjacent to visible text and the change feels predictable.
  1472. Never delete a previously invisible character or add in the
  1473. middle or right after an invisible region. Basically, this
  1474. allows insertion and backward-delete right before ellipses.
  1475. FIXME: maybe in this case we should not even show?"
  1476. :group 'org-edit-structure
  1477. :version "24.1"
  1478. :type '(choice
  1479. (const :tag "Do not check" nil)
  1480. (const :tag "Throw error when trying to edit" error)
  1481. (const :tag "Unhide, but do not do the edit" show-and-error)
  1482. (const :tag "Show invisible part and do the edit" show)
  1483. (const :tag "Be smart and do the right thing" smart)))
  1484. (defcustom org-yank-folded-subtrees t
  1485. "Non-nil means when yanking subtrees, fold them.
  1486. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1487. it starts with a heading and all other headings in it are either children
  1488. or siblings, then fold all the subtrees. However, do this only if no
  1489. text after the yank would be swallowed into a folded tree by this action."
  1490. :group 'org-edit-structure
  1491. :type 'boolean)
  1492. (defcustom org-yank-adjusted-subtrees nil
  1493. "Non-nil means when yanking subtrees, adjust the level.
  1494. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1495. this function for details."
  1496. :group 'org-edit-structure
  1497. :type 'boolean)
  1498. (defcustom org-M-RET-may-split-line '((default . t))
  1499. "Non-nil means M-RET will split the line at the cursor position.
  1500. When nil, it will go to the end of the line before making a
  1501. new line.
  1502. You may also set this option in a different way for different
  1503. contexts. Valid contexts are:
  1504. headline when creating a new headline
  1505. item when creating a new item
  1506. table in a table field
  1507. default the value to be used for all contexts not explicitly
  1508. customized"
  1509. :group 'org-structure
  1510. :group 'org-table
  1511. :type '(choice
  1512. (const :tag "Always" t)
  1513. (const :tag "Never" nil)
  1514. (repeat :greedy t :tag "Individual contexts"
  1515. (cons
  1516. (choice :tag "Context"
  1517. (const headline)
  1518. (const item)
  1519. (const table)
  1520. (const default))
  1521. (boolean)))))
  1522. (defcustom org-insert-heading-respect-content nil
  1523. "Non-nil means insert new headings after the current subtree.
  1524. \\<org-mode-map>
  1525. When nil, the new heading is created directly after the current line.
  1526. The commands `\\[org-insert-heading-respect-content]' and \
  1527. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1528. for the duration of the command."
  1529. :group 'org-structure
  1530. :type 'boolean)
  1531. (defcustom org-blank-before-new-entry '((heading . auto)
  1532. (plain-list-item . auto))
  1533. "Should `org-insert-heading' leave a blank line before new heading/item?
  1534. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1535. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1536. which case Org will look at the surrounding headings/items and try to
  1537. make an intelligent decision whether to insert a blank line or not."
  1538. :group 'org-edit-structure
  1539. :type '(list
  1540. (cons (const heading)
  1541. (choice (const :tag "Never" nil)
  1542. (const :tag "Always" t)
  1543. (const :tag "Auto" auto)))
  1544. (cons (const plain-list-item)
  1545. (choice (const :tag "Never" nil)
  1546. (const :tag "Always" t)
  1547. (const :tag "Auto" auto)))))
  1548. (defcustom org-insert-heading-hook nil
  1549. "Hook being run after inserting a new heading."
  1550. :group 'org-edit-structure
  1551. :type 'hook)
  1552. (defgroup org-sparse-trees nil
  1553. "Options concerning sparse trees in Org mode."
  1554. :tag "Org Sparse Trees"
  1555. :group 'org-structure)
  1556. (defcustom org-highlight-sparse-tree-matches t
  1557. "Non-nil means highlight all matches that define a sparse tree.
  1558. The highlights will automatically disappear the next time the buffer is
  1559. changed by an edit command."
  1560. :group 'org-sparse-trees
  1561. :type 'boolean)
  1562. (defcustom org-remove-highlights-with-change t
  1563. "Non-nil means any change to the buffer will remove temporary highlights.
  1564. \\<org-mode-map>\
  1565. Such highlights are created by `org-occur' and `org-clock-display'.
  1566. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1567. to get rid of the highlights.
  1568. The highlights created by `org-latex-preview' always need
  1569. `\\[org-latex-preview]' to be removed."
  1570. :group 'org-sparse-trees
  1571. :group 'org-time
  1572. :type 'boolean)
  1573. (defcustom org-occur-case-fold-search t
  1574. "Non-nil means `org-occur' should be case-insensitive.
  1575. If set to `smart' the search will be case-insensitive only if it
  1576. doesn't specify any upper case character."
  1577. :group 'org-sparse-trees
  1578. :version "26.1"
  1579. :type '(choice
  1580. (const :tag "Case-sensitive" nil)
  1581. (const :tag "Case-insensitive" t)
  1582. (const :tag "Case-insensitive for lower case searches only" smart)))
  1583. (defcustom org-occur-hook '(org-first-headline-recenter)
  1584. "Hook that is run after `org-occur' has constructed a sparse tree.
  1585. This can be used to recenter the window to show as much of the structure
  1586. as possible."
  1587. :group 'org-sparse-trees
  1588. :type 'hook)
  1589. (defcustom org-self-insert-cluster-for-undo nil
  1590. "Non-nil means cluster self-insert commands for undo when possible.
  1591. If this is set, then, like in the Emacs command loop, 20 consecutive
  1592. characters will be undone together.
  1593. This is configurable, because there is some impact on typing performance."
  1594. :group 'org-table
  1595. :type 'boolean)
  1596. (defvaralias 'org-activate-links 'org-highlight-links)
  1597. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1598. "Types of links that should be highlighted in Org files.
  1599. This is a list of symbols, each one of them leading to the
  1600. highlighting of a certain link type.
  1601. You can still open links that are not highlighted.
  1602. In principle, it does not hurt to turn on highlighting for all
  1603. link types. There may be a small gain when turning off unused
  1604. link types. The types are:
  1605. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1606. angle Links in angular brackets that may contain whitespace like
  1607. <bbdb:Carsten Dominik>.
  1608. plain Plain links in normal text, no whitespace, like https://gnu.org.
  1609. radio Text that is matched by a radio target, see manual for details.
  1610. tag Tag settings in a headline (link to tag search).
  1611. date Time stamps (link to calendar).
  1612. footnote Footnote labels.
  1613. If you set this variable during an Emacs session, use `org-mode-restart'
  1614. in the Org buffer so that the change takes effect."
  1615. :group 'org-appearance
  1616. :type '(set :greedy t
  1617. (const :tag "Double bracket links" bracket)
  1618. (const :tag "Angular bracket links" angle)
  1619. (const :tag "Plain text links" plain)
  1620. (const :tag "Radio target matches" radio)
  1621. (const :tag "Tags" tag)
  1622. (const :tag "Timestamps" date)
  1623. (const :tag "Footnotes" footnote)))
  1624. (defcustom org-mark-ring-length 4
  1625. "Number of different positions to be recorded in the ring.
  1626. Changing this requires a restart of Emacs to work correctly."
  1627. :group 'org-link-follow
  1628. :type 'integer)
  1629. (defgroup org-todo nil
  1630. "Options concerning TODO items in Org mode."
  1631. :tag "Org TODO"
  1632. :group 'org)
  1633. (defgroup org-progress nil
  1634. "Options concerning Progress logging in Org mode."
  1635. :tag "Org Progress"
  1636. :group 'org-time)
  1637. (defvar org-todo-interpretation-widgets
  1638. '((:tag "Sequence (cycling hits every state)" sequence)
  1639. (:tag "Type (cycling directly to DONE)" type))
  1640. "The available interpretation symbols for customizing `org-todo-keywords'.
  1641. Interested libraries should add to this list.")
  1642. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  1643. "List of TODO entry keyword sequences and their interpretation.
  1644. \\<org-mode-map>This is a list of sequences.
  1645. Each sequence starts with a symbol, either `sequence' or `type',
  1646. indicating if the keywords should be interpreted as a sequence of
  1647. action steps, or as different types of TODO items. The first
  1648. keywords are states requiring action - these states will select a headline
  1649. for inclusion into the global TODO list Org produces. If one of the
  1650. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  1651. signify that no further action is necessary. If \"|\" is not found,
  1652. the last keyword is treated as the only DONE state of the sequence.
  1653. The command `\\[org-todo]' cycles an entry through these states, and one
  1654. additional state where no keyword is present. For details about this
  1655. cycling, see the manual.
  1656. TODO keywords and interpretation can also be set on a per-file basis with
  1657. the special #+SEQ_TODO and #+TYP_TODO lines.
  1658. Each keyword can optionally specify a character for fast state selection
  1659. \(in combination with the variable `org-use-fast-todo-selection')
  1660. and specifiers for state change logging, using the same syntax that
  1661. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  1662. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  1663. indicates to record a time stamp each time this state is selected.
  1664. Each keyword may also specify if a timestamp or a note should be
  1665. recorded when entering or leaving the state, by adding additional
  1666. characters in the parenthesis after the keyword. This looks like this:
  1667. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  1668. record only the time of the state change. With X and Y being either
  1669. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  1670. Y when leaving the state if and only if the *target* state does not
  1671. define X. You may omit any of the fast-selection key or X or /Y,
  1672. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  1673. For backward compatibility, this variable may also be just a list
  1674. of keywords. In this case the interpretation (sequence or type) will be
  1675. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  1676. :group 'org-todo
  1677. :group 'org-keywords
  1678. :type '(choice
  1679. (repeat :tag "Old syntax, just keywords"
  1680. (string :tag "Keyword"))
  1681. (repeat :tag "New syntax"
  1682. (cons
  1683. (choice
  1684. :tag "Interpretation"
  1685. ;;Quick and dirty way to see
  1686. ;;`org-todo-interpretation'. This takes the
  1687. ;;place of item arguments
  1688. :convert-widget
  1689. (lambda (widget)
  1690. (widget-put widget
  1691. :args (mapcar
  1692. (lambda (x)
  1693. (widget-convert
  1694. (cons 'const x)))
  1695. org-todo-interpretation-widgets))
  1696. widget))
  1697. (repeat
  1698. (string :tag "Keyword"))))))
  1699. (defvar-local org-todo-keywords-1 nil
  1700. "All TODO and DONE keywords active in a buffer.")
  1701. (defvar org-todo-keywords-for-agenda nil)
  1702. (defvar org-done-keywords-for-agenda nil)
  1703. (defvar org-todo-keyword-alist-for-agenda nil)
  1704. (defvar org-tag-alist-for-agenda nil
  1705. "Alist of all tags from all agenda files.")
  1706. (defvar org-tag-groups-alist-for-agenda nil
  1707. "Alist of all groups tags from all current agenda files.")
  1708. (defvar-local org-tag-groups-alist nil)
  1709. (defvar org-agenda-contributing-files nil)
  1710. (defvar-local org-current-tag-alist nil
  1711. "Alist of all tag groups in current buffer.
  1712. This variable takes into consideration `org-tag-alist',
  1713. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  1714. (defvar-local org-not-done-keywords nil)
  1715. (defvar-local org-done-keywords nil)
  1716. (defvar-local org-todo-heads nil)
  1717. (defvar-local org-todo-sets nil)
  1718. (defvar-local org-todo-log-states nil)
  1719. (defvar-local org-todo-kwd-alist nil)
  1720. (defvar-local org-todo-key-alist nil)
  1721. (defvar-local org-todo-key-trigger nil)
  1722. (defcustom org-todo-interpretation 'sequence
  1723. "Controls how TODO keywords are interpreted.
  1724. This variable is in principle obsolete and is only used for
  1725. backward compatibility, if the interpretation of todo keywords is
  1726. not given already in `org-todo-keywords'. See that variable for
  1727. more information."
  1728. :group 'org-todo
  1729. :group 'org-keywords
  1730. :type '(choice (const sequence)
  1731. (const type)))
  1732. (defcustom org-use-fast-todo-selection 'auto
  1733. "\\<org-mode-map>\
  1734. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  1735. This variable describes if and under what circumstances the cycling
  1736. mechanism for TODO keywords will be replaced by a single-key, direct
  1737. selection scheme, where the choices are displayed in a little window.
  1738. When nil, fast selection is never used. This means that the command
  1739. will always switch to the next state.
  1740. When it is the symbol `auto', fast selection is whenever selection
  1741. keys have been defined.
  1742. `expert' is like `auto', but no special window with the keyword
  1743. will be shown, choices will only be listed in the prompt.
  1744. In all cases, the special interface is only used if access keys have
  1745. actually been assigned by the user, i.e. if keywords in the configuration
  1746. are followed by a letter in parenthesis, like TODO(t)."
  1747. :group 'org-todo
  1748. :set (lambda (var val)
  1749. (cond
  1750. ((eq var t) (set var 'auto))
  1751. ((eq var 'prefix) (set var nil))
  1752. (t (set var val))))
  1753. :type '(choice
  1754. (const :tag "Never" nil)
  1755. (const :tag "Automatically, when key letter have been defined" auto)
  1756. (const :tag "Automatically, but don't show the selection window" expert)))
  1757. (defcustom org-provide-todo-statistics t
  1758. "Non-nil means update todo statistics after insert and toggle.
  1759. ALL-HEADLINES means update todo statistics by including headlines
  1760. with no TODO keyword as well, counting them as not done.
  1761. A list of TODO keywords means the same, but skip keywords that are
  1762. not in this list.
  1763. When set to a list of two lists, the first list contains keywords
  1764. to consider as TODO keywords, the second list contains keywords
  1765. to consider as DONE keywords.
  1766. When this is set, todo statistics is updated in the parent of the
  1767. current entry each time a todo state is changed."
  1768. :group 'org-todo
  1769. :type '(choice
  1770. (const :tag "Yes, only for TODO entries" t)
  1771. (const :tag "Yes, including all entries" all-headlines)
  1772. (repeat :tag "Yes, for TODOs in this list"
  1773. (string :tag "TODO keyword"))
  1774. (list :tag "Yes, for TODOs and DONEs in these lists"
  1775. (repeat (string :tag "TODO keyword"))
  1776. (repeat (string :tag "DONE keyword")))
  1777. (other :tag "No TODO statistics" nil)))
  1778. (defcustom org-hierarchical-todo-statistics t
  1779. "Non-nil means TODO statistics covers just direct children.
  1780. When nil, all entries in the subtree are considered.
  1781. This has only an effect if `org-provide-todo-statistics' is set.
  1782. To set this to nil for only a single subtree, use a COOKIE_DATA
  1783. property and include the word \"recursive\" into the value."
  1784. :group 'org-todo
  1785. :type 'boolean)
  1786. (defcustom org-after-todo-state-change-hook nil
  1787. "Hook which is run after the state of a TODO item was changed.
  1788. The new state (a string with a TODO keyword, or nil) is available in the
  1789. Lisp variable `org-state'."
  1790. :group 'org-todo
  1791. :type 'hook)
  1792. (defvar org-blocker-hook nil
  1793. "Hook for functions that are allowed to block a state change.
  1794. Functions in this hook should not modify the buffer.
  1795. Each function gets as its single argument a property list,
  1796. see `org-trigger-hook' for more information about this list.
  1797. If any of the functions in this hook returns nil, the state change
  1798. is blocked.")
  1799. (defvar org-trigger-hook nil
  1800. "Hook for functions that are triggered by a state change.
  1801. Each function gets as its single argument a property list with at
  1802. least the following elements:
  1803. (:type type-of-change :position pos-at-entry-start
  1804. :from old-state :to new-state)
  1805. Depending on the type, more properties may be present.
  1806. This mechanism is currently implemented for:
  1807. TODO state changes
  1808. ------------------
  1809. :type todo-state-change
  1810. :from previous state (keyword as a string), or nil, or a symbol
  1811. `todo' or `done', to indicate the general type of state.
  1812. :to new state, like in :from")
  1813. (defcustom org-enforce-todo-dependencies nil
  1814. "Non-nil means undone TODO entries will block switching the parent to DONE.
  1815. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  1816. be blocked if any prior sibling is not yet done.
  1817. Finally, if the parent is blocked because of ordered siblings of its own,
  1818. the child will also be blocked."
  1819. :set (lambda (var val)
  1820. (set var val)
  1821. (if val
  1822. (add-hook 'org-blocker-hook
  1823. 'org-block-todo-from-children-or-siblings-or-parent)
  1824. (remove-hook 'org-blocker-hook
  1825. 'org-block-todo-from-children-or-siblings-or-parent)))
  1826. :group 'org-todo
  1827. :type 'boolean)
  1828. (defcustom org-enforce-todo-checkbox-dependencies nil
  1829. "Non-nil means unchecked boxes will block switching the parent to DONE.
  1830. When this is nil, checkboxes have no influence on switching TODO states.
  1831. When non-nil, you first need to check off all check boxes before the TODO
  1832. entry can be switched to DONE.
  1833. This variable needs to be set before org.el is loaded, and you need to
  1834. restart Emacs after a change to make the change effective. The only way
  1835. to change it while Emacs is running is through the customize interface."
  1836. :set (lambda (var val)
  1837. (set var val)
  1838. (if val
  1839. (add-hook 'org-blocker-hook
  1840. 'org-block-todo-from-checkboxes)
  1841. (remove-hook 'org-blocker-hook
  1842. 'org-block-todo-from-checkboxes)))
  1843. :group 'org-todo
  1844. :type 'boolean)
  1845. (defcustom org-treat-insert-todo-heading-as-state-change nil
  1846. "Non-nil means inserting a TODO heading is treated as state change.
  1847. So when the command `\\[org-insert-todo-heading]' is used, state change
  1848. logging will apply if appropriate. When nil, the new TODO item will
  1849. be inserted directly, and no logging will take place."
  1850. :group 'org-todo
  1851. :type 'boolean)
  1852. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  1853. "Non-nil means switching TODO states with S-cursor counts as state change.
  1854. This is the default behavior. However, setting this to nil allows a
  1855. convenient way to select a TODO state and bypass any logging associated
  1856. with that."
  1857. :group 'org-todo
  1858. :type 'boolean)
  1859. (defcustom org-todo-state-tags-triggers nil
  1860. "Tag changes that should be triggered by TODO state changes.
  1861. This is a list. Each entry is
  1862. (state-change (tag . flag) .......)
  1863. State-change can be a string with a state, and empty string to indicate the
  1864. state that has no TODO keyword, or it can be one of the symbols `todo'
  1865. or `done', meaning any not-done or done state, respectively."
  1866. :group 'org-todo
  1867. :group 'org-tags
  1868. :type '(repeat
  1869. (cons (choice :tag "When changing to"
  1870. (const :tag "Not-done state" todo)
  1871. (const :tag "Done state" done)
  1872. (string :tag "State"))
  1873. (repeat
  1874. (cons :tag "Tag action"
  1875. (string :tag "Tag")
  1876. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  1877. (defcustom org-log-done nil
  1878. "Information to record when a task moves to the DONE state.
  1879. Possible values are:
  1880. nil Don't add anything, just change the keyword
  1881. time Add a time stamp to the task
  1882. note Prompt for a note and add it with template `org-log-note-headings'
  1883. This option can also be set with on a per-file-basis with
  1884. #+STARTUP: nologdone
  1885. #+STARTUP: logdone
  1886. #+STARTUP: lognotedone
  1887. You can have local logging settings for a subtree by setting the LOGGING
  1888. property to one or more of these keywords."
  1889. :group 'org-todo
  1890. :group 'org-progress
  1891. :type '(choice
  1892. (const :tag "No logging" nil)
  1893. (const :tag "Record CLOSED timestamp" time)
  1894. (const :tag "Record CLOSED timestamp with note." note)))
  1895. ;; Normalize old uses of org-log-done.
  1896. (cond
  1897. ((eq org-log-done t) (setq org-log-done 'time))
  1898. ((and (listp org-log-done) (memq 'done org-log-done))
  1899. (setq org-log-done 'note)))
  1900. (defcustom org-log-reschedule nil
  1901. "Information to record when the scheduling date of a task is modified.
  1902. Possible values are:
  1903. nil Don't add anything, just change the date
  1904. time Add a time stamp to the task
  1905. note Prompt for a note and add it with template `org-log-note-headings'
  1906. This option can also be set with on a per-file-basis with
  1907. #+STARTUP: nologreschedule
  1908. #+STARTUP: logreschedule
  1909. #+STARTUP: lognotereschedule
  1910. You can have local logging settings for a subtree by setting the LOGGING
  1911. property to one or more of these keywords.
  1912. This variable has an effect when calling `org-schedule' or
  1913. `org-agenda-schedule' only."
  1914. :group 'org-todo
  1915. :group 'org-progress
  1916. :type '(choice
  1917. (const :tag "No logging" nil)
  1918. (const :tag "Record timestamp" time)
  1919. (const :tag "Record timestamp with note" note)))
  1920. (defcustom org-log-redeadline nil
  1921. "Information to record when the deadline date of a task is modified.
  1922. Possible values are:
  1923. nil Don't add anything, just change the date
  1924. time Add a time stamp to the task
  1925. note Prompt for a note and add it with template `org-log-note-headings'
  1926. This option can also be set with on a per-file-basis with
  1927. #+STARTUP: nologredeadline
  1928. #+STARTUP: logredeadline
  1929. #+STARTUP: lognoteredeadline
  1930. You can have local logging settings for a subtree by setting the LOGGING
  1931. property to one or more of these keywords.
  1932. This variable has an effect when calling `org-deadline' or
  1933. `org-agenda-deadline' only."
  1934. :group 'org-todo
  1935. :group 'org-progress
  1936. :type '(choice
  1937. (const :tag "No logging" nil)
  1938. (const :tag "Record timestamp" time)
  1939. (const :tag "Record timestamp with note." note)))
  1940. (defcustom org-log-note-clock-out nil
  1941. "Non-nil means record a note when clocking out of an item.
  1942. This can also be configured on a per-file basis by adding one of
  1943. the following lines anywhere in the buffer:
  1944. #+STARTUP: lognoteclock-out
  1945. #+STARTUP: nolognoteclock-out"
  1946. :group 'org-todo
  1947. :group 'org-progress
  1948. :type 'boolean)
  1949. (defcustom org-log-done-with-time t
  1950. "Non-nil means the CLOSED time stamp will contain date and time.
  1951. When nil, only the date will be recorded."
  1952. :group 'org-progress
  1953. :type 'boolean)
  1954. (defcustom org-log-note-headings
  1955. '((done . "CLOSING NOTE %t")
  1956. (state . "State %-12s from %-12S %t")
  1957. (note . "Note taken on %t")
  1958. (reschedule . "Rescheduled from %S on %t")
  1959. (delschedule . "Not scheduled, was %S on %t")
  1960. (redeadline . "New deadline from %S on %t")
  1961. (deldeadline . "Removed deadline, was %S on %t")
  1962. (refile . "Refiled on %t")
  1963. (clock-out . ""))
  1964. "Headings for notes added to entries.
  1965. The value is an alist, with the car being a symbol indicating the
  1966. note context, and the cdr is the heading to be used. The heading
  1967. may also be the empty string. The following placeholders can be
  1968. used:
  1969. %t a time stamp.
  1970. %T an active time stamp instead the default inactive one
  1971. %d a short-format time stamp.
  1972. %D an active short-format time stamp.
  1973. %s the new TODO state or time stamp (inactive), in double quotes.
  1974. %S the old TODO state or time stamp (inactive), in double quotes.
  1975. %u the user name.
  1976. %U full user name.
  1977. In fact, it is not a good idea to change the `state' entry,
  1978. because Agenda Log mode depends on the format of these entries."
  1979. :group 'org-todo
  1980. :group 'org-progress
  1981. :type '(list :greedy t
  1982. (cons (const :tag "Heading when closing an item" done) string)
  1983. (cons (const :tag
  1984. "Heading when changing todo state (todo sequence only)"
  1985. state) string)
  1986. (cons (const :tag "Heading when just taking a note" note) string)
  1987. (cons (const :tag "Heading when rescheduling" reschedule) string)
  1988. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  1989. (cons (const :tag "Heading when changing deadline" redeadline) string)
  1990. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  1991. (cons (const :tag "Heading when refiling" refile) string)
  1992. (cons (const :tag "Heading when clocking out" clock-out) string)))
  1993. (unless (assq 'note org-log-note-headings)
  1994. (push '(note . "%t") org-log-note-headings))
  1995. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  1996. (defcustom org-log-into-drawer nil
  1997. "Non-nil means insert state change notes and time stamps into a drawer.
  1998. When nil, state changes notes will be inserted after the headline and
  1999. any scheduling and clock lines, but not inside a drawer.
  2000. The value of this variable should be the name of the drawer to use.
  2001. LOGBOOK is proposed as the default drawer for this purpose, you can
  2002. also set this to a string to define the drawer of your choice.
  2003. A value of t is also allowed, representing \"LOGBOOK\".
  2004. A value of t or nil can also be set with on a per-file-basis with
  2005. #+STARTUP: logdrawer
  2006. #+STARTUP: nologdrawer
  2007. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2008. will be ignored.
  2009. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2010. a subtree.
  2011. Do not check directly this variable in a Lisp program. Call
  2012. function `org-log-into-drawer' instead."
  2013. :group 'org-todo
  2014. :group 'org-progress
  2015. :type '(choice
  2016. (const :tag "Not into a drawer" nil)
  2017. (const :tag "LOGBOOK" t)
  2018. (string :tag "Other")))
  2019. (defun org-log-into-drawer ()
  2020. "Name of the log drawer, as a string, or nil.
  2021. This is the value of `org-log-into-drawer'. However, if the
  2022. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2023. be used instead of the default value."
  2024. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2025. (cond ((equal p "nil") nil)
  2026. ((equal p "t") "LOGBOOK")
  2027. ((stringp p) p)
  2028. (p "LOGBOOK")
  2029. ((stringp org-log-into-drawer) org-log-into-drawer)
  2030. (org-log-into-drawer "LOGBOOK"))))
  2031. (defcustom org-log-state-notes-insert-after-drawers nil
  2032. "Non-nil means insert state change notes after any drawers in entry.
  2033. Only the drawers that *immediately* follow the headline and the
  2034. deadline/scheduled line are skipped.
  2035. When nil, insert notes right after the heading and perhaps the line
  2036. with deadline/scheduling if present.
  2037. This variable will have no effect if `org-log-into-drawer' is
  2038. set."
  2039. :group 'org-todo
  2040. :group 'org-progress
  2041. :type 'boolean)
  2042. (defcustom org-log-states-order-reversed t
  2043. "Non-nil means the latest state note will be directly after heading.
  2044. When nil, the state change notes will be ordered according to time.
  2045. This option can also be set with on a per-file-basis with
  2046. #+STARTUP: logstatesreversed
  2047. #+STARTUP: nologstatesreversed"
  2048. :group 'org-todo
  2049. :group 'org-progress
  2050. :type 'boolean)
  2051. (defcustom org-todo-repeat-to-state nil
  2052. "The TODO state to which a repeater should return the repeating task.
  2053. By default this is the first task of a TODO sequence or the
  2054. previous state of a TYPE_TODO set. But you can specify to use
  2055. the previous state in a TODO sequence or a string.
  2056. Alternatively, you can set the :REPEAT_TO_STATE: property of the
  2057. entry, which has precedence over this option."
  2058. :group 'org-todo
  2059. :version "24.1"
  2060. :type '(choice (const :tag "Use the previous TODO state" t)
  2061. (const :tag "Use the head of the TODO sequence" nil)
  2062. (string :tag "Use a specific TODO state")))
  2063. (defcustom org-log-repeat 'time
  2064. "Non-nil means record moving through the DONE state when triggering repeat.
  2065. An auto-repeating task is immediately switched back to TODO when
  2066. marked DONE. If you are not logging state changes (by adding \"@\"
  2067. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2068. record a closing note, there will be no record of the task moving
  2069. through DONE. This variable forces taking a note anyway.
  2070. nil Don't force a record
  2071. time Record a time stamp
  2072. note Prompt for a note and add it with template `org-log-note-headings'
  2073. This option can also be set with on a per-file-basis with
  2074. #+STARTUP: nologrepeat
  2075. #+STARTUP: logrepeat
  2076. #+STARTUP: lognoterepeat
  2077. You can have local logging settings for a subtree by setting the LOGGING
  2078. property to one or more of these keywords."
  2079. :group 'org-todo
  2080. :group 'org-progress
  2081. :type '(choice
  2082. (const :tag "Don't force a record" nil)
  2083. (const :tag "Force recording the DONE state" time)
  2084. (const :tag "Force recording a note with the DONE state" note)))
  2085. (defcustom org-todo-repeat-hook nil
  2086. "Hook that is run after a task has been repeated."
  2087. :package-version '(Org . "9.2")
  2088. :group 'org-todo
  2089. :type 'hook)
  2090. (defgroup org-priorities nil
  2091. "Priorities in Org mode."
  2092. :tag "Org Priorities"
  2093. :group 'org-todo)
  2094. (defvaralias 'org-enable-priority-commands 'org-priority-enable-commands)
  2095. (defcustom org-priority-enable-commands t
  2096. "Non-nil means priority commands are active.
  2097. When nil, these commands will be disabled, so that you never accidentally
  2098. set a priority."
  2099. :group 'org-priorities
  2100. :type 'boolean)
  2101. (defvaralias 'org-highest-priority 'org-priority-highest)
  2102. (defcustom org-priority-highest ?A
  2103. "The highest priority of TODO items.
  2104. A character like ?A, ?B, etc., or a numeric value like 1, 2, etc.
  2105. The default is the character ?A, which is 65 as a numeric value.
  2106. If you set `org-priority-highest' to a numeric value inferior to
  2107. 65, Org assumes you want to use digits for the priority cookie.
  2108. If you set it to >=65, Org assumes you want to use alphabetical
  2109. characters.
  2110. In both cases, the value of `org-priority-highest' must be
  2111. smaller than `org-priority-lowest': for example, if \"A\" is the
  2112. highest priority, it is smaller than the lowest \"C\" priority:
  2113. 65 < 67."
  2114. :group 'org-priorities
  2115. :type '(choice
  2116. (character :tag "Character")
  2117. (integer :tag "Integer (< 65)")))
  2118. (defvaralias 'org-lowest-priority 'org-priority-lowest)
  2119. (defcustom org-priority-lowest ?C
  2120. "The lowest priority of TODO items.
  2121. A character like ?C, ?B, etc., or a numeric value like 9, 8, etc.
  2122. The default is the character ?C, which is 67 as a numeric value.
  2123. If you set `org-priority-lowest' to a numeric value inferior to
  2124. 65, Org assumes you want to use digits for the priority cookie.
  2125. If you set it to >=65, Org assumes you want to use alphabetical
  2126. characters.
  2127. In both cases, the value of `org-priority-lowest' must be greater
  2128. than `org-priority-highest': for example, if \"C\" is the lowest
  2129. priority, it is greater than the highest \"A\" priority: 67 >
  2130. 65."
  2131. :group 'org-priorities
  2132. :type '(choice
  2133. (character :tag "Character")
  2134. (integer :tag "Integer (< 65)")))
  2135. (defvaralias 'org-default-priority 'org-priority-default)
  2136. (defcustom org-priority-default ?B
  2137. "The default priority of TODO items.
  2138. This is the priority an item gets if no explicit priority is given.
  2139. When starting to cycle on an empty priority the first step in the cycle
  2140. depends on `org-priority-start-cycle-with-default'. The resulting first
  2141. step priority must not exceed the range from `org-priority-highest' to
  2142. `org-priority-lowest' which means that `org-priority-default' has to be
  2143. in this range exclusive or inclusive to the range boundaries. Else the
  2144. first step refuses to set the default and the second will fall back on
  2145. \(depending on the command used) the highest or lowest priority."
  2146. :group 'org-priorities
  2147. :type '(choice
  2148. (character :tag "Character")
  2149. (integer :tag "Integer (< 65)")))
  2150. (defcustom org-priority-start-cycle-with-default t
  2151. "Non-nil means start with default priority when starting to cycle.
  2152. When this is nil, the first step in the cycle will be (depending on the
  2153. command used) one higher or lower than the default priority.
  2154. See also `org-priority-default'."
  2155. :group 'org-priorities
  2156. :type 'boolean)
  2157. (defvaralias 'org-get-priority-function 'org-priority-get-priority-function)
  2158. (defcustom org-priority-get-priority-function nil
  2159. "Function to extract the priority from a string.
  2160. The string is normally the headline. If this is nil, Org
  2161. computes the priority from the priority cookie like [#A] in the
  2162. headline. It returns an integer, increasing by 1000 for each
  2163. priority level.
  2164. The user can set a different function here, which should take a
  2165. string as an argument and return the numeric priority."
  2166. :group 'org-priorities
  2167. :version "24.1"
  2168. :type '(choice
  2169. (const nil)
  2170. (function)))
  2171. (defgroup org-time nil
  2172. "Options concerning time stamps and deadlines in Org mode."
  2173. :tag "Org Time"
  2174. :group 'org)
  2175. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2176. "Number of minutes to round time stamps to.
  2177. \\<org-mode-map>\
  2178. These are two values, the first applies when first creating a time stamp.
  2179. The second applies when changing it with the commands `S-up' and `S-down'.
  2180. When changing the time stamp, this means that it will change in steps
  2181. of N minutes, as given by the second value.
  2182. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2183. numbers should be factors of 60, so for example 5, 10, 15.
  2184. When this is larger than 1, you can still force an exact time stamp by using
  2185. a double prefix argument to a time stamp command like \
  2186. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2187. and by using a prefix arg to `S-up/down' to specify the exact number
  2188. of minutes to shift."
  2189. :group 'org-time
  2190. :get (lambda (var) ; Make sure both elements are there
  2191. (if (integerp (default-value var))
  2192. (list (default-value var) 5)
  2193. (default-value var)))
  2194. :type '(list
  2195. (integer :tag "when inserting times")
  2196. (integer :tag "when modifying times")))
  2197. ;; Normalize old customizations of this variable.
  2198. (when (integerp org-time-stamp-rounding-minutes)
  2199. (setq org-time-stamp-rounding-minutes
  2200. (list org-time-stamp-rounding-minutes
  2201. org-time-stamp-rounding-minutes)))
  2202. (defcustom org-display-custom-times nil
  2203. "Non-nil means overlay custom formats over all time stamps.
  2204. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2205. To turn this on on a per-file basis, insert anywhere in the file:
  2206. #+STARTUP: customtime"
  2207. :group 'org-time
  2208. :set 'set-default
  2209. :type 'sexp)
  2210. (make-variable-buffer-local 'org-display-custom-times)
  2211. (defcustom org-time-stamp-custom-formats
  2212. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2213. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2214. These are overlaid over the default ISO format if the variable
  2215. `org-display-custom-times' is set. Time like %H:%M should be at the
  2216. end of the second format. The custom formats are also honored by export
  2217. commands, if custom time display is turned on at the time of export."
  2218. :group 'org-time
  2219. :type 'sexp)
  2220. (defun org-time-stamp-format (&optional long inactive)
  2221. "Get the right format for a time string."
  2222. (let ((f (if long (cdr org-time-stamp-formats)
  2223. (car org-time-stamp-formats))))
  2224. (if inactive
  2225. (concat "[" (substring f 1 -1) "]")
  2226. f)))
  2227. (defcustom org-deadline-warning-days 14
  2228. "Number of days before expiration during which a deadline becomes active.
  2229. This variable governs the display in sparse trees and in the agenda.
  2230. When 0 or negative, it means use this number (the absolute value of it)
  2231. even if a deadline has a different individual lead time specified.
  2232. Custom commands can set this variable in the options section."
  2233. :group 'org-time
  2234. :group 'org-agenda-daily/weekly
  2235. :type 'integer)
  2236. (defcustom org-scheduled-delay-days 0
  2237. "Number of days before a scheduled item becomes active.
  2238. This variable governs the display in sparse trees and in the agenda.
  2239. The default value (i.e. 0) means: don't delay scheduled item.
  2240. When negative, it means use this number (the absolute value of it)
  2241. even if a scheduled item has a different individual delay time
  2242. specified.
  2243. Custom commands can set this variable in the options section."
  2244. :group 'org-time
  2245. :group 'org-agenda-daily/weekly
  2246. :version "24.4"
  2247. :package-version '(Org . "8.0")
  2248. :type 'integer)
  2249. (defcustom org-read-date-prefer-future t
  2250. "Non-nil means assume future for incomplete date input from user.
  2251. This affects the following situations:
  2252. 1. The user gives a month but not a year.
  2253. For example, if it is April and you enter \"feb 2\", this will be read
  2254. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2255. 2. The user gives a day, but no month.
  2256. For example, if today is the 15th, and you enter \"3\", Org will read
  2257. this as the third of *next* month. However, if you enter \"17\",
  2258. it will be considered as *this* month.
  2259. If you set this variable to the symbol `time', then also the following
  2260. will work:
  2261. 3. If the user gives a time.
  2262. If the time is before now, it will be interpreted as tomorrow.
  2263. Currently none of this works for ISO week specifications.
  2264. When this option is nil, the current day, month and year will always be
  2265. used as defaults.
  2266. See also `org-agenda-jump-prefer-future'."
  2267. :group 'org-time
  2268. :type '(choice
  2269. (const :tag "Never" nil)
  2270. (const :tag "Check month and day" t)
  2271. (const :tag "Check month, day, and time" time)))
  2272. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2273. "Should the agenda jump command prefer the future for incomplete dates?
  2274. The default is to do the same as configured in `org-read-date-prefer-future'.
  2275. But you can also set a deviating value here.
  2276. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2277. :group 'org-agenda
  2278. :group 'org-time
  2279. :version "24.1"
  2280. :type '(choice
  2281. (const :tag "Use org-read-date-prefer-future"
  2282. org-read-date-prefer-future)
  2283. (const :tag "Never" nil)
  2284. (const :tag "Always" t)))
  2285. (defcustom org-read-date-force-compatible-dates t
  2286. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2287. Depending on the system Emacs is running on, certain dates cannot
  2288. be represented with the type used internally to represent time.
  2289. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2290. correctly. Some systems allow for earlier dates, some for later,
  2291. some for both. One way to find out is to insert any date into an
  2292. Org buffer, putting the cursor on the year and hitting S-up and
  2293. S-down to test the range.
  2294. When this variable is set to t, the date/time prompt will not let
  2295. you specify dates outside the 1970-2037 range, so it is certain that
  2296. these dates will work in whatever version of Emacs you are
  2297. running, and also that you can move a file from one Emacs implementation
  2298. to another. Whenever Org is forcing the year for you, it will display
  2299. a message and beep.
  2300. When this variable is nil, Org will check if the date is
  2301. representable in the specific Emacs implementation you are using.
  2302. If not, it will force a year, usually the current year, and beep
  2303. to remind you. Currently this setting is not recommended because
  2304. the likelihood that you will open your Org files in an Emacs that
  2305. has limited date range is not negligible.
  2306. A workaround for this problem is to use diary sexp dates for time
  2307. stamps outside of this range."
  2308. :group 'org-time
  2309. :version "24.1"
  2310. :type 'boolean)
  2311. (defcustom org-read-date-display-live t
  2312. "Non-nil means display current interpretation of date prompt live.
  2313. This display will be in an overlay, in the minibuffer. Note that
  2314. live display is only active when `org-read-date-popup-calendar'
  2315. is non-nil."
  2316. :group 'org-time
  2317. :type 'boolean)
  2318. (defvaralias 'org-popup-calendar-for-date-prompt
  2319. 'org-read-date-popup-calendar)
  2320. (defcustom org-read-date-popup-calendar t
  2321. "Non-nil means pop up a calendar when prompting for a date.
  2322. In the calendar, the date can be selected with mouse-1. However, the
  2323. minibuffer will also be active, and you can simply enter the date as well.
  2324. When nil, only the minibuffer will be available."
  2325. :group 'org-time
  2326. :type 'boolean)
  2327. (defcustom org-extend-today-until 0
  2328. "The hour when your day really ends. Must be an integer.
  2329. This has influence for the following applications:
  2330. - When switching the agenda to \"today\". If it is still earlier than
  2331. the time given here, the day recognized as TODAY is actually yesterday.
  2332. - When a date is read from the user and it is still before the time given
  2333. here, the current date and time will be assumed to be yesterday, 23:59.
  2334. Also, timestamps inserted in capture templates follow this rule.
  2335. IMPORTANT: This is a feature whose implementation is and likely will
  2336. remain incomplete. Really, it is only here because past midnight seems to
  2337. be the favorite working time of John Wiegley :-)"
  2338. :group 'org-time
  2339. :type 'integer)
  2340. (defcustom org-use-effective-time nil
  2341. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2342. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2343. \"effective time\" of any timestamps between midnight and 8am will be
  2344. 23:59 of the previous day."
  2345. :group 'org-time
  2346. :version "24.1"
  2347. :type 'boolean)
  2348. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2349. "When non-nil, use the last clock out time for `org-todo'.
  2350. Note that this option has precedence over the combined use of
  2351. `org-use-effective-time' and `org-extend-today-until'."
  2352. :group 'org-time
  2353. :version "24.4"
  2354. :package-version '(Org . "8.0")
  2355. :type 'boolean)
  2356. (defcustom org-edit-timestamp-down-means-later nil
  2357. "Non-nil means S-down will increase the time in a time stamp.
  2358. When nil, S-up will increase."
  2359. :group 'org-time
  2360. :type 'boolean)
  2361. (defcustom org-calendar-follow-timestamp-change t
  2362. "Non-nil means make the calendar window follow timestamp changes.
  2363. When a timestamp is modified and the calendar window is visible, it will be
  2364. moved to the new date."
  2365. :group 'org-time
  2366. :type 'boolean)
  2367. (defgroup org-tags nil
  2368. "Options concerning tags in Org mode."
  2369. :tag "Org Tags"
  2370. :group 'org)
  2371. (defcustom org-tag-alist nil
  2372. "Default tags available in Org files.
  2373. The value of this variable is an alist. Associations either:
  2374. (TAG)
  2375. (TAG . SELECT)
  2376. (SPECIAL)
  2377. where TAG is a tag as a string, SELECT is character, used to
  2378. select that tag through the fast tag selection interface, and
  2379. SPECIAL is one of the following keywords: `:startgroup',
  2380. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2381. `:newline'. These keywords are used to define a hierarchy of
  2382. tags. See manual for details.
  2383. When this variable is nil, Org mode bases tag input on what is
  2384. already in the buffer. The value can be overridden locally by
  2385. using a TAGS keyword, e.g.,
  2386. #+TAGS: tag1 tag2
  2387. See also `org-tag-persistent-alist' to sidestep this behavior."
  2388. :group 'org-tags
  2389. :type '(repeat
  2390. (choice
  2391. (cons :tag "Tag with key"
  2392. (string :tag "Tag name")
  2393. (character :tag "Access char"))
  2394. (list :tag "Tag" (string :tag "Tag name"))
  2395. (const :tag "Start radio group" (:startgroup))
  2396. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2397. (const :tag "Group tags delimiter" (:grouptags))
  2398. (const :tag "End radio group" (:endgroup))
  2399. (const :tag "End tag group, non distinct" (:endgrouptag))
  2400. (const :tag "New line" (:newline)))))
  2401. (defcustom org-tag-persistent-alist nil
  2402. "Tags always available in Org files.
  2403. The value of this variable is an alist. Associations either:
  2404. (TAG)
  2405. (TAG . SELECT)
  2406. (SPECIAL)
  2407. where TAG is a tag as a string, SELECT is a character, used to
  2408. select that tag through the fast tag selection interface, and
  2409. SPECIAL is one of the following keywords: `:startgroup',
  2410. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2411. `:newline'. These keywords are used to define a hierarchy of
  2412. tags. See manual for details.
  2413. Unlike to `org-tag-alist', tags defined in this variable do not
  2414. depend on a local TAGS keyword. Instead, to disable these tags
  2415. on a per-file basis, insert anywhere in the file:
  2416. #+STARTUP: noptag"
  2417. :group 'org-tags
  2418. :type '(repeat
  2419. (choice
  2420. (cons :tag "Tag with key"
  2421. (string :tag "Tag name")
  2422. (character :tag "Access char"))
  2423. (list :tag "Tag" (string :tag "Tag name"))
  2424. (const :tag "Start radio group" (:startgroup))
  2425. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2426. (const :tag "Group tags delimiter" (:grouptags))
  2427. (const :tag "End radio group" (:endgroup))
  2428. (const :tag "End tag group, non distinct" (:endgrouptag))
  2429. (const :tag "New line" (:newline)))))
  2430. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2431. "If non-nil, always offer completion for all tags of all agenda files.
  2432. Setting this variable locally allows for dynamic generation of tag
  2433. completions in capture buffers.
  2434. (add-hook \\='org-capture-mode-hook
  2435. (lambda ()
  2436. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  2437. :group 'org-tags
  2438. :version "24.1"
  2439. :type 'boolean)
  2440. (defvar org-file-tags nil
  2441. "List of tags that can be inherited by all entries in the file.
  2442. The tags will be inherited if the variable `org-use-tag-inheritance'
  2443. says they should be.
  2444. This variable is populated from #+FILETAGS lines.")
  2445. (defcustom org-use-fast-tag-selection 'auto
  2446. "Non-nil means use fast tag selection scheme.
  2447. This is a special interface to select and deselect tags with single keys.
  2448. When nil, fast selection is never used.
  2449. When the symbol `auto', fast selection is used if and only if selection
  2450. characters for tags have been configured, either through the variable
  2451. `org-tag-alist' or through a #+TAGS line in the buffer.
  2452. When t, fast selection is always used and selection keys are assigned
  2453. automatically if necessary."
  2454. :group 'org-tags
  2455. :type '(choice
  2456. (const :tag "Always" t)
  2457. (const :tag "Never" nil)
  2458. (const :tag "When selection characters are configured" auto)))
  2459. (defcustom org-fast-tag-selection-single-key nil
  2460. "Non-nil means fast tag selection exits after first change.
  2461. When nil, you have to press RET to exit it.
  2462. During fast tag selection, you can toggle this flag with `C-c'.
  2463. This variable can also have the value `expert'. In this case, the window
  2464. displaying the tags menu is not even shown, until you press `C-c' again."
  2465. :group 'org-tags
  2466. :type '(choice
  2467. (const :tag "No" nil)
  2468. (const :tag "Yes" t)
  2469. (const :tag "Expert" expert)))
  2470. (defvar org-fast-tag-selection-include-todo nil
  2471. "Non-nil means fast tags selection interface will also offer TODO states.
  2472. This is an undocumented feature, you should not rely on it.")
  2473. (defcustom org-tags-column -77
  2474. "The column to which tags should be indented in a headline.
  2475. If this number is positive, it specifies the column. If it is negative,
  2476. it means that the tags should be flushright to that column. For example,
  2477. -80 works well for a normal 80 character screen.
  2478. When 0, place tags directly after headline text, with only one space in
  2479. between."
  2480. :group 'org-tags
  2481. :type 'integer)
  2482. (defcustom org-auto-align-tags t
  2483. "Non-nil keeps tags aligned when modifying headlines.
  2484. Some operations (i.e. demoting) change the length of a headline and
  2485. therefore shift the tags around. With this option turned on, after
  2486. each such operation the tags are again aligned to `org-tags-column'."
  2487. :group 'org-tags
  2488. :type 'boolean)
  2489. (defcustom org-use-tag-inheritance t
  2490. "Non-nil means tags in levels apply also for sublevels.
  2491. When nil, only the tags directly given in a specific line apply there.
  2492. This may also be a list of tags that should be inherited, or a regexp that
  2493. matches tags that should be inherited. Additional control is possible
  2494. with the variable `org-tags-exclude-from-inheritance' which gives an
  2495. explicit list of tags to be excluded from inheritance, even if the value of
  2496. `org-use-tag-inheritance' would select it for inheritance.
  2497. If this option is t, a match early-on in a tree can lead to a large
  2498. number of matches in the subtree when constructing the agenda or creating
  2499. a sparse tree. If you only want to see the first match in a tree during
  2500. a search, check out the variable `org-tags-match-list-sublevels'."
  2501. :group 'org-tags
  2502. :type '(choice
  2503. (const :tag "Not" nil)
  2504. (const :tag "Always" t)
  2505. (repeat :tag "Specific tags" (string :tag "Tag"))
  2506. (regexp :tag "Tags matched by regexp")))
  2507. (defcustom org-tags-exclude-from-inheritance nil
  2508. "List of tags that should never be inherited.
  2509. This is a way to exclude a few tags from inheritance. For way to do
  2510. the opposite, to actively allow inheritance for selected tags,
  2511. see the variable `org-use-tag-inheritance'."
  2512. :group 'org-tags
  2513. :type '(repeat (string :tag "Tag")))
  2514. (defun org-tag-inherit-p (tag)
  2515. "Check if TAG is one that should be inherited."
  2516. (cond
  2517. ((member tag org-tags-exclude-from-inheritance) nil)
  2518. ((eq org-use-tag-inheritance t) t)
  2519. ((not org-use-tag-inheritance) nil)
  2520. ((stringp org-use-tag-inheritance)
  2521. (string-match org-use-tag-inheritance tag))
  2522. ((listp org-use-tag-inheritance)
  2523. (member tag org-use-tag-inheritance))
  2524. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  2525. (defcustom org-tags-match-list-sublevels t
  2526. "Non-nil means list also sublevels of headlines matching a search.
  2527. This variable applies to tags/property searches, and also to stuck
  2528. projects because this search is based on a tags match as well.
  2529. When set to the symbol `indented', sublevels are indented with
  2530. leading dots.
  2531. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  2532. the sublevels of a headline matching a tag search often also match
  2533. the same search. Listing all of them can create very long lists.
  2534. Setting this variable to nil causes subtrees of a match to be skipped.
  2535. This variable is semi-obsolete and probably should always be true. It
  2536. is better to limit inheritance to certain tags using the variables
  2537. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  2538. :group 'org-tags
  2539. :type '(choice
  2540. (const :tag "No, don't list them" nil)
  2541. (const :tag "Yes, do list them" t)
  2542. (const :tag "List them, indented with leading dots" indented)))
  2543. (defcustom org-tags-sort-function nil
  2544. "When set, tags are sorted using this function as a comparator."
  2545. :group 'org-tags
  2546. :type '(choice
  2547. (const :tag "No sorting" nil)
  2548. (const :tag "Alphabetical" org-string-collate-lessp)
  2549. (const :tag "Reverse alphabetical" org-string-collate-greaterp)
  2550. (function :tag "Custom function" nil)))
  2551. (defvar org-tags-history nil
  2552. "History of minibuffer reads for tags.")
  2553. (defvar org-last-tags-completion-table nil
  2554. "The last used completion table for tags.")
  2555. (defvar org-after-tags-change-hook nil
  2556. "Hook that is run after the tags in a line have changed.")
  2557. (defgroup org-properties nil
  2558. "Options concerning properties in Org mode."
  2559. :tag "Org Properties"
  2560. :group 'org)
  2561. (defcustom org-property-format "%-10s %s"
  2562. "How property key/value pairs should be formatted by `indent-line'.
  2563. When `indent-line' hits a property definition, it will format the line
  2564. according to this format, mainly to make sure that the values are
  2565. lined-up with respect to each other."
  2566. :group 'org-properties
  2567. :type 'string)
  2568. (defcustom org-properties-postprocess-alist nil
  2569. "Alist of properties and functions to adjust inserted values.
  2570. Elements of this alist must be of the form
  2571. ([string] [function])
  2572. where [string] must be a property name and [function] must be a
  2573. lambda expression: this lambda expression must take one argument,
  2574. the value to adjust, and return the new value as a string.
  2575. For example, this element will allow the property \"Remaining\"
  2576. to be updated wrt the relation between the \"Effort\" property
  2577. and the clock summary:
  2578. ((\"Remaining\" (lambda(value)
  2579. (let ((clocksum (org-clock-sum-current-item))
  2580. (effort (org-duration-to-minutes
  2581. (org-entry-get (point) \"Effort\"))))
  2582. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  2583. :group 'org-properties
  2584. :version "24.1"
  2585. :type '(alist :key-type (string :tag "Property")
  2586. :value-type (function :tag "Function")))
  2587. (defcustom org-use-property-inheritance nil
  2588. "Non-nil means properties apply also for sublevels.
  2589. This setting is chiefly used during property searches. Turning it on can
  2590. cause significant overhead when doing a search, which is why it is not
  2591. on by default.
  2592. When nil, only the properties directly given in the current entry count.
  2593. When t, every property is inherited. The value may also be a list of
  2594. properties that should have inheritance, or a regular expression matching
  2595. properties that should be inherited.
  2596. However, note that some special properties use inheritance under special
  2597. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  2598. and the properties ending in \"_ALL\" when they are used as descriptor
  2599. for valid values of a property.
  2600. Note for programmers:
  2601. When querying an entry with `org-entry-get', you can control if inheritance
  2602. should be used. By default, `org-entry-get' looks only at the local
  2603. properties. You can request inheritance by setting the inherit argument
  2604. to t (to force inheritance) or to `selective' (to respect the setting
  2605. in this variable)."
  2606. :group 'org-properties
  2607. :type '(choice
  2608. (const :tag "Not" nil)
  2609. (const :tag "Always" t)
  2610. (repeat :tag "Specific properties" (string :tag "Property"))
  2611. (regexp :tag "Properties matched by regexp")))
  2612. (defun org-property-inherit-p (property)
  2613. "Return a non-nil value if PROPERTY should be inherited."
  2614. (cond
  2615. ((eq org-use-property-inheritance t) t)
  2616. ((not org-use-property-inheritance) nil)
  2617. ((stringp org-use-property-inheritance)
  2618. (string-match org-use-property-inheritance property))
  2619. ((listp org-use-property-inheritance)
  2620. (member-ignore-case property org-use-property-inheritance))
  2621. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  2622. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  2623. "The default column format, if no other format has been defined.
  2624. This variable can be set on the per-file basis by inserting a line
  2625. #+COLUMNS: %25ITEM ....."
  2626. :group 'org-properties
  2627. :type 'string)
  2628. (defcustom org-columns-default-format-for-agenda nil
  2629. "The default column format in an agenda buffer.
  2630. This will be used for column view in the agenda unless a format has
  2631. been set by adding `org-overriding-columns-format' to the local
  2632. settings list of a custom agenda view. When nil, the columns format
  2633. for the first item in the agenda list will be used, or as a fall-back,
  2634. `org-columns-default-format'."
  2635. :group 'org-properties
  2636. :type '(choice
  2637. (const :tag "No default" nil)
  2638. (string :tag "Format string")))
  2639. (defcustom org-columns-ellipses ".."
  2640. "The ellipses to be used when a field in column view is truncated.
  2641. When this is the empty string, as many characters as possible are shown,
  2642. but then there will be no visual indication that the field has been truncated.
  2643. When this is a string of length N, the last N characters of a truncated
  2644. field are replaced by this string. If the column is narrower than the
  2645. ellipses string, only part of the ellipses string will be shown."
  2646. :group 'org-properties
  2647. :type 'string)
  2648. (defconst org-global-properties-fixed
  2649. '(("VISIBILITY_ALL" . "folded children content all")
  2650. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  2651. "List of property/value pairs that can be inherited by any entry.
  2652. These are fixed values, for the preset properties. The user variable
  2653. that can be used to add to this list is `org-global-properties'.
  2654. The entries in this list are cons cells where the car is a property
  2655. name and cdr is a string with the value. If the value represents
  2656. multiple items like an \"_ALL\" property, separate the items by
  2657. spaces.")
  2658. (defcustom org-global-properties nil
  2659. "List of property/value pairs that can be inherited by any entry.
  2660. This list will be combined with the constant `org-global-properties-fixed'.
  2661. The entries in this list are cons cells where the car is a property
  2662. name and cdr is a string with the value.
  2663. Buffer local properties are added either by a document property drawer
  2664. :PROPERTIES:
  2665. :NAME: VALUE
  2666. :END:
  2667. or by adding lines like
  2668. #+PROPERTY: NAME VALUE"
  2669. :group 'org-properties
  2670. :type '(repeat
  2671. (cons (string :tag "Property")
  2672. (string :tag "Value"))))
  2673. (defvar-local org-keyword-properties nil
  2674. "List of property/value pairs inherited by any entry.
  2675. Valid for the current buffer. This variable is populated from
  2676. PROPERTY keywords.
  2677. Note that properties are defined also in property drawers.
  2678. Properties defined there take precedence over properties defined
  2679. as keywords.")
  2680. (defgroup org-agenda nil
  2681. "Options concerning agenda views in Org mode."
  2682. :tag "Org Agenda"
  2683. :group 'org)
  2684. (defvar-local org-category nil
  2685. "Variable used by Org files to set a category for agenda display.
  2686. There are multiple ways to set the category. One way is to set
  2687. it in the document property drawer. For example:
  2688. :PROPERTIES:
  2689. :CATEGORY: ELisp
  2690. :END:
  2691. Other ways to define it is as an Emacs file variable, for example
  2692. # -*- mode: org; org-category: \"ELisp\"
  2693. or for the file to contain a special line:
  2694. #+CATEGORY: ELisp
  2695. If the file does not specify a category, then file's base name
  2696. is used instead.")
  2697. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  2698. (defcustom org-agenda-files nil
  2699. "The files to be used for agenda display.
  2700. If an entry is a directory, all files in that directory that are matched
  2701. by `org-agenda-file-regexp' will be part of the file list.
  2702. If the value of the variable is not a list but a single file name, then
  2703. the list of agenda files is actually stored and maintained in that file,
  2704. one agenda file per line. In this file paths can be given relative to
  2705. `org-directory'. Tilde expansion and environment variable substitution
  2706. are also made.
  2707. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  2708. and removed with `\\[org-remove-file]'."
  2709. :group 'org-agenda
  2710. :type '(choice
  2711. (repeat :tag "List of files and directories" file)
  2712. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  2713. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  2714. "Regular expression to match files for `org-agenda-files'.
  2715. If any element in the list in that variable contains a directory instead
  2716. of a normal file, all files in that directory that are matched by this
  2717. regular expression will be included."
  2718. :group 'org-agenda
  2719. :type 'regexp)
  2720. (defvaralias 'org-agenda-multi-occur-extra-files
  2721. 'org-agenda-text-search-extra-files)
  2722. (defcustom org-agenda-text-search-extra-files nil
  2723. "List of extra files to be searched by text search commands.
  2724. These files will be searched in addition to the agenda files by the
  2725. commands `org-search-view' (`\\[org-agenda] s') \
  2726. and `org-occur-in-agenda-files'.
  2727. Note that these files will only be searched for text search commands,
  2728. not for the other agenda views like todo lists, tag searches or the weekly
  2729. agenda. This variable is intended to list notes and possibly archive files
  2730. that should also be searched by these two commands.
  2731. In fact, if the first element in the list is the symbol `agenda-archives',
  2732. then all archive files of all agenda files will be added to the search
  2733. scope."
  2734. :group 'org-agenda
  2735. :type '(set :greedy t
  2736. (const :tag "Agenda Archives" agenda-archives)
  2737. (repeat :inline t (file))))
  2738. (defcustom org-agenda-skip-unavailable-files nil
  2739. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  2740. A nil value means to remove them, after a query, from the list."
  2741. :group 'org-agenda
  2742. :type 'boolean)
  2743. (defgroup org-latex nil
  2744. "Options for embedding LaTeX code into Org mode."
  2745. :tag "Org LaTeX"
  2746. :group 'org)
  2747. (defcustom org-format-latex-options
  2748. '(:foreground default :background default :scale 1.0
  2749. :html-foreground "Black" :html-background "Transparent"
  2750. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  2751. "Options for creating images from LaTeX fragments.
  2752. This is a property list with the following properties:
  2753. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  2754. `default' means use the foreground of the default face.
  2755. `auto' means use the foreground from the text face.
  2756. :background the background color, or \"Transparent\".
  2757. `default' means use the background of the default face.
  2758. `auto' means use the background from the text face.
  2759. :scale a scaling factor for the size of the images, to get more pixels
  2760. :html-foreground, :html-background, :html-scale
  2761. the same numbers for HTML export.
  2762. :matchers a list indicating which matchers should be used to
  2763. find LaTeX fragments. Valid members of this list are:
  2764. \"begin\" find environments
  2765. \"$1\" find single characters surrounded by $.$
  2766. \"$\" find math expressions surrounded by $...$
  2767. \"$$\" find math expressions surrounded by $$....$$
  2768. \"\\(\" find math expressions surrounded by \\(...\\)
  2769. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  2770. :group 'org-latex
  2771. :type 'plist)
  2772. (defcustom org-format-latex-signal-error t
  2773. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  2774. When nil, just push out a message."
  2775. :group 'org-latex
  2776. :version "24.1"
  2777. :type 'boolean)
  2778. (defcustom org-latex-to-mathml-jar-file nil
  2779. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  2780. Use this to specify additional executable file say a jar file.
  2781. When using MathToWeb as the converter, specify the full-path to
  2782. your mathtoweb.jar file."
  2783. :group 'org-latex
  2784. :version "24.1"
  2785. :type '(choice
  2786. (const :tag "None" nil)
  2787. (file :tag "JAR file" :must-match t)))
  2788. (defcustom org-latex-to-mathml-convert-command nil
  2789. "Command to convert LaTeX fragments to MathML.
  2790. Replace format-specifiers in the command as noted below and use
  2791. `shell-command' to convert LaTeX to MathML.
  2792. %j: Executable file in fully expanded form as specified by
  2793. `org-latex-to-mathml-jar-file'.
  2794. %I: Input LaTeX file in fully expanded form.
  2795. %i: The latex fragment to be converted.
  2796. %o: Output MathML file.
  2797. This command is used by `org-create-math-formula'.
  2798. When using MathToWeb as the converter, set this option to
  2799. \"java -jar %j -unicode -force -df %o %I\".
  2800. When using LaTeXML set this option to
  2801. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  2802. :group 'org-latex
  2803. :version "24.1"
  2804. :type '(choice
  2805. (const :tag "None" nil)
  2806. (string :tag "\nShell command")))
  2807. (defcustom org-latex-to-html-convert-command nil
  2808. "Command to convert LaTeX fragments to HTML.
  2809. This command is very open-ended: the output of the command will
  2810. directly replace the LaTeX fragment in the resulting HTML.
  2811. Replace format-specifiers in the command as noted below and use
  2812. `shell-command' to convert LaTeX to HTML.
  2813. %i: The LaTeX fragment to be converted.
  2814. For example, this could be used with LaTeXML as
  2815. \"latexmlc \\='literal:%i\\=' --profile=math --preload=siunitx.sty 2>/dev/null\"."
  2816. :group 'org-latex
  2817. :package-version '(Org . "9.4")
  2818. :type '(choice
  2819. (const :tag "None" nil)
  2820. (string :tag "Shell command")))
  2821. (defcustom org-preview-latex-default-process 'dvipng
  2822. "The default process to convert LaTeX fragments to image files.
  2823. All available processes and theirs documents can be found in
  2824. `org-preview-latex-process-alist', which see."
  2825. :group 'org-latex
  2826. :version "26.1"
  2827. :package-version '(Org . "9.0")
  2828. :type 'symbol)
  2829. (defcustom org-preview-latex-process-alist
  2830. '((dvipng
  2831. :programs ("latex" "dvipng")
  2832. :description "dvi > png"
  2833. :message "you need to install the programs: latex and dvipng."
  2834. :image-input-type "dvi"
  2835. :image-output-type "png"
  2836. :image-size-adjust (1.0 . 1.0)
  2837. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2838. :image-converter ("dvipng -D %D -T tight -bg Transparent -o %O %f"))
  2839. (dvisvgm
  2840. :programs ("latex" "dvisvgm")
  2841. :description "dvi > svg"
  2842. :message "you need to install the programs: latex and dvisvgm."
  2843. :image-input-type "dvi"
  2844. :image-output-type "svg"
  2845. :image-size-adjust (1.7 . 1.5)
  2846. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2847. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  2848. (imagemagick
  2849. :programs ("latex" "convert")
  2850. :description "pdf > png"
  2851. :message "you need to install the programs: latex and imagemagick."
  2852. :image-input-type "pdf"
  2853. :image-output-type "png"
  2854. :image-size-adjust (1.0 . 1.0)
  2855. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  2856. :image-converter
  2857. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  2858. "Definitions of external processes for LaTeX previewing.
  2859. Org mode can use some external commands to generate TeX snippet's images for
  2860. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  2861. `org-create-formula-image' how to call them.
  2862. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  2863. PROPERTIES accepts the following attributes:
  2864. :programs list of strings, required programs.
  2865. :description string, describe the process.
  2866. :message string, message it when required programs cannot be found.
  2867. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  2868. :image-output-type string, output file type of image converter (e.g., \"png\").
  2869. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  2870. image size showed in buffer and the cdr element is for
  2871. HTML file. This option is only useful for process
  2872. developers, users should use variable
  2873. `org-format-latex-options' instead.
  2874. :post-clean list of strings, files matched are to be cleaned up once
  2875. the image is generated. When nil, the files with \".dvi\",
  2876. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  2877. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  2878. be cleaned up.
  2879. :latex-header list of strings, the LaTeX header of the snippet file.
  2880. When nil, the fallback value is used instead, which is
  2881. controlled by `org-format-latex-header',
  2882. `org-latex-default-packages-alist' and
  2883. `org-latex-packages-alist', which see.
  2884. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  2885. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  2886. replaced with values defined below.
  2887. :image-converter list of image converter commands strings. Each of them is
  2888. given to the shell and supports any of the following
  2889. place-holders defined below.
  2890. Place-holders used by `:image-converter' and `:latex-compiler':
  2891. %f input file name
  2892. %b base name of input file
  2893. %o base directory of input file
  2894. %O absolute output file name
  2895. Place-holders only used by `:image-converter':
  2896. %D dpi, which is used to adjust image size by some processing commands.
  2897. %S the image size scale ratio, which is used to adjust image size by some
  2898. processing commands."
  2899. :group 'org-latex
  2900. :version "26.1"
  2901. :package-version '(Org . "9.0")
  2902. :type '(alist :tag "LaTeX to image backends"
  2903. :value-type (plist)))
  2904. (defcustom org-preview-latex-image-directory "ltximg/"
  2905. "Path to store latex preview images.
  2906. A relative path here creates many directories relative to the
  2907. processed Org files paths. An absolute path puts all preview
  2908. images at the same place."
  2909. :group 'org-latex
  2910. :version "26.1"
  2911. :package-version '(Org . "9.0")
  2912. :type 'string)
  2913. (defun org-format-latex-mathml-available-p ()
  2914. "Return t if `org-latex-to-mathml-convert-command' is usable."
  2915. (save-match-data
  2916. (when (and (boundp 'org-latex-to-mathml-convert-command)
  2917. org-latex-to-mathml-convert-command)
  2918. (let ((executable (car (split-string
  2919. org-latex-to-mathml-convert-command))))
  2920. (when (executable-find executable)
  2921. (if (string-match
  2922. "%j" org-latex-to-mathml-convert-command)
  2923. (file-readable-p org-latex-to-mathml-jar-file)
  2924. t))))))
  2925. (defcustom org-format-latex-header "\\documentclass{article}
  2926. \\usepackage[usenames]{color}
  2927. \[PACKAGES]
  2928. \[DEFAULT-PACKAGES]
  2929. \\pagestyle{empty} % do not remove
  2930. % The settings below are copied from fullpage.sty
  2931. \\setlength{\\textwidth}{\\paperwidth}
  2932. \\addtolength{\\textwidth}{-3cm}
  2933. \\setlength{\\oddsidemargin}{1.5cm}
  2934. \\addtolength{\\oddsidemargin}{-2.54cm}
  2935. \\setlength{\\evensidemargin}{\\oddsidemargin}
  2936. \\setlength{\\textheight}{\\paperheight}
  2937. \\addtolength{\\textheight}{-\\headheight}
  2938. \\addtolength{\\textheight}{-\\headsep}
  2939. \\addtolength{\\textheight}{-\\footskip}
  2940. \\addtolength{\\textheight}{-3cm}
  2941. \\setlength{\\topmargin}{1.5cm}
  2942. \\addtolength{\\topmargin}{-2.54cm}"
  2943. "The document header used for processing LaTeX fragments.
  2944. It is imperative that this header make sure that no page number
  2945. appears on the page. The package defined in the variables
  2946. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  2947. will either replace the placeholder \"[PACKAGES]\" in this
  2948. header, or they will be appended."
  2949. :group 'org-latex
  2950. :type 'string)
  2951. (defun org-set-packages-alist (var val)
  2952. "Set the packages alist and make sure it has 3 elements per entry."
  2953. (set var (mapcar (lambda (x)
  2954. (if (and (consp x) (= (length x) 2))
  2955. (list (car x) (nth 1 x) t)
  2956. x))
  2957. val)))
  2958. (defun org-get-packages-alist (var)
  2959. "Get the packages alist and make sure it has 3 elements per entry."
  2960. (mapcar (lambda (x)
  2961. (if (and (consp x) (= (length x) 2))
  2962. (list (car x) (nth 1 x) t)
  2963. x))
  2964. (default-value var)))
  2965. (defcustom org-latex-default-packages-alist
  2966. '(("AUTO" "inputenc" t ("pdflatex"))
  2967. ("T1" "fontenc" t ("pdflatex"))
  2968. ("" "graphicx" t)
  2969. ("" "longtable" nil)
  2970. ("" "wrapfig" nil)
  2971. ("" "rotating" nil)
  2972. ("normalem" "ulem" t)
  2973. ("" "amsmath" t)
  2974. ("" "amssymb" t)
  2975. ("" "capt-of" nil)
  2976. ("" "hyperref" nil))
  2977. "Alist of default packages to be inserted in the header.
  2978. Change this only if one of the packages here causes an
  2979. incompatibility with another package you are using.
  2980. The packages in this list are needed by one part or another of
  2981. Org mode to function properly:
  2982. - inputenc, fontenc: for basic font and character selection
  2983. - graphicx: for including images
  2984. - longtable: For multipage tables
  2985. - wrapfig: for figure placement
  2986. - rotating: for sideways figures and tables
  2987. - ulem: for underline and strike-through
  2988. - amsmath: for subscript and superscript and math environments
  2989. - amssymb: for various symbols used for interpreting the entities
  2990. in `org-entities'. You can skip some of this package if you don't
  2991. use any of the symbols.
  2992. - capt-of: for captions outside of floats
  2993. - hyperref: for cross references
  2994. Therefore you should not modify this variable unless you know
  2995. what you are doing. The one reason to change it anyway is that
  2996. you might be loading some other package that conflicts with one
  2997. of the default packages. Each element is either a cell or
  2998. a string.
  2999. A cell is of the format
  3000. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3001. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3002. when compiling LaTeX snippets into images for inclusion into
  3003. non-LaTeX output.
  3004. COMPILERS is a list of compilers that should include the package,
  3005. see `org-latex-compiler'. If the document compiler is not in the
  3006. list, and the list is non-nil, the package will not be inserted
  3007. in the final document.
  3008. A string will be inserted as-is in the header of the document."
  3009. :group 'org-latex
  3010. :group 'org-export-latex
  3011. :set 'org-set-packages-alist
  3012. :get 'org-get-packages-alist
  3013. :version "26.1"
  3014. :package-version '(Org . "8.3")
  3015. :type '(repeat
  3016. (choice
  3017. (list :tag "options/package pair"
  3018. (string :tag "options")
  3019. (string :tag "package")
  3020. (boolean :tag "Snippet")
  3021. (choice
  3022. (const :tag "For all compilers" nil)
  3023. (repeat :tag "Allowed compiler" string)))
  3024. (string :tag "A line of LaTeX"))))
  3025. (defcustom org-latex-packages-alist nil
  3026. "Alist of packages to be inserted in every LaTeX header.
  3027. These will be inserted after `org-latex-default-packages-alist'.
  3028. Each element is either a cell or a string.
  3029. A cell is of the format:
  3030. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3031. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3032. needed when turning LaTeX snippets into images for inclusion into
  3033. non-LaTeX output.
  3034. COMPILERS is a list of compilers that should include the package,
  3035. see `org-latex-compiler'. If the document compiler is not in the
  3036. list, and the list is non-nil, the package will not be inserted
  3037. in the final document.
  3038. A string will be inserted as-is in the header of the document.
  3039. Make sure that you only list packages here which:
  3040. - you want in every file;
  3041. - do not conflict with the setup in `org-format-latex-header';
  3042. - do not conflict with the default packages in
  3043. `org-latex-default-packages-alist'."
  3044. :group 'org-latex
  3045. :group 'org-export-latex
  3046. :set 'org-set-packages-alist
  3047. :get 'org-get-packages-alist
  3048. :type '(repeat
  3049. (choice
  3050. (list :tag "options/package pair"
  3051. (string :tag "options")
  3052. (string :tag "package")
  3053. (boolean :tag "Snippet"))
  3054. (string :tag "A line of LaTeX"))))
  3055. (defgroup org-appearance nil
  3056. "Settings for Org mode appearance."
  3057. :tag "Org Appearance"
  3058. :group 'org)
  3059. (defcustom org-level-color-stars-only nil
  3060. "Non-nil means fontify only the stars in each headline.
  3061. When nil, the entire headline is fontified.
  3062. Changing it requires restart of `font-lock-mode' to become effective
  3063. also in regions already fontified."
  3064. :group 'org-appearance
  3065. :type 'boolean)
  3066. (defcustom org-hide-leading-stars nil
  3067. "Non-nil means hide the first N-1 stars in a headline.
  3068. This works by using the face `org-hide' for these stars. This
  3069. face is white for a light background, and black for a dark
  3070. background. You may have to customize the face `org-hide' to
  3071. make this work.
  3072. Changing it requires restart of `font-lock-mode' to become effective
  3073. also in regions already fontified.
  3074. You may also set this on a per-file basis by adding one of the following
  3075. lines to the buffer:
  3076. #+STARTUP: hidestars
  3077. #+STARTUP: showstars"
  3078. :group 'org-appearance
  3079. :type 'boolean)
  3080. (defcustom org-hidden-keywords nil
  3081. "List of symbols corresponding to keywords to be hidden in the Org buffer.
  3082. For example, a value \\='(title) for this list makes the document's title
  3083. appear in the buffer without the initial \"#+TITLE:\" part."
  3084. :group 'org-appearance
  3085. :package-version '(Org . "9.5")
  3086. :type '(set (const :tag "#+AUTHOR" author)
  3087. (const :tag "#+DATE" date)
  3088. (const :tag "#+EMAIL" email)
  3089. (const :tag "#+SUBTITLE" subtitle)
  3090. (const :tag "#+TITLE" title)))
  3091. (defcustom org-custom-properties nil
  3092. "List of properties (as strings) with a special meaning.
  3093. The default use of these custom properties is to let the user
  3094. hide them with `org-toggle-custom-properties-visibility'."
  3095. :group 'org-properties
  3096. :group 'org-appearance
  3097. :version "24.3"
  3098. :type '(repeat (string :tag "Property Name")))
  3099. (defcustom org-fontify-todo-headline nil
  3100. "Non-nil means change the face of a headline if it is marked as TODO.
  3101. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3102. When this is non-nil, the headline after the keyword is set to the
  3103. `org-headline-todo' as an additional indication."
  3104. :group 'org-appearance
  3105. :package-version '(Org . "9.4")
  3106. :type 'boolean
  3107. :safe #'booleanp)
  3108. (defcustom org-fontify-done-headline t
  3109. "Non-nil means change the face of a headline if it is marked DONE.
  3110. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3111. When this is non-nil, the headline after the keyword is set to the
  3112. `org-headline-done' as an additional indication."
  3113. :group 'org-appearance
  3114. :package-version '(Org . "9.4")
  3115. :type 'boolean)
  3116. (defcustom org-fontify-emphasized-text t
  3117. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3118. Changing this variable requires a restart of Emacs to take effect."
  3119. :group 'org-appearance
  3120. :type 'boolean)
  3121. (defcustom org-fontify-whole-heading-line nil
  3122. "Non-nil means fontify the whole line for headings.
  3123. This is useful when setting a background color for the
  3124. org-level-* faces."
  3125. :group 'org-appearance
  3126. :type 'boolean)
  3127. (defcustom org-fontify-whole-block-delimiter-line t
  3128. "Non-nil means fontify the whole line for begin/end lines of blocks.
  3129. This is useful when setting a background color for the
  3130. org-block-begin-line and org-block-end-line faces."
  3131. :group 'org-appearance
  3132. :type 'boolean)
  3133. (defcustom org-highlight-latex-and-related nil
  3134. "Non-nil means highlight LaTeX related syntax in the buffer.
  3135. When non-nil, the value should be a list containing any of the
  3136. following symbols:
  3137. `native' Highlight LaTeX snippets and environments natively.
  3138. `latex' Highlight LaTeX snippets and environments.
  3139. `script' Highlight subscript and superscript.
  3140. `entities' Highlight entities."
  3141. :group 'org-appearance
  3142. :version "24.4"
  3143. :package-version '(Org . "8.0")
  3144. :type '(choice
  3145. (const :tag "No highlighting" nil)
  3146. (set :greedy t :tag "Highlight"
  3147. (const :tag "LaTeX snippets and environments (native)" native)
  3148. (const :tag "LaTeX snippets and environments" latex)
  3149. (const :tag "Subscript and superscript" script)
  3150. (const :tag "Entities" entities))))
  3151. (defcustom org-hide-emphasis-markers nil
  3152. "Non-nil mean font-lock should hide the emphasis marker characters."
  3153. :group 'org-appearance
  3154. :type 'boolean
  3155. :safe #'booleanp)
  3156. (defcustom org-hide-macro-markers nil
  3157. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3158. :group 'org-appearance
  3159. :type 'boolean)
  3160. (defcustom org-pretty-entities nil
  3161. "Non-nil means show entities as UTF8 characters.
  3162. When nil, the \\name form remains in the buffer."
  3163. :group 'org-appearance
  3164. :version "24.1"
  3165. :type 'boolean)
  3166. (defcustom org-pretty-entities-include-sub-superscripts t
  3167. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3168. :group 'org-appearance
  3169. :version "24.1"
  3170. :type 'boolean)
  3171. (defvar org-emph-re nil
  3172. "Regular expression for matching emphasis.
  3173. After a match, the match groups contain these elements:
  3174. 0 The match of the full regular expression, including the characters
  3175. before and after the proper match
  3176. 1 The character before the proper match, or empty at beginning of line
  3177. 2 The proper match, including the leading and trailing markers
  3178. 3 The leading marker like * or /, indicating the type of highlighting
  3179. 4 The text between the emphasis markers, not including the markers
  3180. 5 The character after the match, empty at the end of a line")
  3181. (defvar org-verbatim-re nil
  3182. "Regular expression for matching verbatim text.")
  3183. (defvar org-emphasis-regexp-components) ; defined just below
  3184. (defvar org-emphasis-alist) ; defined just below
  3185. (defun org-set-emph-re (var val)
  3186. "Set variable and compute the emphasis regular expression."
  3187. (set var val)
  3188. (when (and (boundp 'org-emphasis-alist)
  3189. (boundp 'org-emphasis-regexp-components)
  3190. org-emphasis-alist org-emphasis-regexp-components)
  3191. (pcase-let*
  3192. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3193. (body (if (<= nl 0) body
  3194. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3195. (template
  3196. (format (concat "\\([%s]\\|^\\)" ;before markers
  3197. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3198. "\\([%s]\\|$\\)") ;after markers
  3199. pre border border body border post)))
  3200. (setq org-emph-re (format template "*/_+"))
  3201. (setq org-verbatim-re (format template "=~")))))
  3202. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3203. ;; set this option proved cumbersome. See this message/thread:
  3204. ;; https://orgmode.org/list/B72CDC2B-72F6-43A8-AC70-E6E6295766EC@gmail.com
  3205. (defvar org-emphasis-regexp-components
  3206. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3207. "Components used to build the regular expression for emphasis.
  3208. This is a list with five entries. Terminology: In an emphasis string
  3209. like \" *strong word* \", we call the initial space PREMATCH, the final
  3210. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3211. and \"trong wor\" is the body. The different components in this variable
  3212. specify what is allowed/forbidden in each part:
  3213. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3214. post Chars allowed as postmatch. End of line will be allowed too.
  3215. border The chars *forbidden* as border characters.
  3216. body-regexp A regexp like \".\" to match a body character. Don't use
  3217. non-shy groups here, and don't allow newline here.
  3218. newline The maximum number of newlines allowed in an emphasis exp.
  3219. You need to reload Org or to restart Emacs after setting this.")
  3220. (defcustom org-emphasis-alist
  3221. '(("*" bold)
  3222. ("/" italic)
  3223. ("_" underline)
  3224. ("=" org-verbatim verbatim)
  3225. ("~" org-code verbatim)
  3226. ("+" (:strike-through t)))
  3227. "Alist of characters and faces to emphasize text.
  3228. Text starting and ending with a special character will be emphasized,
  3229. for example *bold*, _underlined_ and /italic/. This variable sets the
  3230. marker characters and the face to be used by font-lock for highlighting
  3231. in Org buffers.
  3232. You need to reload Org or to restart Emacs after customizing this."
  3233. :group 'org-appearance
  3234. :set 'org-set-emph-re
  3235. :version "24.4"
  3236. :package-version '(Org . "8.0")
  3237. :type '(repeat
  3238. (list
  3239. (string :tag "Marker character")
  3240. (choice
  3241. (face :tag "Font-lock-face")
  3242. (plist :tag "Face property list"))
  3243. (option (const verbatim)))))
  3244. (defvar org-protecting-blocks '("src" "example" "export")
  3245. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3246. This is needed for font-lock setup.")
  3247. ;;; Functions and variables from their packages
  3248. ;; Declared here to avoid compiler warnings
  3249. (defvar mark-active)
  3250. ;; Various packages
  3251. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3252. (declare-function calendar-forward-day "cal-move" (arg))
  3253. (declare-function calendar-goto-date "cal-move" (date))
  3254. (declare-function calendar-goto-today "cal-move" ())
  3255. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3256. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3257. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3258. (declare-function cdlatex-tab "ext:cdlatex" ())
  3259. (declare-function dired-get-filename
  3260. "dired"
  3261. (&optional localp no-error-if-not-filep))
  3262. (declare-function org-agenda-change-all-lines
  3263. "org-agenda"
  3264. (newhead hdmarker &optional fixface just-this))
  3265. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3266. "org-agenda"
  3267. (&optional end))
  3268. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3269. (declare-function org-agenda-format-item
  3270. "org-agenda"
  3271. (extra txt &optional level category tags dotime
  3272. remove-re habitp))
  3273. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3274. (declare-function org-agenda-save-markers-for-cut-and-paste
  3275. "org-agenda"
  3276. (beg end))
  3277. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3278. (declare-function org-agenda-skip "org-agenda" ())
  3279. (declare-function org-attach-expand "org-attach" (file))
  3280. (declare-function org-attach-reveal "org-attach" ())
  3281. (declare-function org-attach-reveal-in-emacs "org-attach" ())
  3282. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3283. (declare-function org-indent-mode "org-indent" (&optional arg))
  3284. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3285. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3286. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3287. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3288. (declare-function parse-time-string "parse-time" (string))
  3289. (defvar align-mode-rules-list)
  3290. (defvar calc-embedded-close-formula)
  3291. (defvar calc-embedded-open-formula)
  3292. (defvar calc-embedded-open-mode)
  3293. (defvar font-lock-unfontify-region-function)
  3294. (defvar org-agenda-tags-todo-honor-ignore-options)
  3295. (defvar remember-data-file)
  3296. (defvar texmathp-why)
  3297. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3298. (declare-function org-clock-update-mode-line "org-clock" (&optional refresh))
  3299. (declare-function org-resolve-clocks "org-clock"
  3300. (&optional also-non-dangling-p prompt last-valid))
  3301. (defvar org-clock-start-time)
  3302. (defvar org-clock-marker (make-marker)
  3303. "Marker recording the last clock-in.")
  3304. (defvar org-clock-hd-marker (make-marker)
  3305. "Marker recording the last clock-in, but the headline position.")
  3306. (defvar org-clock-heading ""
  3307. "The heading of the current clock entry.")
  3308. (defun org-clocking-buffer ()
  3309. "Return the buffer where the clock is currently running.
  3310. Return nil if no clock is running."
  3311. (marker-buffer org-clock-marker))
  3312. (defalias 'org-clock-is-active #'org-clocking-buffer)
  3313. (defun org-check-running-clock ()
  3314. "Check if the current buffer contains the running clock.
  3315. If yes, offer to stop it and to save the buffer with the changes."
  3316. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3317. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3318. (buffer-name))))
  3319. (org-clock-out)
  3320. (when (y-or-n-p "Save changed buffer?")
  3321. (save-buffer))))
  3322. (defun org-clocktable-try-shift (dir n)
  3323. "Check if this line starts a clock table, if yes, shift the time block."
  3324. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3325. (org-clocktable-shift dir n)))
  3326. ;;;###autoload
  3327. (defun org-clock-persistence-insinuate ()
  3328. "Set up hooks for clock persistence."
  3329. (require 'org-clock)
  3330. (add-hook 'org-mode-hook 'org-clock-load)
  3331. (add-hook 'kill-emacs-hook 'org-clock-save))
  3332. (defun org-clock-auto-clockout-insinuate ()
  3333. "Set up hook for auto clocking out when Emacs is idle.
  3334. See `org-clock-auto-clockout-timer'.
  3335. This function is meant to be added to the user configuration."
  3336. (require 'org-clock)
  3337. (add-hook 'org-clock-in-hook #'org-clock-auto-clockout t))
  3338. (defgroup org-archive nil
  3339. "Options concerning archiving in Org mode."
  3340. :tag "Org Archive"
  3341. :group 'org-structure)
  3342. (defcustom org-archive-location "%s_archive::"
  3343. "The location where subtrees should be archived.
  3344. The value of this variable is a string, consisting of two parts,
  3345. separated by a double-colon. The first part is a filename and
  3346. the second part is a headline.
  3347. When the filename is omitted, archiving happens in the same file.
  3348. %s in the filename will be replaced by the current file
  3349. name (without the directory part). Archiving to a different file
  3350. is useful to keep archived entries from contributing to the
  3351. Org Agenda.
  3352. The archived entries will be filed as subtrees of the specified
  3353. headline. When the headline is omitted, the subtrees are simply
  3354. filed away at the end of the file, as top-level entries. Also in
  3355. the heading you can use %s to represent the file name, this can be
  3356. useful when using the same archive for a number of different files.
  3357. Here are a few examples:
  3358. \"%s_archive::\"
  3359. If the current file is Projects.org, archive in file
  3360. Projects.org_archive, as top-level trees. This is the default.
  3361. \"::* Archived Tasks\"
  3362. Archive in the current file, under the top-level headline
  3363. \"* Archived Tasks\".
  3364. \"~/org/archive.org::\"
  3365. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3366. \"~/org/archive.org::* From %s\"
  3367. Archive in file ~/org/archive.org (absolute path), under headlines
  3368. \"From FILENAME\" where file name is the current file name.
  3369. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3370. The \"datetree/\" string is special, signifying to archive
  3371. items to the datetree. Items are placed in either the CLOSED
  3372. date of the item, or the current date if there is no CLOSED date.
  3373. The heading will be a subentry to the current date. There doesn't
  3374. need to be a heading, but there always needs to be a slash after
  3375. datetree. For example, to store archived items directly in the
  3376. datetree, use \"~/org/datetree.org::datetree/\".
  3377. \"basement::** Finished Tasks\"
  3378. Archive in file ./basement (relative path), as level 3 trees
  3379. below the level 2 heading \"** Finished Tasks\".
  3380. You may define it locally by setting an ARCHIVE property. If
  3381. such a property is found in the file or in an entry, and anywhere
  3382. up the hierarchy, it will be used.
  3383. You can also set it for the whole file using the keyword-syntax:
  3384. #+ARCHIVE: basement::** Finished Tasks"
  3385. :group 'org-archive
  3386. :type 'string)
  3387. (defcustom org-agenda-skip-archived-trees t
  3388. "Non-nil means the agenda will skip any items located in archived trees.
  3389. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3390. variable is no longer recommended, you should leave it at the value t.
  3391. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3392. :group 'org-archive
  3393. :group 'org-agenda-skip
  3394. :type 'boolean)
  3395. (defcustom org-columns-skip-archived-trees t
  3396. "Non-nil means ignore archived trees when creating column view."
  3397. :group 'org-archive
  3398. :group 'org-properties
  3399. :type 'boolean)
  3400. (defcustom org-cycle-open-archived-trees nil
  3401. "Non-nil means `org-cycle' will open archived trees.
  3402. An archived tree is a tree marked with the tag ARCHIVE.
  3403. When nil, archived trees will stay folded. You can still open them with
  3404. normal outline commands like `show-all', but not with the cycling commands."
  3405. :group 'org-archive
  3406. :group 'org-cycle
  3407. :type 'boolean)
  3408. (defcustom org-sparse-tree-open-archived-trees nil
  3409. "Non-nil means sparse tree construction shows matches in archived trees.
  3410. When nil, matches in these trees are highlighted, but the trees are kept in
  3411. collapsed state."
  3412. :group 'org-archive
  3413. :group 'org-sparse-trees
  3414. :type 'boolean)
  3415. (defcustom org-sparse-tree-default-date-type nil
  3416. "The default date type when building a sparse tree.
  3417. When this is nil, a date is a scheduled or a deadline timestamp.
  3418. Otherwise, these types are allowed:
  3419. all: all timestamps
  3420. active: only active timestamps (<...>)
  3421. inactive: only inactive timestamps ([...])
  3422. scheduled: only scheduled timestamps
  3423. deadline: only deadline timestamps"
  3424. :type '(choice (const :tag "Scheduled or deadline" nil)
  3425. (const :tag "All timestamps" all)
  3426. (const :tag "Only active timestamps" active)
  3427. (const :tag "Only inactive timestamps" inactive)
  3428. (const :tag "Only scheduled timestamps" scheduled)
  3429. (const :tag "Only deadline timestamps" deadline)
  3430. (const :tag "Only closed timestamps" closed))
  3431. :version "26.1"
  3432. :package-version '(Org . "8.3")
  3433. :group 'org-sparse-trees)
  3434. (defun org-cycle-hide-archived-subtrees (state)
  3435. "Re-hide all archived subtrees after a visibility state change.
  3436. STATE should be one of the symbols listed in the docstring of
  3437. `org-cycle-hook'."
  3438. (when (and (not org-cycle-open-archived-trees)
  3439. (not (memq state '(overview folded))))
  3440. (save-excursion
  3441. (let* ((globalp (memq state '(contents all)))
  3442. (beg (if globalp (point-min) (point)))
  3443. (end (if globalp (point-max) (org-end-of-subtree t))))
  3444. (org-hide-archived-subtrees beg end)
  3445. (goto-char beg)
  3446. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  3447. (message "%s" (substitute-command-keys
  3448. "Subtree is archived and stays closed. Use \
  3449. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  3450. (defun org-force-cycle-archived ()
  3451. "Cycle subtree even if it is archived."
  3452. (interactive)
  3453. (setq this-command 'org-cycle)
  3454. (let ((org-cycle-open-archived-trees t))
  3455. (call-interactively 'org-cycle)))
  3456. (defun org-hide-archived-subtrees (beg end)
  3457. "Re-hide all archived subtrees after a visibility state change."
  3458. (org-with-wide-buffer
  3459. (let ((case-fold-search nil)
  3460. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  3461. (goto-char beg)
  3462. ;; Include headline point is currently on.
  3463. (beginning-of-line)
  3464. (while (and (< (point) end) (re-search-forward re end t))
  3465. (when (member org-archive-tag (org-get-tags nil t))
  3466. (org-flag-subtree t)
  3467. (org-end-of-subtree t))))))
  3468. (defun org-flag-subtree (flag)
  3469. (save-excursion
  3470. (org-back-to-heading t)
  3471. (org-flag-region (line-end-position)
  3472. (progn (org-end-of-subtree t) (point))
  3473. flag
  3474. 'outline)))
  3475. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  3476. ;; Declare Column View Code
  3477. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  3478. (declare-function org-columns-compute "org-colview" (property))
  3479. ;; Declare ID code
  3480. (declare-function org-id-store-link "org-id")
  3481. (declare-function org-id-locations-load "org-id")
  3482. (declare-function org-id-locations-save "org-id")
  3483. (defvar org-id-track-globally)
  3484. ;;; Variables for pre-computed regular expressions, all buffer local
  3485. (defvar-local org-todo-regexp nil
  3486. "Matches any of the TODO state keywords.
  3487. Since TODO keywords are case-sensitive, `case-fold-search' is
  3488. expected to be bound to nil when matching against this regexp.")
  3489. (defvar-local org-not-done-regexp nil
  3490. "Matches any of the TODO state keywords except the last one.
  3491. Since TODO keywords are case-sensitive, `case-fold-search' is
  3492. expected to be bound to nil when matching against this regexp.")
  3493. (defvar-local org-not-done-heading-regexp nil
  3494. "Matches a TODO headline that is not done.
  3495. Since TODO keywords are case-sensitive, `case-fold-search' is
  3496. expected to be bound to nil when matching against this regexp.")
  3497. (defvar-local org-todo-line-regexp nil
  3498. "Matches a headline and puts TODO state into group 2 if present.
  3499. Since TODO keywords are case-sensitive, `case-fold-search' is
  3500. expected to be bound to nil when matching against this regexp.")
  3501. (defvar-local org-complex-heading-regexp nil
  3502. "Matches a headline and puts everything into groups:
  3503. group 1: Stars
  3504. group 2: The TODO keyword, maybe
  3505. group 3: Priority cookie
  3506. group 4: True headline
  3507. group 5: Tags
  3508. Since TODO keywords are case-sensitive, `case-fold-search' is
  3509. expected to be bound to nil when matching against this regexp.")
  3510. (defvar-local org-complex-heading-regexp-format nil
  3511. "Printf format to make regexp to match an exact headline.
  3512. This regexp will match the headline of any node which has the
  3513. exact headline text that is put into the format, but may have any
  3514. TODO state, priority and tags.")
  3515. (defvar-local org-todo-line-tags-regexp nil
  3516. "Matches a headline and puts TODO state into group 2 if present.
  3517. Also put tags into group 4 if tags are present.")
  3518. (defconst org-plain-time-of-day-regexp
  3519. (concat
  3520. "\\(\\<[012]?[0-9]"
  3521. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3522. "\\(--?"
  3523. "\\(\\<[012]?[0-9]"
  3524. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3525. "\\)?")
  3526. "Regular expression to match a plain time or time range.
  3527. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3528. groups carry important information:
  3529. 0 the full match
  3530. 1 the first time, range or not
  3531. 8 the second time, if it is a range.")
  3532. (defconst org-plain-time-extension-regexp
  3533. (concat
  3534. "\\(\\<[012]?[0-9]"
  3535. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3536. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  3537. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  3538. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3539. groups carry important information:
  3540. 0 the full match
  3541. 7 hours of duration
  3542. 9 minutes of duration")
  3543. (defconst org-stamp-time-of-day-regexp
  3544. (concat
  3545. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  3546. "\\([012][0-9]:[0-5][0-9]\\)\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?>"
  3547. "\\(--?"
  3548. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  3549. "Regular expression to match a timestamp time or time range.
  3550. After a match, the following groups carry important information:
  3551. 0 the full match
  3552. 1 date plus weekday, for back referencing to make sure
  3553. both times are on the same day
  3554. 2 the first time, range or not
  3555. 4 the second time, if it is a range.")
  3556. (defconst org-startup-options
  3557. '(("fold" org-startup-folded t)
  3558. ("overview" org-startup-folded t)
  3559. ("nofold" org-startup-folded nil)
  3560. ("showall" org-startup-folded nil)
  3561. ("show2levels" org-startup-folded show2levels)
  3562. ("show3levels" org-startup-folded show3levels)
  3563. ("show4levels" org-startup-folded show4levels)
  3564. ("show5levels" org-startup-folded show5levels)
  3565. ("showeverything" org-startup-folded showeverything)
  3566. ("content" org-startup-folded content)
  3567. ("indent" org-startup-indented t)
  3568. ("noindent" org-startup-indented nil)
  3569. ("num" org-startup-numerated t)
  3570. ("nonum" org-startup-numerated nil)
  3571. ("hidestars" org-hide-leading-stars t)
  3572. ("showstars" org-hide-leading-stars nil)
  3573. ("odd" org-odd-levels-only t)
  3574. ("oddeven" org-odd-levels-only nil)
  3575. ("align" org-startup-align-all-tables t)
  3576. ("noalign" org-startup-align-all-tables nil)
  3577. ("shrink" org-startup-shrink-all-tables t)
  3578. ("inlineimages" org-startup-with-inline-images t)
  3579. ("noinlineimages" org-startup-with-inline-images nil)
  3580. ("latexpreview" org-startup-with-latex-preview t)
  3581. ("nolatexpreview" org-startup-with-latex-preview nil)
  3582. ("customtime" org-display-custom-times t)
  3583. ("logdone" org-log-done time)
  3584. ("lognotedone" org-log-done note)
  3585. ("nologdone" org-log-done nil)
  3586. ("lognoteclock-out" org-log-note-clock-out t)
  3587. ("nolognoteclock-out" org-log-note-clock-out nil)
  3588. ("logrepeat" org-log-repeat state)
  3589. ("lognoterepeat" org-log-repeat note)
  3590. ("logdrawer" org-log-into-drawer t)
  3591. ("nologdrawer" org-log-into-drawer nil)
  3592. ("logstatesreversed" org-log-states-order-reversed t)
  3593. ("nologstatesreversed" org-log-states-order-reversed nil)
  3594. ("nologrepeat" org-log-repeat nil)
  3595. ("logreschedule" org-log-reschedule time)
  3596. ("lognotereschedule" org-log-reschedule note)
  3597. ("nologreschedule" org-log-reschedule nil)
  3598. ("logredeadline" org-log-redeadline time)
  3599. ("lognoteredeadline" org-log-redeadline note)
  3600. ("nologredeadline" org-log-redeadline nil)
  3601. ("logrefile" org-log-refile time)
  3602. ("lognoterefile" org-log-refile note)
  3603. ("nologrefile" org-log-refile nil)
  3604. ("fninline" org-footnote-define-inline t)
  3605. ("nofninline" org-footnote-define-inline nil)
  3606. ("fnlocal" org-footnote-section nil)
  3607. ("fnauto" org-footnote-auto-label t)
  3608. ("fnprompt" org-footnote-auto-label nil)
  3609. ("fnconfirm" org-footnote-auto-label confirm)
  3610. ("fnplain" org-footnote-auto-label plain)
  3611. ("fnadjust" org-footnote-auto-adjust t)
  3612. ("nofnadjust" org-footnote-auto-adjust nil)
  3613. ("constcgs" constants-unit-system cgs)
  3614. ("constSI" constants-unit-system SI)
  3615. ("noptag" org-tag-persistent-alist nil)
  3616. ("hideblocks" org-hide-block-startup t)
  3617. ("nohideblocks" org-hide-block-startup nil)
  3618. ("beamer" org-startup-with-beamer-mode t)
  3619. ("entitiespretty" org-pretty-entities t)
  3620. ("entitiesplain" org-pretty-entities nil))
  3621. "Variable associated with STARTUP options for Org.
  3622. Each element is a list of three items: the startup options (as written
  3623. in the #+STARTUP line), the corresponding variable, and the value to set
  3624. this variable to if the option is found. An optional fourth element PUSH
  3625. means to push this value onto the list in the variable.")
  3626. (defcustom org-group-tags t
  3627. "When non-nil (the default), use group tags.
  3628. This can be turned on/off through `org-toggle-tags-groups'."
  3629. :group 'org-tags
  3630. :group 'org-startup
  3631. :type 'boolean)
  3632. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  3633. (defun org-toggle-tags-groups ()
  3634. "Toggle support for group tags.
  3635. Support for group tags is controlled by the option
  3636. `org-group-tags', which is non-nil by default."
  3637. (interactive)
  3638. (setq org-group-tags (not org-group-tags))
  3639. (cond ((and (derived-mode-p 'org-agenda-mode)
  3640. org-group-tags)
  3641. (org-agenda-redo))
  3642. ((derived-mode-p 'org-mode)
  3643. (let ((org-inhibit-startup t)) (org-mode))))
  3644. (message "Groups tags support has been turned %s"
  3645. (if org-group-tags "on" "off")))
  3646. (defun org--tag-add-to-alist (alist1 alist2)
  3647. "Merge tags from ALIST1 into ALIST2.
  3648. Duplicates tags outside a group are removed. Keywords and order
  3649. are preserved.
  3650. The function assumes ALIST1 and ALIST2 are proper tag alists.
  3651. See `org-tag-alist' for their structure."
  3652. (cond
  3653. ((null alist2) alist1)
  3654. ((null alist1) alist2)
  3655. (t
  3656. (let ((to-add nil)
  3657. (group-flag nil))
  3658. (dolist (tag-pair alist1)
  3659. (pcase tag-pair
  3660. (`(,(or :startgrouptag :startgroup))
  3661. (setq group-flag t)
  3662. (push tag-pair to-add))
  3663. (`(,(or :endgrouptag :endgroup))
  3664. (setq group-flag nil)
  3665. (push tag-pair to-add))
  3666. (`(,(or :grouptags :newline))
  3667. (push tag-pair to-add))
  3668. (`(,tag . ,_)
  3669. ;; Remove duplicates from ALIST1, unless they are in
  3670. ;; a group. Indeed, it makes sense to have a tag appear in
  3671. ;; multiple groups.
  3672. (when (or group-flag (not (assoc tag alist2)))
  3673. (push tag-pair to-add)))
  3674. (_ (error "Invalid association in tag alist: %S" tag-pair))))
  3675. ;; Preserve order of ALIST1.
  3676. (append (nreverse to-add) alist2)))))
  3677. (defun org-priority-to-value (s)
  3678. "Convert priority string S to its numeric value."
  3679. (or (save-match-data
  3680. (and (string-match "\\([0-9]+\\)" s)
  3681. (string-to-number (match-string 1 s))))
  3682. (string-to-char s)))
  3683. (defun org-set-regexps-and-options (&optional tags-only)
  3684. "Precompute regular expressions used in the current buffer.
  3685. When optional argument TAGS-ONLY is non-nil, only compute tags
  3686. related expressions."
  3687. (when (derived-mode-p 'org-mode)
  3688. (let ((alist (org-collect-keywords
  3689. (append '("FILETAGS" "TAGS")
  3690. (and (not tags-only)
  3691. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  3692. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  3693. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))
  3694. '("ARCHIVE" "CATEGORY" "COLUMNS" "PRIORITIES"))))
  3695. ;; Startup options. Get this early since it does change
  3696. ;; behavior for other options (e.g., tags).
  3697. (let ((startup (cl-mapcan (lambda (value) (split-string value))
  3698. (cdr (assoc "STARTUP" alist)))))
  3699. (dolist (option startup)
  3700. (pcase (assoc-string option org-startup-options t)
  3701. (`(,_ ,variable ,value t)
  3702. (unless (listp (symbol-value variable))
  3703. (set (make-local-variable variable) nil))
  3704. (add-to-list variable value))
  3705. (`(,_ ,variable ,value . ,_)
  3706. (set (make-local-variable variable) value))
  3707. (_ nil))))
  3708. (setq-local org-file-tags
  3709. (mapcar #'org-add-prop-inherited
  3710. (cl-mapcan (lambda (value)
  3711. (cl-mapcan
  3712. (lambda (k) (org-split-string k ":"))
  3713. (split-string value)))
  3714. (cdr (assoc "FILETAGS" alist)))))
  3715. (setq org-current-tag-alist
  3716. (org--tag-add-to-alist
  3717. org-tag-persistent-alist
  3718. (let ((tags (cdr (assoc "TAGS" alist))))
  3719. (if tags
  3720. (org-tag-string-to-alist
  3721. (mapconcat #'identity tags "\n"))
  3722. org-tag-alist))))
  3723. (setq org-tag-groups-alist
  3724. (org-tag-alist-to-groups org-current-tag-alist))
  3725. (unless tags-only
  3726. ;; Properties.
  3727. (let ((properties nil))
  3728. (dolist (value (cdr (assoc "PROPERTY" alist)))
  3729. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  3730. (setq properties (org--update-property-plist
  3731. (match-string-no-properties 1 value)
  3732. (match-string-no-properties 2 value)
  3733. properties))))
  3734. (setq-local org-keyword-properties properties))
  3735. ;; Archive location.
  3736. (let ((archive (cdr (assoc "ARCHIVE" alist))))
  3737. (when archive (setq-local org-archive-location archive)))
  3738. ;; Category.
  3739. (let ((category (cdr (assoc "CATEGORY" alist))))
  3740. (when category
  3741. (setq-local org-category (intern category))
  3742. (setq-local org-keyword-properties
  3743. (org--update-property-plist
  3744. "CATEGORY" category org-keyword-properties))))
  3745. ;; Columns.
  3746. (let ((column (cdr (assoc "COLUMNS" alist))))
  3747. (when column (setq-local org-columns-default-format column)))
  3748. ;; Constants.
  3749. (let ((store nil))
  3750. (dolist (pair (cl-mapcan #'split-string
  3751. (cdr (assoc "CONSTANTS" alist))))
  3752. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" pair)
  3753. (let* ((name (match-string 1 pair))
  3754. (value (match-string 2 pair))
  3755. (old (assoc name store)))
  3756. (if old (setcdr old value)
  3757. (push (cons name value) store)))))
  3758. (setq org-table-formula-constants-local store))
  3759. ;; Link abbreviations.
  3760. (let ((links
  3761. (delq nil
  3762. (mapcar
  3763. (lambda (value)
  3764. (and (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  3765. (cons (match-string-no-properties 1 value)
  3766. (match-string-no-properties 2 value))))
  3767. (cdr (assoc "LINK" alist))))))
  3768. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  3769. ;; Priorities.
  3770. (let ((value (cdr (assoc "PRIORITIES" alist))))
  3771. (pcase (and value (split-string value))
  3772. (`(,high ,low ,default . ,_)
  3773. (setq-local org-priority-highest (org-priority-to-value high))
  3774. (setq-local org-priority-lowest (org-priority-to-value low))
  3775. (setq-local org-priority-default (org-priority-to-value default)))))
  3776. ;; Scripts.
  3777. (let ((value (cdr (assoc "OPTIONS" alist))))
  3778. (dolist (option value)
  3779. (when (string-match "\\^:\\(t\\|nil\\|{}\\)" option)
  3780. (setq-local org-use-sub-superscripts
  3781. (read (match-string 1 option))))))
  3782. ;; TODO keywords.
  3783. (setq-local org-todo-kwd-alist nil)
  3784. (setq-local org-todo-key-alist nil)
  3785. (setq-local org-todo-key-trigger nil)
  3786. (setq-local org-todo-keywords-1 nil)
  3787. (setq-local org-done-keywords nil)
  3788. (setq-local org-todo-heads nil)
  3789. (setq-local org-todo-sets nil)
  3790. (setq-local org-todo-log-states nil)
  3791. (let ((todo-sequences
  3792. (or (append (mapcar (lambda (value)
  3793. (cons 'type (split-string value)))
  3794. (cdr (assoc "TYP_TODO" alist)))
  3795. (mapcar (lambda (value)
  3796. (cons 'sequence (split-string value)))
  3797. (append (cdr (assoc "TODO" alist))
  3798. (cdr (assoc "SEQ_TODO" alist)))))
  3799. (let ((d (default-value 'org-todo-keywords)))
  3800. (if (not (stringp (car d))) d
  3801. ;; XXX: Backward compatibility code.
  3802. (list (cons org-todo-interpretation d)))))))
  3803. (dolist (sequence todo-sequences)
  3804. (let* ((sequence (or (run-hook-with-args-until-success
  3805. 'org-todo-setup-filter-hook sequence)
  3806. sequence))
  3807. (sequence-type (car sequence))
  3808. (keywords (cdr sequence))
  3809. (sep (member "|" keywords))
  3810. names alist)
  3811. (dolist (k (remove "|" keywords))
  3812. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  3813. k)
  3814. (error "Invalid TODO keyword %s" k))
  3815. (let ((name (match-string 1 k))
  3816. (key (match-string 2 k))
  3817. (log (org-extract-log-state-settings k)))
  3818. (push name names)
  3819. (push (cons name (and key (string-to-char key))) alist)
  3820. (when log (push log org-todo-log-states))))
  3821. (let* ((names (nreverse names))
  3822. (done (if sep (org-remove-keyword-keys (cdr sep))
  3823. (last names)))
  3824. (head (car names))
  3825. (tail (list sequence-type head (car done) (org-last done))))
  3826. (add-to-list 'org-todo-heads head 'append)
  3827. (push names org-todo-sets)
  3828. (setq org-done-keywords (append org-done-keywords done nil))
  3829. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  3830. (setq org-todo-key-alist
  3831. (append org-todo-key-alist
  3832. (and alist
  3833. (append '((:startgroup))
  3834. (nreverse alist)
  3835. '((:endgroup))))))
  3836. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  3837. (setq org-todo-sets (nreverse org-todo-sets)
  3838. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  3839. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  3840. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  3841. ;; Compute the regular expressions and other local variables.
  3842. ;; Using `org-outline-regexp-bol' would complicate them much,
  3843. ;; because of the fixed white space at the end of that string.
  3844. (unless org-done-keywords
  3845. (setq org-done-keywords
  3846. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  3847. (setq org-not-done-keywords
  3848. (org-delete-all org-done-keywords
  3849. (copy-sequence org-todo-keywords-1))
  3850. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  3851. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  3852. org-not-done-heading-regexp
  3853. (format org-heading-keyword-regexp-format org-not-done-regexp)
  3854. org-todo-line-regexp
  3855. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  3856. org-complex-heading-regexp
  3857. (concat "^\\(\\*+\\)"
  3858. "\\(?: +" org-todo-regexp "\\)?"
  3859. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3860. "\\(?: +\\(.*?\\)\\)??"
  3861. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  3862. "[ \t]*$")
  3863. org-complex-heading-regexp-format
  3864. (concat "^\\(\\*+\\)"
  3865. "\\(?: +" org-todo-regexp "\\)?"
  3866. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3867. "\\(?: +"
  3868. ;; Stats cookies can be stuck to body.
  3869. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  3870. "\\(%s\\)"
  3871. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  3872. "\\)"
  3873. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  3874. "[ \t]*$")
  3875. org-todo-line-tags-regexp
  3876. (concat "^\\(\\*+\\)"
  3877. "\\(?: +" org-todo-regexp "\\)?"
  3878. "\\(?: +\\(.*?\\)\\)??"
  3879. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  3880. "[ \t]*$"))
  3881. (org-compute-latex-and-related-regexp)))))
  3882. (defun org-collect-keywords (keywords &optional unique directory)
  3883. "Return values for KEYWORDS in current buffer, as an alist.
  3884. KEYWORDS is a list of strings. Return value is a list of
  3885. elements with the pattern:
  3886. (NAME . LIST-OF-VALUES)
  3887. where NAME is the upcase name of the keyword, and LIST-OF-VALUES
  3888. is a list of non-empty values, as strings, in order of appearance
  3889. in the buffer.
  3890. When KEYWORD appears in UNIQUE list, LIST-OF-VALUE is its first
  3891. value, empty or not, appearing in the buffer, as a string.
  3892. When KEYWORD appears in DIRECTORIES, each value is a cons cell:
  3893. (VALUE . DIRECTORY)
  3894. where VALUE is the regular value, and DIRECTORY is the variable
  3895. `default-directory' for the buffer containing the keyword. This
  3896. is important for values containing relative file names, since the
  3897. function follows SETUPFILE keywords, and may change its working
  3898. directory."
  3899. (let* ((keywords (cons "SETUPFILE" (mapcar #'upcase keywords)))
  3900. (unique (mapcar #'upcase unique))
  3901. (alist (org--collect-keywords-1
  3902. keywords unique directory
  3903. (and buffer-file-name (list buffer-file-name))
  3904. nil)))
  3905. ;; Re-order results.
  3906. (dolist (entry alist)
  3907. (pcase entry
  3908. (`(,_ . ,(and value (pred consp)))
  3909. (setcdr entry (nreverse value)))))
  3910. (nreverse alist)))
  3911. (defun org--collect-keywords-1 (keywords unique directory files alist)
  3912. (org-with-point-at 1
  3913. (let ((case-fold-search t)
  3914. (regexp (org-make-options-regexp keywords)))
  3915. (while (and keywords (re-search-forward regexp nil t))
  3916. (let ((element (org-element-at-point)))
  3917. (when (eq 'keyword (org-element-type element))
  3918. (let ((value (org-element-property :value element)))
  3919. (pcase (org-element-property :key element)
  3920. ("SETUPFILE"
  3921. (when (and (org-string-nw-p value)
  3922. (not buffer-read-only)) ;FIXME: bug in Gnus?
  3923. (let* ((uri (org-strip-quotes value))
  3924. (uri-is-url (org-url-p uri))
  3925. (uri (if uri-is-url
  3926. uri
  3927. (expand-file-name uri))))
  3928. (unless (member uri files)
  3929. (with-temp-buffer
  3930. (unless uri-is-url
  3931. (setq default-directory (file-name-directory uri)))
  3932. (let ((contents (org-file-contents uri :noerror)))
  3933. (when contents
  3934. (insert contents)
  3935. ;; Fake Org mode: `org-element-at-point'
  3936. ;; doesn't need full set-up.
  3937. (let ((major-mode 'org-mode))
  3938. (setq alist
  3939. (org--collect-keywords-1
  3940. keywords unique directory
  3941. (cons uri files)
  3942. alist))))))))))
  3943. (keyword
  3944. (let ((entry (assoc keyword alist))
  3945. (final
  3946. (cond ((not (member keyword directory)) value)
  3947. (buffer-file-name
  3948. (cons value
  3949. (file-name-directory buffer-file-name)))
  3950. (t (cons value default-directory)))))
  3951. (cond ((member keyword unique)
  3952. (push (cons keyword final) alist)
  3953. (setq keywords (remove keyword keywords))
  3954. (setq regexp (org-make-options-regexp keywords)))
  3955. ((null entry) (push (list keyword final) alist))
  3956. (t (push final (cdr entry)))))))))))
  3957. alist)))
  3958. (defun org-tag-string-to-alist (s)
  3959. "Return tag alist associated to string S.
  3960. S is a value for TAGS keyword or produced with
  3961. `org-tag-alist-to-string'. Return value is an alist suitable for
  3962. `org-tag-alist' or `org-tag-persistent-alist'."
  3963. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  3964. (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
  3965. "\\(?:(\\(.\\))\\)?\\'"))
  3966. alist group-flag)
  3967. (dolist (tokens lines (cdr (nreverse alist)))
  3968. (push '(:newline) alist)
  3969. (while tokens
  3970. (let ((token (pop tokens)))
  3971. (pcase token
  3972. ("{"
  3973. (push '(:startgroup) alist)
  3974. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3975. ("}"
  3976. (push '(:endgroup) alist)
  3977. (setq group-flag nil))
  3978. ("["
  3979. (push '(:startgrouptag) alist)
  3980. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3981. ("]"
  3982. (push '(:endgrouptag) alist)
  3983. (setq group-flag nil))
  3984. (":"
  3985. (push '(:grouptags) alist))
  3986. ((guard (string-match tag-re token))
  3987. (let ((tag (match-string 1 token))
  3988. (key (and (match-beginning 2)
  3989. (string-to-char (match-string 2 token)))))
  3990. ;; Push all tags in groups, no matter if they already
  3991. ;; appear somewhere else in the list.
  3992. (when (or group-flag (not (assoc tag alist)))
  3993. (push (cons tag key) alist))))))))))
  3994. (defun org-tag-alist-to-string (alist &optional skip-key)
  3995. "Return tag string associated to ALIST.
  3996. ALIST is an alist, as defined in `org-tag-alist' or
  3997. `org-tag-persistent-alist', or produced with
  3998. `org-tag-string-to-alist'.
  3999. Return value is a string suitable as a value for \"TAGS\"
  4000. keyword.
  4001. When optional argument SKIP-KEY is non-nil, skip selection keys
  4002. next to tags."
  4003. (mapconcat (lambda (token)
  4004. (pcase token
  4005. (`(:startgroup) "{")
  4006. (`(:endgroup) "}")
  4007. (`(:startgrouptag) "[")
  4008. (`(:endgrouptag) "]")
  4009. (`(:grouptags) ":")
  4010. (`(:newline) "\\n")
  4011. ((and
  4012. (guard (not skip-key))
  4013. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4014. (format "%s(%c)" tag key))
  4015. (`(,(and tag (pred stringp)) . ,_) tag)
  4016. (_ (user-error "Invalid tag token: %S" token))))
  4017. alist
  4018. " "))
  4019. (defun org-tag-alist-to-groups (alist)
  4020. "Return group alist from tag ALIST.
  4021. ALIST is an alist, as defined in `org-tag-alist' or
  4022. `org-tag-persistent-alist', or produced with
  4023. `org-tag-string-to-alist'. Return value is an alist following
  4024. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4025. a string, summarizing TAGS, as a list of strings."
  4026. (let (groups group-status current-group)
  4027. (dolist (token alist (nreverse groups))
  4028. (pcase token
  4029. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4030. (`(,(or :endgroup :endgrouptag))
  4031. (when (eq group-status 'append)
  4032. (push (nreverse current-group) groups))
  4033. (setq group-status nil current-group nil))
  4034. (`(:grouptags) (setq group-status 'append))
  4035. ((and `(,tag . ,_) (guard group-status))
  4036. (if (eq group-status 'append) (push tag current-group)
  4037. (setq current-group (list tag))))
  4038. (_ nil)))))
  4039. (defvar org--file-cache (make-hash-table :test #'equal)
  4040. "Hash table to store contents of files referenced via a URL.
  4041. This is the cache of file URLs read using `org-file-contents'.")
  4042. (defun org-reset-file-cache ()
  4043. "Reset the cache of files downloaded by `org-file-contents'."
  4044. (clrhash org--file-cache))
  4045. (defun org-file-contents (file &optional noerror nocache)
  4046. "Return the contents of FILE, as a string.
  4047. FILE can be a file name or URL.
  4048. If FILE is a URL, download the contents. If the URL contents are
  4049. already cached in the `org--file-cache' hash table, the download step
  4050. is skipped.
  4051. If NOERROR is non-nil, ignore the error when unable to read the FILE
  4052. from file or URL, and return nil.
  4053. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  4054. is available. This option applies only if FILE is a URL."
  4055. (let* ((is-url (org-url-p file))
  4056. (cache (and is-url
  4057. (not nocache)
  4058. (gethash file org--file-cache))))
  4059. (cond
  4060. (cache)
  4061. (is-url
  4062. (with-current-buffer (url-retrieve-synchronously file)
  4063. (goto-char (point-min))
  4064. ;; Move point to after the url-retrieve header.
  4065. (search-forward "\n\n" nil :move)
  4066. ;; Search for the success code only in the url-retrieve header.
  4067. (if (save-excursion
  4068. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  4069. ;; Update the cache `org--file-cache' and return contents.
  4070. (puthash file
  4071. (buffer-substring-no-properties (point) (point-max))
  4072. org--file-cache)
  4073. (funcall (if noerror #'message #'user-error)
  4074. "Unable to fetch file from %S"
  4075. file)
  4076. nil)))
  4077. (t
  4078. (with-temp-buffer
  4079. (condition-case nil
  4080. (progn
  4081. (insert-file-contents file)
  4082. (buffer-string))
  4083. (file-error
  4084. (funcall (if noerror #'message #'user-error)
  4085. "Unable to read file %S"
  4086. file)
  4087. nil)))))))
  4088. (defun org-extract-log-state-settings (x)
  4089. "Extract the log state setting from a TODO keyword string.
  4090. This will extract info from a string like \"WAIT(w@/!)\"."
  4091. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4092. (let ((kw (match-string 1 x))
  4093. (log1 (and (match-end 3) (match-string 3 x)))
  4094. (log2 (and (match-end 4) (match-string 4 x))))
  4095. (and (or log1 log2)
  4096. (list kw
  4097. (and log1 (if (equal log1 "!") 'time 'note))
  4098. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4099. (defun org-remove-keyword-keys (list)
  4100. "Remove a pair of parenthesis at the end of each string in LIST."
  4101. (mapcar (lambda (x)
  4102. (if (string-match "(.*)$" x)
  4103. (substring x 0 (match-beginning 0))
  4104. x))
  4105. list))
  4106. (defun org-assign-fast-keys (alist)
  4107. "Assign fast keys to a keyword-key alist.
  4108. Respect keys that are already there."
  4109. (let (new e (alt ?0))
  4110. (while (setq e (pop alist))
  4111. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4112. (cdr e)) ;; Key already assigned.
  4113. (push e new)
  4114. (let ((clist (string-to-list (downcase (car e))))
  4115. (used (append new alist)))
  4116. (when (= (car clist) ?@)
  4117. (pop clist))
  4118. (while (and clist (rassoc (car clist) used))
  4119. (pop clist))
  4120. (unless clist
  4121. (while (rassoc alt used)
  4122. (cl-incf alt)))
  4123. (push (cons (car e) (or (car clist) alt)) new))))
  4124. (nreverse new)))
  4125. ;;; Some variables used in various places
  4126. (defvar org-window-configuration nil
  4127. "Used in various places to store a window configuration.")
  4128. (defvar org-selected-window nil
  4129. "Used in various places to store a window configuration.")
  4130. (defvar org-finish-function nil
  4131. "Function to be called when `C-c C-c' is used.
  4132. This is for getting out of special buffers like capture.")
  4133. (defvar org-last-state)
  4134. ;; Defined somewhere in this file, but used before definition.
  4135. (defvar org-entities) ;; defined in org-entities.el
  4136. (defvar org-struct-menu)
  4137. (defvar org-org-menu)
  4138. (defvar org-tbl-menu)
  4139. ;;;; Define the Org mode
  4140. (defun org-before-change-function (_beg _end)
  4141. "Every change indicates that a table might need an update."
  4142. (setq org-table-may-need-update t))
  4143. (defvar org-mode-map)
  4144. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4145. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4146. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4147. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4148. (defvar bidi-paragraph-direction)
  4149. (defvar buffer-face-mode-face)
  4150. (require 'outline)
  4151. ;; Other stuff we need.
  4152. (require 'time-date)
  4153. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4154. (when (< emacs-major-version 28) ; preloaded in Emacs 28
  4155. (require 'easymenu))
  4156. (require 'org-entities)
  4157. (require 'org-faces)
  4158. (require 'org-list)
  4159. (require 'org-pcomplete)
  4160. (require 'org-src)
  4161. (require 'org-footnote)
  4162. (require 'org-macro)
  4163. ;; babel
  4164. (require 'ob)
  4165. ;;;###autoload
  4166. (define-derived-mode org-mode outline-mode "Org"
  4167. "Outline-based notes management and organizer, alias
  4168. \"Carsten's outline-mode for keeping track of everything.\"
  4169. Org mode develops organizational tasks around a NOTES file which
  4170. contains information about projects as plain text. Org mode is
  4171. implemented on top of Outline mode, which is ideal to keep the content
  4172. of large files well structured. It supports ToDo items, deadlines and
  4173. time stamps, which magically appear in the diary listing of the Emacs
  4174. calendar. Tables are easily created with a built-in table editor.
  4175. Plain text URL-like links connect to websites, emails (VM), Usenet
  4176. messages (Gnus), BBDB entries, and any files related to the project.
  4177. For printing and sharing of notes, an Org file (or a part of it)
  4178. can be exported as a structured ASCII or HTML file.
  4179. The following commands are available:
  4180. \\{org-mode-map}"
  4181. (org-load-modules-maybe)
  4182. (org-install-agenda-files-menu)
  4183. (when org-link-descriptive (add-to-invisibility-spec '(org-link)))
  4184. (make-local-variable 'org-link-descriptive)
  4185. (add-to-invisibility-spec '(org-hide-block . t))
  4186. (setq-local outline-regexp org-outline-regexp)
  4187. (setq-local outline-level 'org-outline-level)
  4188. (setq bidi-paragraph-direction 'left-to-right)
  4189. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4190. (unless org-display-table
  4191. (setq org-display-table (make-display-table)))
  4192. (set-display-table-slot
  4193. org-display-table 4
  4194. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4195. org-ellipsis)))
  4196. (setq buffer-display-table org-display-table))
  4197. (org-set-regexps-and-options)
  4198. (org-set-font-lock-defaults)
  4199. (when (and org-tag-faces (not org-tags-special-faces-re))
  4200. ;; tag faces set outside customize.... force initialization.
  4201. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4202. ;; Calc embedded
  4203. (setq-local calc-embedded-open-mode "# ")
  4204. ;; Modify a few syntax entries
  4205. (modify-syntax-entry ?\" "\"")
  4206. (modify-syntax-entry ?\\ "_")
  4207. (modify-syntax-entry ?~ "_")
  4208. (modify-syntax-entry ?< "(>")
  4209. (modify-syntax-entry ?> ")<")
  4210. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4211. ;; Activate before-change-function
  4212. (setq-local org-table-may-need-update t)
  4213. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4214. ;; Check for running clock before killing a buffer
  4215. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4216. ;; Initialize macros templates.
  4217. (org-macro-initialize-templates)
  4218. ;; Initialize radio targets.
  4219. (org-update-radio-target-regexp)
  4220. ;; Indentation.
  4221. (setq-local indent-line-function 'org-indent-line)
  4222. (setq-local indent-region-function 'org-indent-region)
  4223. ;; Filling and auto-filling.
  4224. (org-setup-filling)
  4225. ;; Comments.
  4226. (org-setup-comments-handling)
  4227. ;; Initialize cache.
  4228. (org-element-cache-reset)
  4229. ;; Beginning/end of defun
  4230. (setq-local beginning-of-defun-function 'org-backward-element)
  4231. (setq-local end-of-defun-function
  4232. (lambda ()
  4233. (if (not (org-at-heading-p))
  4234. (org-forward-element)
  4235. (org-forward-element)
  4236. (forward-char -1))))
  4237. ;; Next error for sparse trees
  4238. (setq-local next-error-function 'org-occur-next-match)
  4239. ;; Make commit log messages from Org documents easier.
  4240. (setq-local add-log-current-defun-function #'org-add-log-current-headline)
  4241. ;; Make sure dependence stuff works reliably, even for users who set it
  4242. ;; too late :-(
  4243. (if org-enforce-todo-dependencies
  4244. (add-hook 'org-blocker-hook
  4245. 'org-block-todo-from-children-or-siblings-or-parent)
  4246. (remove-hook 'org-blocker-hook
  4247. 'org-block-todo-from-children-or-siblings-or-parent))
  4248. (if org-enforce-todo-checkbox-dependencies
  4249. (add-hook 'org-blocker-hook
  4250. 'org-block-todo-from-checkboxes)
  4251. (remove-hook 'org-blocker-hook
  4252. 'org-block-todo-from-checkboxes))
  4253. ;; Align options lines
  4254. (setq-local
  4255. align-mode-rules-list
  4256. '((org-in-buffer-settings
  4257. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4258. (modes . '(org-mode)))))
  4259. ;; Setup the pcomplete hooks
  4260. (setq-local pcomplete-command-completion-function #'org-pcomplete-initial)
  4261. (setq-local pcomplete-command-name-function #'org-command-at-point)
  4262. (setq-local pcomplete-default-completion-function #'ignore)
  4263. (setq-local pcomplete-parse-arguments-function #'org-parse-arguments)
  4264. (setq-local pcomplete-termination-string "")
  4265. (add-hook 'completion-at-point-functions
  4266. #'pcomplete-completions-at-point nil t)
  4267. (setq-local buffer-face-mode-face 'org-default)
  4268. ;; If empty file that did not turn on Org mode automatically, make
  4269. ;; it to.
  4270. (when (and org-insert-mode-line-in-empty-file
  4271. (called-interactively-p 'any)
  4272. (= (point-min) (point-max)))
  4273. (insert "# -*- mode: org -*-\n\n"))
  4274. (unless org-inhibit-startup
  4275. (org-unmodified
  4276. (when org-startup-with-beamer-mode (org-beamer-mode))
  4277. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4278. (org-table-map-tables
  4279. (cond ((and org-startup-align-all-tables
  4280. org-startup-shrink-all-tables)
  4281. (lambda () (org-table-align) (org-table-shrink)))
  4282. (org-startup-align-all-tables #'org-table-align)
  4283. (t #'org-table-shrink))
  4284. t))
  4285. (when org-startup-with-inline-images (org-display-inline-images))
  4286. (when org-startup-with-latex-preview (org-latex-preview '(16)))
  4287. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4288. (when org-startup-truncated (setq truncate-lines t))
  4289. (when org-startup-numerated (require 'org-num) (org-num-mode 1))
  4290. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))))
  4291. ;; Add a custom keymap for `visual-line-mode' so that activating
  4292. ;; this minor mode does not override Org's keybindings.
  4293. ;; FIXME: Probably `visual-line-mode' should take care of this.
  4294. (let ((oldmap (cdr (assoc 'visual-line-mode minor-mode-map-alist)))
  4295. (newmap (make-sparse-keymap)))
  4296. (set-keymap-parent newmap oldmap)
  4297. (define-key newmap [remap move-beginning-of-line] nil)
  4298. (define-key newmap [remap move-end-of-line] nil)
  4299. (define-key newmap [remap kill-line] nil)
  4300. (make-local-variable 'minor-mode-overriding-map-alist)
  4301. (push `(visual-line-mode . ,newmap) minor-mode-overriding-map-alist))
  4302. ;; Activate `org-table-header-line-mode'
  4303. (when org-table-header-line-p
  4304. (org-table-header-line-mode 1))
  4305. ;; Try to set `org-hide' face correctly.
  4306. (let ((foreground (org-find-invisible-foreground)))
  4307. (when foreground
  4308. (set-face-foreground 'org-hide foreground)))
  4309. ;; Set face extension as requested.
  4310. (org--set-faces-extend '(org-block-begin-line org-block-end-line)
  4311. org-fontify-whole-block-delimiter-line)
  4312. (org--set-faces-extend org-level-faces org-fontify-whole-heading-line))
  4313. ;; Update `customize-package-emacs-version-alist'
  4314. (add-to-list 'customize-package-emacs-version-alist
  4315. '(Org ("8.0" . "24.4")
  4316. ("8.1" . "24.4")
  4317. ("8.2" . "24.4")
  4318. ("8.2.7" . "24.4")
  4319. ("8.3" . "26.1")
  4320. ("9.0" . "26.1")
  4321. ("9.1" . "26.1")
  4322. ("9.2" . "27.1")
  4323. ("9.3" . "27.1")
  4324. ("9.4" . "27.2")
  4325. ("9.5" . "28.1")))
  4326. (defvar org-mode-transpose-word-syntax-table
  4327. (let ((st (make-syntax-table text-mode-syntax-table)))
  4328. (dolist (c org-emphasis-alist st)
  4329. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4330. (when (fboundp 'abbrev-table-put)
  4331. (abbrev-table-put org-mode-abbrev-table
  4332. :parents (list text-mode-abbrev-table)))
  4333. (defun org-find-invisible-foreground ()
  4334. (let ((candidates (remove
  4335. "unspecified-bg"
  4336. (nconc
  4337. (list (face-background 'default)
  4338. (face-background 'org-default))
  4339. (mapcar
  4340. (lambda (alist)
  4341. (when (boundp alist)
  4342. (cdr (assq 'background-color (symbol-value alist)))))
  4343. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4344. (list (face-foreground 'org-hide))))))
  4345. (car (remove nil candidates))))
  4346. (defun org-current-time (&optional rounding-minutes past)
  4347. "Current time, possibly rounded to ROUNDING-MINUTES.
  4348. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4349. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4350. the rounding returns a past time."
  4351. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4352. (car org-time-stamp-rounding-minutes)))
  4353. (now (current-time)))
  4354. (if (< r 1)
  4355. now
  4356. (let* ((time (decode-time now))
  4357. (res (apply #'encode-time 0 (* r (round (nth 1 time) r))
  4358. (nthcdr 2 time))))
  4359. (if (or (not past) (org-time-less-p res now))
  4360. res
  4361. (org-time-subtract res (* r 60)))))))
  4362. (defun org-today ()
  4363. "Return today date, considering `org-extend-today-until'."
  4364. (time-to-days
  4365. (org-time-since (* 3600 org-extend-today-until))))
  4366. ;;;; Font-Lock stuff, including the activators
  4367. (defconst org-match-sexp-depth 3
  4368. "Number of stacked braces for sub/superscript matching.")
  4369. (defun org-create-multibrace-regexp (left right n)
  4370. "Create a regular expression which will match a balanced sexp.
  4371. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4372. as single character strings.
  4373. The regexp returned will match the entire expression including the
  4374. delimiters. It will also define a single group which contains the
  4375. match except for the outermost delimiters. The maximum depth of
  4376. stacked delimiters is N. Escaping delimiters is not possible."
  4377. (let* ((nothing (concat "[^" left right "]*?"))
  4378. (or "\\|")
  4379. (re nothing)
  4380. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4381. (while (> n 1)
  4382. (setq n (1- n)
  4383. re (concat re or next)
  4384. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4385. (concat left "\\(" re "\\)" right)))
  4386. (defconst org-match-substring-regexp
  4387. (concat
  4388. "\\(\\S-\\)\\([_^]\\)\\("
  4389. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4390. "\\|"
  4391. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4392. "\\|"
  4393. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4394. "The regular expression matching a sub- or superscript.")
  4395. (defconst org-match-substring-with-braces-regexp
  4396. (concat
  4397. "\\(\\S-\\)\\([_^]\\)"
  4398. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4399. "The regular expression matching a sub- or superscript, forcing braces.")
  4400. (defvar org-emph-face nil)
  4401. (defun org-do-emphasis-faces (limit)
  4402. "Run through the buffer and emphasize strings."
  4403. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  4404. (car org-emphasis-regexp-components))))
  4405. (catch :exit
  4406. (while (re-search-forward quick-re limit t)
  4407. (let* ((marker (match-string 2))
  4408. (verbatim? (member marker '("~" "="))))
  4409. (when (save-excursion
  4410. (goto-char (match-beginning 0))
  4411. (and
  4412. ;; Do not match table hlines.
  4413. (not (and (equal marker "+")
  4414. (org-match-line
  4415. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  4416. ;; Do not match headline stars. Do not consider
  4417. ;; stars of a headline as closing marker for bold
  4418. ;; markup either.
  4419. (not (and (equal marker "*")
  4420. (save-excursion
  4421. (forward-char)
  4422. (skip-chars-backward "*")
  4423. (looking-at-p org-outline-regexp-bol))))
  4424. ;; Match full emphasis markup regexp.
  4425. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  4426. ;; Do not span over paragraph boundaries.
  4427. (not (string-match-p org-element-paragraph-separate
  4428. (match-string 2)))
  4429. ;; Do not span over cells in table rows.
  4430. (not (and (save-match-data (org-match-line "[ \t]*|"))
  4431. (string-match-p "|" (match-string 4))))))
  4432. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist))
  4433. (m (if org-hide-emphasis-markers 4 2)))
  4434. (font-lock-prepend-text-property
  4435. (match-beginning m) (match-end m) 'face face)
  4436. (when verbatim?
  4437. (org-remove-flyspell-overlays-in
  4438. (match-beginning 0) (match-end 0))
  4439. (remove-text-properties (match-beginning 2) (match-end 2)
  4440. '(display t invisible t intangible t)))
  4441. (add-text-properties (match-beginning 2) (match-end 2)
  4442. '(font-lock-multiline t org-emphasis t))
  4443. (when (and org-hide-emphasis-markers
  4444. (not (org-at-comment-p)))
  4445. (add-text-properties (match-end 4) (match-beginning 5)
  4446. '(invisible t))
  4447. (add-text-properties (match-beginning 3) (match-end 3)
  4448. '(invisible t)))
  4449. (throw :exit t))))))))
  4450. (defun org-emphasize (&optional char)
  4451. "Insert or change an emphasis, i.e. a font like bold or italic.
  4452. If there is an active region, change that region to a new emphasis.
  4453. If there is no region, just insert the marker characters and position
  4454. the cursor between them.
  4455. CHAR should be the marker character. If it is a space, it means to
  4456. remove the emphasis of the selected region.
  4457. If CHAR is not given (for example in an interactive call) it will be
  4458. prompted for."
  4459. (interactive)
  4460. (let ((erc org-emphasis-regexp-components)
  4461. (string "") beg end move s)
  4462. (if (org-region-active-p)
  4463. (setq beg (region-beginning)
  4464. end (region-end)
  4465. string (buffer-substring beg end))
  4466. (setq move t))
  4467. (unless char
  4468. (message "Emphasis marker or tag: [%s]"
  4469. (mapconcat #'car org-emphasis-alist ""))
  4470. (setq char (read-char-exclusive)))
  4471. (if (equal char ?\s)
  4472. (setq s ""
  4473. move nil)
  4474. (unless (assoc (char-to-string char) org-emphasis-alist)
  4475. (user-error "No such emphasis marker: \"%c\"" char))
  4476. (setq s (char-to-string char)))
  4477. (while (and (> (length string) 1)
  4478. (equal (substring string 0 1) (substring string -1))
  4479. (assoc (substring string 0 1) org-emphasis-alist))
  4480. (setq string (substring string 1 -1)))
  4481. (setq string (concat s string s))
  4482. (when beg (delete-region beg end))
  4483. (unless (or (bolp)
  4484. (string-match (concat "[" (nth 0 erc) "\n]")
  4485. (char-to-string (char-before (point)))))
  4486. (insert " "))
  4487. (unless (or (eobp)
  4488. (string-match (concat "[" (nth 1 erc) "\n]")
  4489. (char-to-string (char-after (point)))))
  4490. (insert " ") (backward-char 1))
  4491. (insert string)
  4492. (and move (backward-char 1))))
  4493. (defconst org-nonsticky-props
  4494. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  4495. (defsubst org-rear-nonsticky-at (pos)
  4496. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  4497. (defun org-activate-links (limit)
  4498. "Add link properties to links.
  4499. This includes angle, plain, and bracket links."
  4500. (catch :exit
  4501. (while (re-search-forward org-link-any-re limit t)
  4502. (let* ((start (match-beginning 0))
  4503. (end (match-end 0))
  4504. (visible-start (or (match-beginning 3) (match-beginning 2)))
  4505. (visible-end (or (match-end 3) (match-end 2)))
  4506. (style (cond ((eq ?< (char-after start)) 'angle)
  4507. ((eq ?\[ (char-after (1+ start))) 'bracket)
  4508. (t 'plain))))
  4509. (when (and (memq style org-highlight-links)
  4510. ;; Do not span over paragraph boundaries.
  4511. (not (string-match-p org-element-paragraph-separate
  4512. (match-string 0)))
  4513. ;; Do not confuse plain links with tags.
  4514. (not (and (eq style 'plain)
  4515. (let ((face (get-text-property
  4516. (max (1- start) (point-min)) 'face)))
  4517. (if (consp face) (memq 'org-tag face)
  4518. (eq 'org-tag face))))))
  4519. (let* ((link-object (save-excursion
  4520. (goto-char start)
  4521. (save-match-data (org-element-link-parser))))
  4522. (link (org-element-property :raw-link link-object))
  4523. (type (org-element-property :type link-object))
  4524. (path (org-element-property :path link-object))
  4525. (face-property (pcase (org-link-get-parameter type :face)
  4526. ((and (pred functionp) face) (funcall face path))
  4527. ((and (pred facep) face) face)
  4528. ((and (pred consp) face) face) ;anonymous
  4529. (_ 'org-link)))
  4530. (properties ;for link's visible part
  4531. (list 'mouse-face (or (org-link-get-parameter type :mouse-face)
  4532. 'highlight)
  4533. 'keymap (or (org-link-get-parameter type :keymap)
  4534. org-mouse-map)
  4535. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  4536. ((and (pred stringp) echo) echo)
  4537. ((and (pred functionp) echo) echo)
  4538. (_ (concat "LINK: " link)))
  4539. 'htmlize-link (pcase (org-link-get-parameter type
  4540. :htmlize-link)
  4541. ((and (pred functionp) f) (funcall f))
  4542. (_ `(:uri ,link)))
  4543. 'font-lock-multiline t)))
  4544. (org-remove-flyspell-overlays-in start end)
  4545. (org-rear-nonsticky-at end)
  4546. (if (not (eq 'bracket style))
  4547. (progn
  4548. (add-face-text-property start end face-property)
  4549. (add-text-properties start end properties))
  4550. ;; Handle invisible parts in bracket links.
  4551. (remove-text-properties start end '(invisible nil))
  4552. (let ((hidden
  4553. (append `(invisible
  4554. ,(or (org-link-get-parameter type :display)
  4555. 'org-link))
  4556. properties)))
  4557. (add-text-properties start visible-start hidden)
  4558. (add-face-text-property start end face-property)
  4559. (add-text-properties visible-start visible-end properties)
  4560. (add-text-properties visible-end end hidden)
  4561. (org-rear-nonsticky-at visible-start)
  4562. (org-rear-nonsticky-at visible-end)))
  4563. (let ((f (org-link-get-parameter type :activate-func)))
  4564. (when (functionp f)
  4565. (funcall f start end path (eq style 'bracket))))
  4566. (throw :exit t))))) ;signal success
  4567. nil))
  4568. (defun org-activate-code (limit)
  4569. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  4570. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4571. (remove-text-properties (match-beginning 0) (match-end 0)
  4572. '(display t invisible t intangible t))
  4573. t))
  4574. (defcustom org-src-fontify-natively t
  4575. "When non-nil, fontify code in code blocks.
  4576. See also the `org-block' face."
  4577. :type 'boolean
  4578. :version "26.1"
  4579. :package-version '(Org . "8.3")
  4580. :group 'org-appearance
  4581. :group 'org-babel)
  4582. (defcustom org-allow-promoting-top-level-subtree nil
  4583. "When non-nil, allow promoting a top level subtree.
  4584. The leading star of the top level headline will be replaced
  4585. by a #."
  4586. :type 'boolean
  4587. :version "24.1"
  4588. :group 'org-appearance)
  4589. (defun org-fontify-meta-lines-and-blocks (limit)
  4590. (condition-case nil
  4591. (org-fontify-meta-lines-and-blocks-1 limit)
  4592. (error (message "Org mode fontification error in %S at %d"
  4593. (current-buffer)
  4594. (line-number-at-pos)))))
  4595. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  4596. "Fontify #+ lines and blocks."
  4597. (let ((case-fold-search t))
  4598. (when (re-search-forward
  4599. (rx bol (group (zero-or-more (any " \t")) "#"
  4600. (group (group (or (seq "+" (one-or-more (any "a-zA-Z")) (optional ":"))
  4601. (any " \t")
  4602. eol))
  4603. (optional (group "_" (group (one-or-more (any "a-zA-Z"))))))
  4604. (zero-or-more (any " \t"))
  4605. (group (group (zero-or-more (not (any " \t\n"))))
  4606. (zero-or-more (any " \t"))
  4607. (group (zero-or-more any)))))
  4608. limit t)
  4609. (let ((beg (match-beginning 0))
  4610. (end-of-beginline (match-end 0))
  4611. ;; Including \n at end of #+begin line will include \n
  4612. ;; after the end of block content.
  4613. (block-start (match-end 0))
  4614. (block-end nil)
  4615. (lang (match-string 7)) ; The language, if it is a source block.
  4616. (bol-after-beginline (line-beginning-position 2))
  4617. (dc1 (downcase (match-string 2)))
  4618. (dc3 (downcase (match-string 3)))
  4619. (whole-blockline org-fontify-whole-block-delimiter-line)
  4620. beg-of-endline end-of-endline nl-before-endline quoting block-type)
  4621. (cond
  4622. ((and (match-end 4) (equal dc3 "+begin"))
  4623. ;; Truly a block
  4624. (setq block-type (downcase (match-string 5))
  4625. ;; Src, example, export, maybe more.
  4626. quoting (member block-type org-protecting-blocks))
  4627. (when (re-search-forward
  4628. (rx-to-string `(group bol (or (seq (one-or-more "*") space)
  4629. (seq (zero-or-more (any " \t"))
  4630. "#+end"
  4631. ,(match-string 4)
  4632. word-end
  4633. (zero-or-more any)))))
  4634. ;; We look further than LIMIT on purpose.
  4635. nil t)
  4636. ;; We do have a matching #+end line.
  4637. (setq beg-of-endline (match-beginning 0)
  4638. end-of-endline (match-end 0)
  4639. nl-before-endline (1- (match-beginning 0)))
  4640. (setq block-end (match-beginning 0)) ; Include the final newline.
  4641. (when quoting
  4642. (org-remove-flyspell-overlays-in bol-after-beginline nl-before-endline)
  4643. (remove-text-properties beg end-of-endline
  4644. '(display t invisible t intangible t)))
  4645. (add-text-properties
  4646. beg end-of-endline '(font-lock-fontified t font-lock-multiline t))
  4647. (org-remove-flyspell-overlays-in beg bol-after-beginline)
  4648. (org-remove-flyspell-overlays-in nl-before-endline end-of-endline)
  4649. (cond
  4650. ((and lang (not (string= lang "")) org-src-fontify-natively)
  4651. (save-match-data
  4652. (org-src-font-lock-fontify-block lang block-start block-end))
  4653. (add-text-properties bol-after-beginline block-end '(src-block t)))
  4654. (quoting
  4655. (add-text-properties
  4656. bol-after-beginline beg-of-endline
  4657. (list 'face
  4658. (list :inherit
  4659. (let ((face-name
  4660. (intern (format "org-block-%s" lang))))
  4661. (append (and (facep face-name) (list face-name))
  4662. '(org-block)))))))
  4663. ((not org-fontify-quote-and-verse-blocks))
  4664. ((string= block-type "quote")
  4665. (add-face-text-property
  4666. bol-after-beginline beg-of-endline 'org-quote t))
  4667. ((string= block-type "verse")
  4668. (add-face-text-property
  4669. bol-after-beginline beg-of-endline 'org-verse t)))
  4670. ;; Fontify the #+begin and #+end lines of the blocks
  4671. (add-text-properties
  4672. beg (if whole-blockline bol-after-beginline end-of-beginline)
  4673. '(face org-block-begin-line))
  4674. (unless (eq (char-after beg-of-endline) ?*)
  4675. (add-text-properties
  4676. beg-of-endline
  4677. (if whole-blockline
  4678. (let ((beg-of-next-line (1+ end-of-endline)))
  4679. (min (point-max) beg-of-next-line))
  4680. (min (point-max) end-of-endline))
  4681. '(face org-block-end-line)))
  4682. t))
  4683. ((member dc1 '("+title:" "+subtitle:" "+author:" "+email:" "+date:"))
  4684. (org-remove-flyspell-overlays-in
  4685. (match-beginning 0)
  4686. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  4687. (add-text-properties
  4688. beg (match-end 3)
  4689. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  4690. '(font-lock-fontified t invisible t)
  4691. '(font-lock-fontified t face org-document-info-keyword)))
  4692. (add-text-properties
  4693. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  4694. (if (string-equal dc1 "+title:")
  4695. '(font-lock-fontified t face org-document-title)
  4696. '(font-lock-fontified t face org-document-info))))
  4697. ((string-prefix-p "+caption" dc1)
  4698. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  4699. (remove-text-properties (match-beginning 0) (match-end 0)
  4700. '(display t invisible t intangible t))
  4701. ;; Handle short captions
  4702. (save-excursion
  4703. (beginning-of-line)
  4704. (looking-at (rx (group (zero-or-more (any " \t"))
  4705. "#+caption"
  4706. (optional "[" (zero-or-more any) "]")
  4707. ":")
  4708. (zero-or-more (any " \t")))))
  4709. (add-text-properties (line-beginning-position) (match-end 1)
  4710. '(font-lock-fontified t face org-meta-line))
  4711. (add-text-properties (match-end 0) (line-end-position)
  4712. '(font-lock-fontified t face org-block))
  4713. t)
  4714. ((member dc3 '(" " ""))
  4715. ;; Just a comment, the plus was not there
  4716. (org-remove-flyspell-overlays-in beg (match-end 0))
  4717. (add-text-properties
  4718. beg (match-end 0)
  4719. '(font-lock-fontified t face font-lock-comment-face)))
  4720. (t ;; Just any other in-buffer setting, but not indented
  4721. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4722. (remove-text-properties (match-beginning 0) (match-end 0)
  4723. '(display t invisible t intangible t))
  4724. (add-text-properties beg (match-end 0)
  4725. '(font-lock-fontified t face org-meta-line))
  4726. t))))))
  4727. (defun org-fontify-drawers (limit)
  4728. "Fontify drawers."
  4729. (when (re-search-forward org-drawer-regexp limit t)
  4730. (add-text-properties (1- (match-beginning 1)) (1+ (match-end 1))
  4731. '(font-lock-fontified t face org-drawer))
  4732. (org-remove-flyspell-overlays-in
  4733. (line-beginning-position) (line-beginning-position 2))
  4734. t))
  4735. (defun org-fontify-macros (limit)
  4736. "Fontify macros."
  4737. (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
  4738. (let ((begin (match-beginning 0))
  4739. (opening-end (match-beginning 1)))
  4740. (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
  4741. (match-string 1))
  4742. (let ((end (match-end 1))
  4743. (closing-start (match-beginning 1)))
  4744. (add-text-properties
  4745. begin end
  4746. '(font-lock-multiline t font-lock-fontified t face org-macro))
  4747. (org-remove-flyspell-overlays-in begin end)
  4748. (when org-hide-macro-markers
  4749. (add-text-properties begin opening-end '(invisible t))
  4750. (add-text-properties closing-start end '(invisible t)))
  4751. t)))))
  4752. (defun org-fontify-extend-region (beg end _old-len)
  4753. (let ((end (if (progn (goto-char end) (looking-at-p "^[*#]"))
  4754. (1+ end) end))
  4755. (begin-re "\\(\\\\\\[\\|\\(#\\+begin_\\|\\\\begin{\\)\\S-+\\)")
  4756. (end-re "\\(\\\\\\]\\|\\(#\\+end_\\|\\\\end{\\)\\S-+\\)")
  4757. (extend
  4758. (lambda (r1 r2 dir)
  4759. (let ((re (replace-regexp-in-string
  4760. "\\(begin\\|end\\)" r1
  4761. (replace-regexp-in-string
  4762. "[][]" r2
  4763. (match-string-no-properties 0)))))
  4764. (re-search-forward (regexp-quote re) nil t dir)))))
  4765. (goto-char beg)
  4766. (back-to-indentation)
  4767. (save-match-data
  4768. (cond ((looking-at end-re)
  4769. (cons (or (funcall extend "begin" "[" -1) beg) end))
  4770. ((looking-at begin-re)
  4771. (cons beg (or (funcall extend "end" "]" 1) end)))
  4772. (t (cons beg end))))))
  4773. (defun org-activate-footnote-links (limit)
  4774. "Add text properties for footnotes."
  4775. (let ((fn (org-footnote-next-reference-or-definition limit)))
  4776. (when fn
  4777. (let* ((beg (nth 1 fn))
  4778. (end (nth 2 fn))
  4779. (label (car fn))
  4780. (referencep (/= (line-beginning-position) beg)))
  4781. (when (and referencep (nth 3 fn))
  4782. (save-excursion
  4783. (goto-char beg)
  4784. (search-forward (or label "fn:"))
  4785. (org-remove-flyspell-overlays-in beg (match-end 0))))
  4786. (add-text-properties beg end
  4787. (list 'mouse-face 'highlight
  4788. 'keymap org-mouse-map
  4789. 'help-echo
  4790. (if referencep "Footnote reference"
  4791. "Footnote definition")
  4792. 'font-lock-fontified t
  4793. 'font-lock-multiline t
  4794. 'face 'org-footnote))))))
  4795. (defun org-activate-dates (limit)
  4796. "Add text properties for dates."
  4797. (when (and (re-search-forward org-tsr-regexp-both limit t)
  4798. (not (equal (char-before (match-beginning 0)) 91)))
  4799. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4800. (add-text-properties (match-beginning 0) (match-end 0)
  4801. (list 'mouse-face 'highlight
  4802. 'keymap org-mouse-map))
  4803. (org-rear-nonsticky-at (match-end 0))
  4804. (when org-display-custom-times
  4805. ;; If it's a date range, activate custom time for second date.
  4806. (when (match-end 3)
  4807. (org-display-custom-time (match-beginning 3) (match-end 3)))
  4808. (org-display-custom-time (match-beginning 1) (match-end 1)))
  4809. t))
  4810. (defun org-activate-target-links (limit)
  4811. "Add text properties for target matches."
  4812. (when org-target-link-regexp
  4813. (let ((case-fold-search t))
  4814. ;; `org-target-link-regexp' matches one character before the
  4815. ;; actual target.
  4816. (unless (bolp) (forward-char -1))
  4817. (when (re-search-forward org-target-link-regexp limit t)
  4818. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4819. (add-text-properties (match-beginning 1) (match-end 1)
  4820. (list 'mouse-face 'highlight
  4821. 'keymap org-mouse-map
  4822. 'help-echo "Radio target link"
  4823. 'org-linked-text t))
  4824. (org-rear-nonsticky-at (match-end 1))
  4825. t))))
  4826. (defvar org-latex-and-related-regexp nil
  4827. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  4828. (defun org-compute-latex-and-related-regexp ()
  4829. "Compute regular expression for LaTeX, entities and sub/superscript.
  4830. Result depends on variable `org-highlight-latex-and-related'."
  4831. (let ((re-sub
  4832. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  4833. ((eq org-use-sub-superscripts '{})
  4834. (list org-match-substring-with-braces-regexp))
  4835. (org-use-sub-superscripts (list org-match-substring-regexp))))
  4836. (re-latex
  4837. (when (or (memq 'latex org-highlight-latex-and-related)
  4838. (memq 'native org-highlight-latex-and-related))
  4839. (let ((matchers (plist-get org-format-latex-options :matchers)))
  4840. (delq nil
  4841. (mapcar (lambda (x)
  4842. (and (member (car x) matchers) (nth 1 x)))
  4843. org-latex-regexps)))))
  4844. (re-entities
  4845. (when (memq 'entities org-highlight-latex-and-related)
  4846. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\
  4847. \\($\\|{}\\|[^[:alpha:]]\\)"))))
  4848. (setq-local org-latex-and-related-regexp
  4849. (mapconcat #'identity
  4850. (append re-latex re-entities re-sub)
  4851. "\\|"))))
  4852. (defun org-do-latex-and-related (limit)
  4853. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  4854. Stop at first highlighted object, if any. Return t if some
  4855. highlighting was done, nil otherwise."
  4856. (when (org-string-nw-p org-latex-and-related-regexp)
  4857. (let ((latex-prefix-re (rx (or "$" "\\(" "\\[")))
  4858. (blank-line-re (rx (and "\n" (zero-or-more (or " " "\t")) "\n"))))
  4859. (catch 'found
  4860. (while (and (< (point) limit)
  4861. (re-search-forward org-latex-and-related-regexp nil t))
  4862. (cond
  4863. ((>= (match-beginning 0) limit)
  4864. (throw 'found nil))
  4865. ((cl-some (lambda (f)
  4866. (memq f '(org-code org-verbatim underline
  4867. org-special-keyword)))
  4868. (save-excursion
  4869. (goto-char (1+ (match-beginning 0)))
  4870. (face-at-point nil t))))
  4871. ;; Try to limit false positives. In this case, ignore
  4872. ;; $$...$$, \(...\), and \[...\] LaTeX constructs if they
  4873. ;; contain an empty line.
  4874. ((save-excursion
  4875. (goto-char (match-beginning 0))
  4876. (and (looking-at-p latex-prefix-re)
  4877. (save-match-data
  4878. (re-search-forward blank-line-re (1- (match-end 0)) t)))))
  4879. (t
  4880. (let* ((offset (if (memq (char-after (1+ (match-beginning 0)))
  4881. '(?_ ?^))
  4882. 1
  4883. 0))
  4884. (start (+ offset (match-beginning 0)))
  4885. (end (match-end 0)))
  4886. (if (memq 'native org-highlight-latex-and-related)
  4887. (org-src-font-lock-fontify-block "latex" start end)
  4888. (font-lock-prepend-text-property start end
  4889. 'face 'org-latex-and-related))
  4890. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  4891. '(font-lock-multiline t))
  4892. (throw 'found t)))))
  4893. nil))))
  4894. (defun org-restart-font-lock ()
  4895. "Restart `font-lock-mode', to force refontification."
  4896. (when font-lock-mode
  4897. (font-lock-mode -1)
  4898. (font-lock-mode 1)))
  4899. (defun org-activate-tags (limit)
  4900. (when (re-search-forward org-tag-line-re limit t)
  4901. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4902. (add-text-properties (match-beginning 1) (match-end 1)
  4903. (list 'mouse-face 'highlight
  4904. 'keymap org-mouse-map))
  4905. (org-rear-nonsticky-at (match-end 1))
  4906. t))
  4907. (defun org-outline-level ()
  4908. "Compute the outline level of the heading at point.
  4909. If this is called at a normal headline, the level is the number
  4910. of stars. Use `org-reduced-level' to remove the effect of
  4911. `org-odd-levels'. Unlike to `org-current-level', this function
  4912. takes into consideration inlinetasks."
  4913. (org-with-wide-buffer
  4914. (end-of-line)
  4915. (if (re-search-backward org-outline-regexp-bol nil t)
  4916. (1- (- (match-end 0) (match-beginning 0)))
  4917. 0)))
  4918. (defvar org-font-lock-keywords nil)
  4919. (defsubst org-re-property (property &optional literal allow-null value)
  4920. "Return a regexp matching a PROPERTY line.
  4921. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  4922. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  4923. non-nil, match properties even without a value.
  4924. Match group 3 is set to the value when it exists. If there is no
  4925. value and ALLOW-NULL is non-nil, it is set to the empty string.
  4926. With optional argument VALUE, match only property lines with
  4927. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  4928. unless LITERAL is non-nil."
  4929. (concat
  4930. "^\\(?4:[ \t]*\\)"
  4931. (format "\\(?1::\\(?2:%s\\):\\)"
  4932. (if literal property (regexp-quote property)))
  4933. (cond (value
  4934. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  4935. (if literal value (regexp-quote value))))
  4936. (allow-null
  4937. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  4938. (t
  4939. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  4940. (defconst org-property-re
  4941. (org-re-property "\\S-+" 'literal t)
  4942. "Regular expression matching a property line.
  4943. There are four matching groups:
  4944. 1: :PROPKEY: including the leading and trailing colon,
  4945. 2: PROPKEY without the leading and trailing colon,
  4946. 3: PROPVAL without leading or trailing spaces,
  4947. 4: the indentation of the current line,
  4948. 5: trailing whitespace.")
  4949. (defvar org-font-lock-hook nil
  4950. "Functions to be called for special font lock stuff.")
  4951. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  4952. (defvar org-font-lock-set-keywords-hook nil
  4953. "Functions that can manipulate `org-font-lock-extra-keywords'.
  4954. This is called after `org-font-lock-extra-keywords' is defined, but before
  4955. it is installed to be used by font lock. This can be useful if something
  4956. needs to be inserted at a specific position in the font-lock sequence.")
  4957. (defun org-font-lock-hook (limit)
  4958. "Run `org-font-lock-hook' within LIMIT."
  4959. (run-hook-with-args 'org-font-lock-hook limit))
  4960. (defun org-set-font-lock-defaults ()
  4961. "Set font lock defaults for the current buffer."
  4962. (let ((org-font-lock-extra-keywords
  4963. (list
  4964. ;; Call the hook
  4965. '(org-font-lock-hook)
  4966. ;; Headlines
  4967. `(,(if org-fontify-whole-heading-line
  4968. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  4969. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  4970. (1 (org-get-level-face 1))
  4971. (2 (org-get-level-face 2))
  4972. (3 (org-get-level-face 3)))
  4973. ;; Table lines
  4974. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  4975. (1 'org-table t))
  4976. ;; Table internals
  4977. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  4978. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  4979. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  4980. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  4981. ;; Properties
  4982. (list org-property-re
  4983. '(1 'org-special-keyword t)
  4984. '(3 'org-property-value t))
  4985. ;; Drawers
  4986. '(org-fontify-drawers)
  4987. ;; Link related fontification.
  4988. '(org-activate-links)
  4989. (when (memq 'tag org-highlight-links) '(org-activate-tags (1 'org-tag prepend)))
  4990. (when (memq 'radio org-highlight-links) '(org-activate-target-links (1 'org-link t)))
  4991. (when (memq 'date org-highlight-links) '(org-activate-dates (0 'org-date t)))
  4992. (when (memq 'footnote org-highlight-links) '(org-activate-footnote-links))
  4993. ;; Targets.
  4994. (list org-radio-target-regexp '(0 'org-target t))
  4995. (list org-target-regexp '(0 'org-target t))
  4996. ;; Diary sexps.
  4997. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  4998. ;; Macro
  4999. '(org-fontify-macros)
  5000. ;; TODO keyword
  5001. (list (format org-heading-keyword-regexp-format
  5002. org-todo-regexp)
  5003. '(2 (org-get-todo-face 2) prepend))
  5004. ;; TODO
  5005. (when org-fontify-todo-headline
  5006. (list (format org-heading-keyword-regexp-format
  5007. (concat
  5008. "\\(?:"
  5009. (mapconcat 'regexp-quote org-not-done-keywords "\\|")
  5010. "\\)"))
  5011. '(2 'org-headline-todo prepend)))
  5012. ;; DONE
  5013. (when org-fontify-done-headline
  5014. (list (format org-heading-keyword-regexp-format
  5015. (concat
  5016. "\\(?:"
  5017. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5018. "\\)"))
  5019. '(2 'org-headline-done prepend)))
  5020. ;; Priorities
  5021. '(org-font-lock-add-priority-faces)
  5022. ;; Tags
  5023. '(org-font-lock-add-tag-faces)
  5024. ;; Tags groups
  5025. (when (and org-group-tags org-tag-groups-alist)
  5026. (list (concat org-outline-regexp-bol ".+\\(:"
  5027. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5028. ":\\).*$")
  5029. '(1 'org-tag-group prepend)))
  5030. ;; Special keywords
  5031. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5032. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5033. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5034. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5035. ;; Emphasis
  5036. (when org-fontify-emphasized-text '(org-do-emphasis-faces))
  5037. ;; Checkboxes
  5038. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5039. 1 'org-checkbox prepend)
  5040. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5041. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5042. (0 (org-get-checkbox-statistics-face) prepend)))
  5043. ;; Description list items
  5044. '("\\(?:^[ \t]*[-+]\\|^[ \t]+[*]\\)[ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5045. 1 'org-list-dt prepend)
  5046. ;; Inline export snippets
  5047. '("\\(@@\\)\\([a-z-]+:\\).*?\\(@@\\)"
  5048. (1 'font-lock-comment-face t)
  5049. (2 'org-tag t)
  5050. (3 'font-lock-comment-face t))
  5051. ;; ARCHIVEd headings
  5052. (list (concat
  5053. org-outline-regexp-bol
  5054. "\\(.*:" org-archive-tag ":.*\\)")
  5055. '(1 'org-archived prepend))
  5056. ;; Specials
  5057. '(org-do-latex-and-related)
  5058. '(org-fontify-entities)
  5059. '(org-raise-scripts)
  5060. ;; Code
  5061. '(org-activate-code (1 'org-code t))
  5062. ;; COMMENT
  5063. (list (format
  5064. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5065. org-todo-regexp
  5066. org-comment-string)
  5067. '(9 'org-special-keyword t))
  5068. ;; Blocks and meta lines
  5069. '(org-fontify-meta-lines-and-blocks)
  5070. ;; Citations
  5071. '(org-cite-activate))))
  5072. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5073. (run-hooks 'org-font-lock-set-keywords-hook)
  5074. ;; Now set the full font-lock-keywords
  5075. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5076. (setq-local font-lock-defaults
  5077. '(org-font-lock-keywords t nil nil backward-paragraph))
  5078. (setq-local font-lock-extend-after-change-region-function
  5079. #'org-fontify-extend-region)
  5080. (kill-local-variable 'font-lock-keywords)
  5081. nil))
  5082. (defun org-toggle-pretty-entities ()
  5083. "Toggle the composition display of entities as UTF8 characters."
  5084. (interactive)
  5085. (setq-local org-pretty-entities (not org-pretty-entities))
  5086. (org-restart-font-lock)
  5087. (if org-pretty-entities
  5088. (message "Entities are now displayed as UTF8 characters")
  5089. (save-restriction
  5090. (widen)
  5091. (decompose-region (point-min) (point-max))
  5092. (message "Entities are now displayed as plain text"))))
  5093. (defvar-local org-custom-properties-overlays nil
  5094. "List of overlays used for custom properties.")
  5095. (defun org-toggle-custom-properties-visibility ()
  5096. "Display or hide properties in `org-custom-properties'."
  5097. (interactive)
  5098. (if org-custom-properties-overlays
  5099. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5100. (setq org-custom-properties-overlays nil))
  5101. (when org-custom-properties
  5102. (org-with-wide-buffer
  5103. (goto-char (point-min))
  5104. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5105. (while (re-search-forward regexp nil t)
  5106. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5107. (when (and end (< (point) end))
  5108. ;; Hide first custom property in current drawer.
  5109. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5110. (overlay-put o 'invisible t)
  5111. (overlay-put o 'org-custom-property t)
  5112. (push o org-custom-properties-overlays))
  5113. ;; Hide additional custom properties in the same drawer.
  5114. (while (re-search-forward regexp end t)
  5115. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5116. (overlay-put o 'invisible t)
  5117. (overlay-put o 'org-custom-property t)
  5118. (push o org-custom-properties-overlays)))))
  5119. ;; Each entry is limited to a single property drawer.
  5120. (outline-next-heading)))))))
  5121. (defun org-fontify-entities (limit)
  5122. "Find an entity to fontify."
  5123. (let (ee)
  5124. (when org-pretty-entities
  5125. (catch 'match
  5126. ;; "\_ "-family is left out on purpose. Only the first one,
  5127. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5128. ;; confusing when adding a second white space character.
  5129. (while (re-search-forward
  5130. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5131. limit t)
  5132. (when (and (not (org-at-comment-p))
  5133. (setq ee (org-entity-get (match-string 1)))
  5134. (= (length (nth 6 ee)) 1))
  5135. (let* ((end (if (equal (match-string 2) "{}")
  5136. (match-end 2)
  5137. (match-end 1))))
  5138. (add-text-properties
  5139. (match-beginning 0) end
  5140. (list 'font-lock-fontified t))
  5141. (compose-region (match-beginning 0) end
  5142. (nth 6 ee) nil)
  5143. (backward-char 1)
  5144. (throw 'match t))))
  5145. nil))))
  5146. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5147. "Fontify string S like in Org mode."
  5148. (with-temp-buffer
  5149. (insert s)
  5150. (let ((org-odd-levels-only odd-levels))
  5151. (org-mode)
  5152. (org-font-lock-ensure)
  5153. (buffer-string))))
  5154. (defun org-get-level-face (n)
  5155. "Get the right face for match N in font-lock matching of headlines."
  5156. (let* ((org-l0 (- (match-end 2) (match-beginning 1) 1))
  5157. (org-l (if org-odd-levels-only (1+ (/ org-l0 2)) org-l0))
  5158. (org-f (if org-cycle-level-faces
  5159. (nth (% (1- org-l) org-n-level-faces) org-level-faces)
  5160. (nth (1- (min org-l org-n-level-faces)) org-level-faces))))
  5161. (cond
  5162. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5163. ((eq n 2) org-f)
  5164. (t (unless org-level-color-stars-only org-f)))))
  5165. (defun org-face-from-face-or-color (context inherit face-or-color)
  5166. "Create a face list that inherits INHERIT, but sets the foreground color.
  5167. When FACE-OR-COLOR is not a string, just return it."
  5168. (if (stringp face-or-color)
  5169. (list :inherit inherit
  5170. (cdr (assoc context org-faces-easy-properties))
  5171. face-or-color)
  5172. face-or-color))
  5173. (defun org-get-todo-face (kwd)
  5174. "Get the right face for a TODO keyword KWD.
  5175. If KWD is a number, get the corresponding match group."
  5176. (when (numberp kwd) (setq kwd (match-string kwd)))
  5177. (or (org-face-from-face-or-color
  5178. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5179. (and (member kwd org-done-keywords) 'org-done)
  5180. 'org-todo))
  5181. (defun org-get-priority-face (priority)
  5182. "Get the right face for PRIORITY.
  5183. PRIORITY is a character."
  5184. (or (org-face-from-face-or-color
  5185. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5186. 'org-priority))
  5187. (defun org-get-tag-face (tag)
  5188. "Get the right face for TAG.
  5189. If TAG is a number, get the corresponding match group."
  5190. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5191. (or (org-face-from-face-or-color
  5192. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5193. 'org-tag)))
  5194. (defvar org-priority-regexp) ; defined later in the file
  5195. (defun org-font-lock-add-priority-faces (limit)
  5196. "Add the special priority faces."
  5197. (while (re-search-forward (concat "^\\*+" org-priority-regexp) limit t)
  5198. (let ((beg (match-beginning 1))
  5199. (end (1+ (match-end 2))))
  5200. (add-face-text-property
  5201. beg end
  5202. (org-get-priority-face (string-to-char (match-string 2))))
  5203. (add-text-properties
  5204. beg end
  5205. (list 'font-lock-fontified t)))))
  5206. (defun org-font-lock-add-tag-faces (limit)
  5207. "Add the special tag faces."
  5208. (when (and org-tag-faces org-tags-special-faces-re)
  5209. (while (re-search-forward org-tags-special-faces-re limit t)
  5210. (add-face-text-property
  5211. (match-beginning 1)
  5212. (match-end 1)
  5213. (org-get-tag-face 1))
  5214. (add-text-properties (match-beginning 1) (match-end 1)
  5215. (list 'font-lock-fontified t))
  5216. (backward-char 1))))
  5217. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5218. "Remove fontification and activation overlays from links."
  5219. (font-lock-default-unfontify-region beg end)
  5220. (with-silent-modifications
  5221. (decompose-region beg end)
  5222. (remove-text-properties beg end
  5223. '(mouse-face t keymap t org-linked-text t
  5224. invisible t intangible t
  5225. org-emphasis t))
  5226. (org-remove-font-lock-display-properties beg end)))
  5227. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5228. ((raise 0.3) (height 0.7))
  5229. ((raise -0.5))
  5230. ((raise 0.5)))
  5231. "Display properties for showing superscripts and subscripts.")
  5232. (defun org-remove-font-lock-display-properties (beg end)
  5233. "Remove specific display properties that have been added by font lock.
  5234. The will remove the raise properties that are used to show superscripts
  5235. and subscripts."
  5236. (let (next prop)
  5237. (while (< beg end)
  5238. (setq next (next-single-property-change beg 'display nil end)
  5239. prop (get-text-property beg 'display))
  5240. (when (member prop org-script-display)
  5241. (put-text-property beg next 'display nil))
  5242. (setq beg next))))
  5243. (defun org-raise-scripts (limit)
  5244. "Add raise properties to sub/superscripts."
  5245. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5246. (re-search-forward
  5247. (if (eq org-use-sub-superscripts t)
  5248. org-match-substring-regexp
  5249. org-match-substring-with-braces-regexp)
  5250. limit t))
  5251. (let* ((pos (point)) table-p comment-p
  5252. (mpos (match-beginning 3))
  5253. (emph-p (get-text-property mpos 'org-emphasis))
  5254. (link-p (get-text-property mpos 'mouse-face))
  5255. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5256. (goto-char (line-beginning-position))
  5257. (setq table-p (looking-at-p org-table-dataline-regexp)
  5258. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5259. (goto-char pos)
  5260. ;; Handle a_b^c
  5261. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5262. (unless (or comment-p emph-p link-p keyw-p)
  5263. (put-text-property (match-beginning 3) (match-end 0)
  5264. 'display
  5265. (if (equal (char-after (match-beginning 2)) ?^)
  5266. (nth (if table-p 3 1) org-script-display)
  5267. (nth (if table-p 2 0) org-script-display)))
  5268. (add-text-properties (match-beginning 2) (match-end 2)
  5269. (list 'invisible t))
  5270. (when (and (eq (char-after (match-beginning 3)) ?{)
  5271. (eq (char-before (match-end 3)) ?}))
  5272. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5273. (list 'invisible t))
  5274. (add-text-properties (1- (match-end 3)) (match-end 3)
  5275. (list 'invisible t))))
  5276. t)))
  5277. (defun org-remove-empty-overlays-at (pos)
  5278. "Remove outline overlays that do not contain non-white stuff."
  5279. (dolist (o (overlays-at pos))
  5280. (and (eq 'outline (overlay-get o 'invisible))
  5281. (not (string-match-p
  5282. "\\S-" (buffer-substring (overlay-start o)
  5283. (overlay-end o))))
  5284. (delete-overlay o))))
  5285. (defun org-show-empty-lines-in-parent ()
  5286. "Move to the parent and re-show empty lines before visible headlines."
  5287. (save-excursion
  5288. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  5289. (org-cycle-show-empty-lines context))))
  5290. (defun org-files-list ()
  5291. "Return `org-agenda-files' list, plus all open Org files.
  5292. This is useful for operations that need to scan all of a user's
  5293. open and agenda-wise Org files."
  5294. (let ((files (mapcar #'expand-file-name (org-agenda-files))))
  5295. (dolist (buf (buffer-list))
  5296. (with-current-buffer buf
  5297. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  5298. (cl-pushnew (expand-file-name (buffer-file-name)) files
  5299. :test #'equal))))
  5300. files))
  5301. (defsubst org-entry-beginning-position ()
  5302. "Return the beginning position of the current entry."
  5303. (save-excursion (org-back-to-heading t) (point)))
  5304. (defsubst org-entry-end-position ()
  5305. "Return the end position of the current entry."
  5306. (save-excursion (outline-next-heading) (point)))
  5307. (defun org-subtree-end-visible-p ()
  5308. "Is the end of the current subtree visible?"
  5309. (pos-visible-in-window-p
  5310. (save-excursion (org-end-of-subtree t) (point))))
  5311. (defun org-first-headline-recenter ()
  5312. "Move cursor to the first headline and recenter the headline."
  5313. (let ((window (get-buffer-window)))
  5314. (when window
  5315. (goto-char (point-min))
  5316. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  5317. (set-window-start window (line-beginning-position))))))
  5318. ;;; Visibility (headlines, blocks, drawers)
  5319. ;;;; Headlines visibility
  5320. (defun org-show-entry ()
  5321. "Show the body directly following its heading.
  5322. Show the heading too, if it is currently invisible."
  5323. (interactive)
  5324. (save-excursion
  5325. (org-back-to-heading-or-point-min t)
  5326. (org-flag-region
  5327. (line-end-position 0)
  5328. (save-excursion
  5329. (if (re-search-forward
  5330. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  5331. (match-beginning 1)
  5332. (point-max)))
  5333. nil
  5334. 'outline)
  5335. (org-cycle-hide-drawers 'children)))
  5336. (defun org-hide-entry ()
  5337. "Hide the body directly following its heading."
  5338. (interactive)
  5339. (save-excursion
  5340. (org-back-to-heading-or-point-min t)
  5341. (when (org-at-heading-p) (forward-line))
  5342. (org-flag-region
  5343. (line-end-position 0)
  5344. (save-excursion
  5345. (if (re-search-forward
  5346. (concat "[\r\n]" org-outline-regexp) nil t)
  5347. (line-end-position 0)
  5348. (point-max)))
  5349. t
  5350. 'outline)))
  5351. (defun org-show-children (&optional level)
  5352. "Show all direct subheadings of this heading.
  5353. Prefix arg LEVEL is how many levels below the current level
  5354. should be shown. Default is enough to cause the following
  5355. heading to appear."
  5356. (interactive "p")
  5357. (unless (org-before-first-heading-p)
  5358. (save-excursion
  5359. (org-with-limited-levels (org-back-to-heading t))
  5360. (let* ((current-level (funcall outline-level))
  5361. (max-level (org-get-valid-level
  5362. current-level
  5363. (if level (prefix-numeric-value level) 1)))
  5364. (end (save-excursion (org-end-of-subtree t t)))
  5365. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  5366. (past-first-child nil)
  5367. ;; Make sure to skip inlinetasks.
  5368. (re (format regexp-fmt
  5369. current-level
  5370. (cond
  5371. ((not (featurep 'org-inlinetask)) "")
  5372. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  5373. 3))
  5374. (t (1- org-inlinetask-min-level))))))
  5375. ;; Display parent heading.
  5376. (org-flag-heading nil)
  5377. (forward-line)
  5378. ;; Display children. First child may be deeper than expected
  5379. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  5380. ;; MAX-LEVEL accordingly.
  5381. (while (re-search-forward re end t)
  5382. (unless past-first-child
  5383. (setq re (format regexp-fmt
  5384. current-level
  5385. (max (funcall outline-level) max-level)))
  5386. (setq past-first-child t))
  5387. (org-flag-heading nil))))))
  5388. (defun org-show-subtree ()
  5389. "Show everything after this heading at deeper levels."
  5390. (interactive)
  5391. (org-flag-region
  5392. (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
  5393. ;;;; Blocks and drawers visibility
  5394. (defun org--hide-wrapper-toggle (element category force no-error)
  5395. "Toggle visibility for ELEMENT.
  5396. ELEMENT is a block or drawer type parsed element. CATEGORY is
  5397. either `block' or `drawer'. When FORCE is `off', show the block
  5398. or drawer. If it is non-nil, hide it unconditionally. Throw an
  5399. error when not at a block or drawer, unless NO-ERROR is non-nil.
  5400. Return a non-nil value when toggling is successful."
  5401. (let ((type (org-element-type element)))
  5402. (cond
  5403. ((memq type
  5404. (pcase category
  5405. (`drawer '(drawer property-drawer))
  5406. (`block '(center-block
  5407. comment-block dynamic-block example-block export-block
  5408. quote-block special-block src-block verse-block))
  5409. (_ (error "Unknown category: %S" category))))
  5410. (let* ((post (org-element-property :post-affiliated element))
  5411. (start (save-excursion
  5412. (goto-char post)
  5413. (line-end-position)))
  5414. (end (save-excursion
  5415. (goto-char (org-element-property :end element))
  5416. (skip-chars-backward " \t\n")
  5417. (line-end-position))))
  5418. ;; Do nothing when not before or at the block opening line or
  5419. ;; at the block closing line.
  5420. (unless (let ((eol (line-end-position)))
  5421. (and (> eol start) (/= eol end)))
  5422. (let* ((spec (if (eq category 'block) 'org-hide-block 'outline))
  5423. (flag
  5424. (cond ((eq force 'off) nil)
  5425. (force t)
  5426. ((eq spec (get-char-property start 'invisible)) nil)
  5427. (t t))))
  5428. (org-flag-region start end flag spec))
  5429. ;; When the block is hidden away, make sure point is left in
  5430. ;; a visible part of the buffer.
  5431. (when (invisible-p (max (1- (point)) (point-min)))
  5432. (goto-char post))
  5433. ;; Signal success.
  5434. t)))
  5435. (no-error nil)
  5436. (t
  5437. (user-error (if (eq category 'drawer)
  5438. "Not at a drawer"
  5439. "Not at a block"))))))
  5440. (defun org-hide-block-toggle (&optional force no-error element)
  5441. "Toggle the visibility of the current block.
  5442. When optional argument FORCE is `off', make block visible. If it
  5443. is non-nil, hide it unconditionally. Throw an error when not at
  5444. a block, unless NO-ERROR is non-nil. When optional argument
  5445. ELEMENT is provided, consider it instead of the current block.
  5446. Return a non-nil value when toggling is successful."
  5447. (interactive)
  5448. (org--hide-wrapper-toggle
  5449. (or element (org-element-at-point)) 'block force no-error))
  5450. (defun org-hide-drawer-toggle (&optional force no-error element)
  5451. "Toggle the visibility of the current drawer.
  5452. When optional argument FORCE is `off', make drawer visible. If
  5453. it is non-nil, hide it unconditionally. Throw an error when not
  5454. at a drawer, unless NO-ERROR is non-nil. When optional argument
  5455. ELEMENT is provided, consider it instead of the current drawer.
  5456. Return a non-nil value when toggling is successful."
  5457. (interactive)
  5458. (org--hide-wrapper-toggle
  5459. (or element (org-element-at-point)) 'drawer force no-error))
  5460. (defun org-hide-block-all ()
  5461. "Fold all blocks in the current buffer."
  5462. (interactive)
  5463. (org-show-all '(blocks))
  5464. (org-block-map 'org-hide-block-toggle))
  5465. (defun org-hide-drawer-all ()
  5466. "Fold all drawers in the current buffer."
  5467. (let ((begin (point-min))
  5468. (end (point-max)))
  5469. (org--hide-drawers begin end)))
  5470. (defun org-cycle-hide-drawers (state)
  5471. "Re-hide all drawers after a visibility state change.
  5472. STATE should be one of the symbols listed in the docstring of
  5473. `org-cycle-hook'."
  5474. (when (derived-mode-p 'org-mode)
  5475. (cond ((not (memq state '(overview folded contents)))
  5476. (let* ((global? (eq state 'all))
  5477. (beg (if global? (point-min) (line-beginning-position)))
  5478. (end (cond (global? (point-max))
  5479. ((eq state 'children) (org-entry-end-position))
  5480. (t (save-excursion (org-end-of-subtree t t))))))
  5481. (org--hide-drawers beg end)))
  5482. ((memq state '(overview contents))
  5483. ;; Hide drawers before first heading.
  5484. (let ((beg (point-min))
  5485. (end (save-excursion
  5486. (goto-char (point-min))
  5487. (if (org-before-first-heading-p)
  5488. (org-entry-end-position)
  5489. (point-min)))))
  5490. (when (< beg end)
  5491. (org--hide-drawers beg end)))))))
  5492. (defun org--hide-drawers (begin end)
  5493. "Hide all drawers between BEGIN and END."
  5494. (save-excursion
  5495. (goto-char begin)
  5496. (while (re-search-forward org-drawer-regexp end t)
  5497. (let* ((pair (get-char-property-and-overlay (line-beginning-position)
  5498. 'invisible))
  5499. (o (cdr-safe pair)))
  5500. (if (overlayp o) (goto-char (overlay-end o)) ;invisible drawer
  5501. (pcase (get-char-property-and-overlay (point) 'invisible)
  5502. (`(outline . ,o) (goto-char (overlay-end o))) ;already folded
  5503. (_
  5504. (let* ((drawer (org-element-at-point))
  5505. (type (org-element-type drawer)))
  5506. (when (memq type '(drawer property-drawer))
  5507. (org-hide-drawer-toggle t nil drawer)
  5508. ;; Make sure to skip drawer entirely or we might flag it
  5509. ;; another time when matching its ending line with
  5510. ;; `org-drawer-regexp'.
  5511. (goto-char (org-element-property :end drawer)))))))))))
  5512. ;;;; Visibility cycling
  5513. (defvar-local org-cycle-global-status nil)
  5514. (put 'org-cycle-global-status 'org-state t)
  5515. (defvar-local org-cycle-subtree-status nil)
  5516. (put 'org-cycle-subtree-status 'org-state t)
  5517. (defun org-show-all (&optional types)
  5518. "Show all contents in the visible part of the buffer.
  5519. By default, the function expands headings, blocks and drawers.
  5520. When optional argument TYPE is a list of symbols among `blocks',
  5521. `drawers' and `headings', to only expand one specific type."
  5522. (interactive)
  5523. (let ((types (or types '(blocks drawers headings))))
  5524. (when (memq 'blocks types)
  5525. (org-flag-region (point-min) (point-max) nil 'org-hide-block))
  5526. (cond
  5527. ;; Fast path. Since headings and drawers share the same
  5528. ;; invisible spec, clear everything in one go.
  5529. ((and (memq 'headings types)
  5530. (memq 'drawers types))
  5531. (org-flag-region (point-min) (point-max) nil 'outline))
  5532. ((memq 'headings types)
  5533. (org-flag-region (point-min) (point-max) nil 'outline)
  5534. (org-cycle-hide-drawers 'all))
  5535. ((memq 'drawers types)
  5536. (save-excursion
  5537. (goto-char (point-min))
  5538. (while (re-search-forward org-drawer-regexp nil t)
  5539. (let* ((pair (get-char-property-and-overlay (line-beginning-position)
  5540. 'invisible))
  5541. (o (cdr-safe pair)))
  5542. (if (overlayp o) (goto-char (overlay-end o))
  5543. (pcase (get-char-property-and-overlay (point) 'invisible)
  5544. (`(outline . ,o)
  5545. (goto-char (overlay-end o))
  5546. (delete-overlay o))
  5547. (_ nil))))))))))
  5548. ;;;###autoload
  5549. (defun org-cycle (&optional arg)
  5550. "TAB-action and visibility cycling for Org mode.
  5551. This is the command invoked in Org mode by the `TAB' key. Its main
  5552. purpose is outline visibility cycling, but it also invokes other actions
  5553. in special contexts.
  5554. When this function is called with a `\\[universal-argument]' prefix, rotate \
  5555. the entire
  5556. buffer through 3 states (global cycling)
  5557. 1. OVERVIEW: Show only top-level headlines.
  5558. 2. CONTENTS: Show all headlines of all levels, but no body text.
  5559. 3. SHOW ALL: Show everything.
  5560. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  5561. switch to the startup visibility,
  5562. determined by the variable `org-startup-folded', and by any VISIBILITY
  5563. properties in the buffer.
  5564. With a `\\[universal-argument] \\[universal-argument] \
  5565. \\[universal-argument]' prefix argument, show the entire buffer, including
  5566. any drawers.
  5567. When inside a table, re-align the table and move to the next field.
  5568. When point is at the beginning of a headline, rotate the subtree started
  5569. by this line through 3 different states (local cycling)
  5570. 1. FOLDED: Only the main headline is shown.
  5571. 2. CHILDREN: The main headline and the direct children are shown.
  5572. From this state, you can move to one of the children
  5573. and zoom in further.
  5574. 3. SUBTREE: Show the entire subtree, including body text.
  5575. If there is no subtree, switch directly from CHILDREN to FOLDED.
  5576. When point is at the beginning of an empty headline and the variable
  5577. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  5578. of the headline by demoting and promoting it to likely levels. This
  5579. speeds up creation document structure by pressing `TAB' once or several
  5580. times right after creating a new headline.
  5581. When there is a numeric prefix, go up to a heading with level ARG, do
  5582. a `show-subtree' and return to the previous cursor position. If ARG
  5583. is negative, go up that many levels.
  5584. When point is not at the beginning of a headline, execute the global
  5585. binding for `TAB', which is re-indenting the line. See the option
  5586. `org-cycle-emulate-tab' for details.
  5587. As a special case, if point is at the very beginning of the buffer, if
  5588. there is no headline there, and if the variable `org-cycle-global-at-bob'
  5589. is non-nil, this function acts as if called with prefix argument \
  5590. \(`\\[universal-argument] TAB',
  5591. same as `S-TAB') also when called without prefix argument."
  5592. (interactive "P")
  5593. (org-load-modules-maybe)
  5594. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  5595. (and org-cycle-level-after-item/entry-creation
  5596. (or (org-cycle-level)
  5597. (org-cycle-item-indentation))))
  5598. (let* ((limit-level
  5599. (or org-cycle-max-level
  5600. (and (boundp 'org-inlinetask-min-level)
  5601. org-inlinetask-min-level
  5602. (1- org-inlinetask-min-level))))
  5603. (nstars
  5604. (and limit-level
  5605. (if org-odd-levels-only
  5606. (1- (* 2 limit-level))
  5607. limit-level)))
  5608. (org-outline-regexp
  5609. (format "\\*%s " (if nstars (format "\\{1,%d\\}" nstars) "+"))))
  5610. (cond
  5611. ((equal arg '(16))
  5612. (setq last-command 'dummy)
  5613. (org-set-startup-visibility)
  5614. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  5615. ((equal arg '(64))
  5616. (org-show-all)
  5617. (org-unlogged-message "Entire buffer visible, including drawers"))
  5618. ((equal arg '(4)) (org-cycle-internal-global))
  5619. ;; Show-subtree, ARG levels up from here.
  5620. ((integerp arg)
  5621. (save-excursion
  5622. (org-back-to-heading)
  5623. (outline-up-heading (if (< arg 0) (- arg)
  5624. (- (funcall outline-level) arg)))
  5625. (org-show-subtree)))
  5626. ;; Global cycling at BOB: delegate to `org-cycle-internal-global'.
  5627. ((and org-cycle-global-at-bob
  5628. (bobp)
  5629. (not (looking-at org-outline-regexp)))
  5630. (let ((org-cycle-hook
  5631. (remq 'org-optimize-window-after-visibility-change
  5632. org-cycle-hook)))
  5633. (org-cycle-internal-global)))
  5634. ;; Try CDLaTeX TAB completion.
  5635. ((org-try-cdlatex-tab))
  5636. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  5637. ((and (featurep 'org-inlinetask)
  5638. (org-inlinetask-at-task-p)
  5639. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5640. (org-inlinetask-toggle-visibility))
  5641. (t
  5642. (let ((pos (point))
  5643. (element (org-element-at-point)))
  5644. (cond
  5645. ;; Try toggling visibility for block at point.
  5646. ((org-hide-block-toggle nil t element))
  5647. ;; Try toggling visibility for drawer at point.
  5648. ((org-hide-drawer-toggle nil t element))
  5649. ;; Table: enter it or move to the next field.
  5650. ((and (org-match-line "[ \t]*[|+]")
  5651. (org-element-lineage element '(table) t))
  5652. (if (and (eq 'table (org-element-type element))
  5653. (eq 'table.el (org-element-property :type element)))
  5654. (message (substitute-command-keys "\\<org-mode-map>\
  5655. Use `\\[org-edit-special]' to edit table.el tables"))
  5656. (org-table-justify-field-maybe)
  5657. (call-interactively #'org-table-next-field)))
  5658. ((run-hook-with-args-until-success
  5659. 'org-tab-after-check-for-table-hook))
  5660. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  5661. ((and (or (and org-cycle-include-plain-lists
  5662. (let ((item (org-element-lineage element
  5663. '(item plain-list)
  5664. t)))
  5665. (and item
  5666. (= (line-beginning-position)
  5667. (org-element-property :post-affiliated
  5668. item)))))
  5669. (org-match-line org-outline-regexp))
  5670. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5671. (org-cycle-internal-local))
  5672. ;; From there: TAB emulation and template completion.
  5673. (buffer-read-only (org-back-to-heading))
  5674. ((run-hook-with-args-until-success
  5675. 'org-tab-after-check-for-cycling-hook))
  5676. ((run-hook-with-args-until-success
  5677. 'org-tab-before-tab-emulation-hook))
  5678. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  5679. (or (not (bolp))
  5680. (not (looking-at org-outline-regexp))))
  5681. (call-interactively (global-key-binding (kbd "TAB"))))
  5682. ((or (eq org-cycle-emulate-tab t)
  5683. (and (memq org-cycle-emulate-tab '(white whitestart))
  5684. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  5685. (or (and (eq org-cycle-emulate-tab 'white)
  5686. (= (match-end 0) (line-end-position)))
  5687. (and (eq org-cycle-emulate-tab 'whitestart)
  5688. (>= (match-end 0) pos)))))
  5689. (call-interactively (global-key-binding (kbd "TAB"))))
  5690. (t
  5691. (save-excursion
  5692. (org-back-to-heading)
  5693. (org-cycle))))))))))
  5694. (defun org-cycle-internal-global ()
  5695. "Do the global cycling action."
  5696. ;; Hack to avoid display of messages for .org attachments in Gnus
  5697. (let ((ga (string-match-p "\\*fontification" (buffer-name))))
  5698. (cond
  5699. ((and (eq last-command this-command)
  5700. (eq org-cycle-global-status 'overview))
  5701. ;; We just created the overview - now do table of contents
  5702. ;; This can be slow in very large buffers, so indicate action
  5703. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  5704. (unless ga (org-unlogged-message "CONTENTS..."))
  5705. (org-content)
  5706. (unless ga (org-unlogged-message "CONTENTS...done"))
  5707. (setq org-cycle-global-status 'contents)
  5708. (run-hook-with-args 'org-cycle-hook 'contents))
  5709. ((and (eq last-command this-command)
  5710. (eq org-cycle-global-status 'contents))
  5711. ;; We just showed the table of contents - now show everything
  5712. (run-hook-with-args 'org-pre-cycle-hook 'all)
  5713. (org-show-all '(headings blocks))
  5714. (unless ga (org-unlogged-message "SHOW ALL"))
  5715. (setq org-cycle-global-status 'all)
  5716. (run-hook-with-args 'org-cycle-hook 'all))
  5717. (t
  5718. ;; Default action: go to overview
  5719. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  5720. (org-overview)
  5721. (unless ga (org-unlogged-message "OVERVIEW"))
  5722. (setq org-cycle-global-status 'overview)
  5723. (run-hook-with-args 'org-cycle-hook 'overview)))))
  5724. (defvar org-called-with-limited-levels nil
  5725. "Non-nil when `org-with-limited-levels' is currently active.")
  5726. (defun org-cycle-internal-local ()
  5727. "Do the local cycling action."
  5728. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  5729. ;; First, determine end of headline (EOH), end of subtree or item
  5730. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  5731. (save-excursion
  5732. (if (org-at-item-p)
  5733. (progn
  5734. (beginning-of-line)
  5735. (setq struct (org-list-struct))
  5736. (setq eoh (line-end-position))
  5737. (setq eos (org-list-get-item-end-before-blank (point) struct))
  5738. (setq has-children (org-list-has-child-p (point) struct)))
  5739. (org-back-to-heading)
  5740. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  5741. (setq eos (save-excursion
  5742. (org-end-of-subtree t t)
  5743. (unless (eobp) (forward-char -1))
  5744. (point)))
  5745. (setq has-children
  5746. (or
  5747. (save-excursion
  5748. (let ((level (funcall outline-level)))
  5749. (outline-next-heading)
  5750. (and (org-at-heading-p t)
  5751. (> (funcall outline-level) level))))
  5752. (and (eq org-cycle-include-plain-lists 'integrate)
  5753. (save-excursion
  5754. (org-list-search-forward (org-item-beginning-re) eos t))))))
  5755. ;; Determine end invisible part of buffer (EOL)
  5756. (beginning-of-line 2)
  5757. (while (and (not (eobp)) ;this is like `next-line'
  5758. (get-char-property (1- (point)) 'invisible))
  5759. (goto-char (next-single-char-property-change (point) 'invisible))
  5760. (and (eolp) (beginning-of-line 2)))
  5761. (setq eol (point)))
  5762. ;; Find out what to do next and set `this-command'
  5763. (cond
  5764. ((= eos eoh)
  5765. ;; Nothing is hidden behind this heading
  5766. (unless (org-before-first-heading-p)
  5767. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  5768. (org-unlogged-message "EMPTY ENTRY")
  5769. (setq org-cycle-subtree-status nil)
  5770. (save-excursion
  5771. (goto-char eos)
  5772. (outline-next-heading)
  5773. (when (org-invisible-p) (org-flag-heading nil))))
  5774. ((and (or (>= eol eos)
  5775. (not (string-match "\\S-" (buffer-substring eol eos))))
  5776. (or has-children
  5777. (not (setq children-skipped
  5778. org-cycle-skip-children-state-if-no-children))))
  5779. ;; Entire subtree is hidden in one line: children view
  5780. (unless (org-before-first-heading-p)
  5781. (run-hook-with-args 'org-pre-cycle-hook 'children))
  5782. (if (org-at-item-p)
  5783. (org-list-set-item-visibility (line-beginning-position) struct 'children)
  5784. (org-show-entry)
  5785. (org-with-limited-levels (org-show-children))
  5786. (org-show-set-visibility 'tree)
  5787. ;; Fold every list in subtree to top-level items.
  5788. (when (eq org-cycle-include-plain-lists 'integrate)
  5789. (save-excursion
  5790. (org-back-to-heading)
  5791. (while (org-list-search-forward (org-item-beginning-re) eos t)
  5792. (beginning-of-line 1)
  5793. (let* ((struct (org-list-struct))
  5794. (prevs (org-list-prevs-alist struct))
  5795. (end (org-list-get-bottom-point struct)))
  5796. (dolist (e (org-list-get-all-items (point) struct prevs))
  5797. (org-list-set-item-visibility e struct 'folded))
  5798. (goto-char (if (< end eos) end eos)))))))
  5799. (org-unlogged-message "CHILDREN")
  5800. (save-excursion
  5801. (goto-char eos)
  5802. (outline-next-heading)
  5803. (when (org-invisible-p) (org-flag-heading nil)))
  5804. (setq org-cycle-subtree-status 'children)
  5805. (unless (org-before-first-heading-p)
  5806. (run-hook-with-args 'org-cycle-hook 'children)))
  5807. ((or children-skipped
  5808. (and (eq last-command this-command)
  5809. (eq org-cycle-subtree-status 'children)))
  5810. ;; We just showed the children, or no children are there,
  5811. ;; now show everything.
  5812. (unless (org-before-first-heading-p)
  5813. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  5814. (org-flag-region eoh eos nil 'outline)
  5815. (org-unlogged-message
  5816. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  5817. (setq org-cycle-subtree-status 'subtree)
  5818. (unless (org-before-first-heading-p)
  5819. (run-hook-with-args 'org-cycle-hook 'subtree)))
  5820. (t
  5821. ;; Default action: hide the subtree.
  5822. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  5823. (org-flag-region eoh eos t 'outline)
  5824. (org-unlogged-message "FOLDED")
  5825. (setq org-cycle-subtree-status 'folded)
  5826. (unless (org-before-first-heading-p)
  5827. (run-hook-with-args 'org-cycle-hook 'folded))))))
  5828. ;;;###autoload
  5829. (defun org-global-cycle (&optional arg)
  5830. "Cycle the global visibility. For details see `org-cycle'.
  5831. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  5832. With a numeric prefix, show all headlines up to that level."
  5833. (interactive "P")
  5834. (cond
  5835. ((integerp arg)
  5836. (org-content arg)
  5837. (setq org-cycle-global-status 'contents))
  5838. ((equal arg '(4))
  5839. (org-set-startup-visibility)
  5840. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  5841. (t
  5842. (org-cycle '(4)))))
  5843. (defun org-set-startup-visibility ()
  5844. "Set the visibility required by startup options and properties."
  5845. (cond
  5846. ((eq org-startup-folded t)
  5847. (org-overview))
  5848. ((eq org-startup-folded 'content)
  5849. (org-content))
  5850. ((eq org-startup-folded 'show2levels)
  5851. (org-content 2))
  5852. ((eq org-startup-folded 'show3levels)
  5853. (org-content 3))
  5854. ((eq org-startup-folded 'show4levels)
  5855. (org-content 4))
  5856. ((eq org-startup-folded 'show5levels)
  5857. (org-content 5))
  5858. ((or (eq org-startup-folded 'showeverything)
  5859. (eq org-startup-folded nil))
  5860. (org-show-all)))
  5861. (unless (eq org-startup-folded 'showeverything)
  5862. (when org-hide-block-startup (org-hide-block-all))
  5863. (org-set-visibility-according-to-property)
  5864. (org-cycle-hide-archived-subtrees 'all)
  5865. (org-cycle-hide-drawers 'all)
  5866. (org-cycle-show-empty-lines t)))
  5867. (defun org-set-visibility-according-to-property ()
  5868. "Switch subtree visibility according to VISIBILITY property."
  5869. (interactive)
  5870. (let ((regexp (org-re-property "VISIBILITY")))
  5871. (org-with-point-at 1
  5872. (while (re-search-forward regexp nil t)
  5873. (let ((state (match-string 3)))
  5874. (if (not (org-at-property-p)) (outline-next-heading)
  5875. (save-excursion
  5876. (org-back-to-heading t)
  5877. (org-flag-subtree t)
  5878. (org-reveal)
  5879. (pcase state
  5880. ("folded"
  5881. (org-flag-subtree t))
  5882. ("children"
  5883. (org-show-hidden-entry)
  5884. (org-show-children))
  5885. ("content"
  5886. (save-excursion
  5887. (save-restriction
  5888. (org-narrow-to-subtree)
  5889. (org-content))))
  5890. ((or "all" "showall")
  5891. (outline-show-subtree))
  5892. (_ nil)))
  5893. (org-end-of-subtree)))))))
  5894. (defun org-overview ()
  5895. "Switch to overview mode, showing only top-level headlines."
  5896. (interactive)
  5897. (org-show-all '(headings drawers))
  5898. (save-excursion
  5899. (goto-char (point-min))
  5900. (when (re-search-forward org-outline-regexp-bol nil t)
  5901. (let* ((last (line-end-position))
  5902. (level (- (match-end 0) (match-beginning 0) 1))
  5903. (regexp (format "^\\*\\{1,%d\\} " level)))
  5904. (while (re-search-forward regexp nil :move)
  5905. (org-flag-region last (line-end-position 0) t 'outline)
  5906. (setq last (line-end-position))
  5907. (setq level (- (match-end 0) (match-beginning 0) 1))
  5908. (setq regexp (format "^\\*\\{1,%d\\} " level)))
  5909. (org-flag-region last (point) t 'outline)))))
  5910. (defun org-content (&optional arg)
  5911. "Show all headlines in the buffer, like a table of contents.
  5912. With numerical argument N, show content up to level N."
  5913. (interactive "p")
  5914. (org-show-all '(headings drawers))
  5915. (save-excursion
  5916. (goto-char (point-max))
  5917. (let ((regexp (if (and (wholenump arg) (> arg 0))
  5918. (format "^\\*\\{1,%d\\} " arg)
  5919. "^\\*+ "))
  5920. (last (point)))
  5921. (while (re-search-backward regexp nil t)
  5922. (org-flag-region (line-end-position) last t 'outline)
  5923. (setq last (line-end-position 0))))))
  5924. (defvar org-scroll-position-to-restore nil
  5925. "Temporarily store scroll position to restore.")
  5926. (defun org-optimize-window-after-visibility-change (state)
  5927. "Adjust the window after a change in outline visibility.
  5928. This function is the default value of the hook `org-cycle-hook'."
  5929. (when (get-buffer-window (current-buffer))
  5930. (let ((repeat (eq last-command this-command)))
  5931. (unless repeat
  5932. (setq org-scroll-position-to-restore nil))
  5933. (cond
  5934. ((eq state 'content) nil)
  5935. ((eq state 'all) nil)
  5936. ((and org-scroll-position-to-restore repeat
  5937. (eq state 'folded))
  5938. (set-window-start nil org-scroll-position-to-restore))
  5939. ((eq state 'folded) nil)
  5940. ((eq state 'children)
  5941. (setq org-scroll-position-to-restore (window-start))
  5942. (or (org-subtree-end-visible-p) (recenter 1)))
  5943. ((eq state 'subtree)
  5944. (unless repeat
  5945. (setq org-scroll-position-to-restore (window-start)))
  5946. (or (org-subtree-end-visible-p) (recenter 1)))))))
  5947. (defun org-clean-visibility-after-subtree-move ()
  5948. "Fix visibility issues after moving a subtree."
  5949. ;; First, find a reasonable region to look at:
  5950. ;; Start two siblings above, end three below
  5951. (let* ((beg (save-excursion
  5952. (and (org-get-previous-sibling)
  5953. (org-get-previous-sibling))
  5954. (point)))
  5955. (end (save-excursion
  5956. (and (org-get-next-sibling)
  5957. (org-get-next-sibling)
  5958. (org-get-next-sibling))
  5959. (if (org-at-heading-p)
  5960. (line-end-position)
  5961. (point))))
  5962. (level (looking-at "\\*+"))
  5963. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  5964. (save-excursion
  5965. (save-restriction
  5966. (narrow-to-region beg end)
  5967. (when re
  5968. ;; Properly fold already folded siblings
  5969. (goto-char (point-min))
  5970. (while (re-search-forward re nil t)
  5971. (when (and (not (org-invisible-p))
  5972. (org-invisible-p (line-end-position)))
  5973. (outline-hide-entry))))
  5974. (org-cycle-hide-drawers 'all)
  5975. (org-cycle-show-empty-lines 'overview)))))
  5976. (defun org-cycle-show-empty-lines (state)
  5977. "Show empty lines above all visible headlines.
  5978. The region to be covered depends on STATE when called through
  5979. `org-cycle-hook'. Lisp program can use t for STATE to get the
  5980. entire buffer covered. Note that an empty line is only shown if there
  5981. are at least `org-cycle-separator-lines' empty lines before the headline."
  5982. (when (/= org-cycle-separator-lines 0)
  5983. (save-excursion
  5984. (let* ((n (abs org-cycle-separator-lines))
  5985. (re (cond
  5986. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  5987. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  5988. (t (let ((ns (number-to-string (- n 2))))
  5989. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  5990. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  5991. beg end)
  5992. (cond
  5993. ((memq state '(overview contents t))
  5994. (setq beg (point-min) end (point-max)))
  5995. ((memq state '(children folded))
  5996. (setq beg (point)
  5997. end (progn (org-end-of-subtree t t)
  5998. (line-beginning-position 2)))))
  5999. (when beg
  6000. (goto-char beg)
  6001. (while (re-search-forward re end t)
  6002. (unless (get-char-property (match-end 1) 'invisible)
  6003. (let ((e (match-end 1))
  6004. (b (if (>= org-cycle-separator-lines 0)
  6005. (match-beginning 1)
  6006. (save-excursion
  6007. (goto-char (match-beginning 0))
  6008. (skip-chars-backward " \t\n")
  6009. (line-end-position)))))
  6010. (org-flag-region b e nil 'outline))))))))
  6011. ;; Never hide empty lines at the end of the file.
  6012. (save-excursion
  6013. (goto-char (point-max))
  6014. (outline-previous-heading)
  6015. (outline-end-of-heading)
  6016. (when (and (looking-at "[ \t\n]+")
  6017. (= (match-end 0) (point-max)))
  6018. (org-flag-region (point) (match-end 0) nil 'outline))))
  6019. ;;;; Reveal point location
  6020. (defun org-show-context (&optional key)
  6021. "Make sure point and context are visible.
  6022. Optional argument KEY, when non-nil, is a symbol. See
  6023. `org-show-context-detail' for allowed values and how much is to
  6024. be shown."
  6025. (org-show-set-visibility
  6026. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  6027. ((cdr (assq key org-show-context-detail)))
  6028. (t (cdr (assq 'default org-show-context-detail))))))
  6029. (defun org-show-set-visibility (detail)
  6030. "Set visibility around point according to DETAIL.
  6031. DETAIL is either nil, `minimal', `local', `ancestors',
  6032. `ancestors-full', `lineage', `tree', `canonical' or t. See
  6033. `org-show-context-detail' for more information."
  6034. ;; Show current heading and possibly its entry, following headline
  6035. ;; or all children.
  6036. (if (and (org-at-heading-p) (not (eq detail 'local)))
  6037. (org-flag-heading nil)
  6038. (org-show-entry)
  6039. ;; If point is hidden within a drawer or a block, make sure to
  6040. ;; expose it.
  6041. (dolist (o (overlays-at (point)))
  6042. (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
  6043. (delete-overlay o)))
  6044. (unless (org-before-first-heading-p)
  6045. (org-with-limited-levels
  6046. (cl-case detail
  6047. ((tree canonical t) (org-show-children))
  6048. ((nil minimal ancestors ancestors-full))
  6049. (t (save-excursion
  6050. (outline-next-heading)
  6051. (org-flag-heading nil)))))))
  6052. ;; Show whole subtree.
  6053. (when (eq detail 'ancestors-full) (org-show-subtree))
  6054. ;; Show all siblings.
  6055. (when (eq detail 'lineage) (org-show-siblings))
  6056. ;; Show ancestors, possibly with their children.
  6057. (when (memq detail '(ancestors ancestors-full lineage tree canonical t))
  6058. (save-excursion
  6059. (while (org-up-heading-safe)
  6060. (org-flag-heading nil)
  6061. (when (memq detail '(canonical t)) (org-show-entry))
  6062. (when (memq detail '(tree canonical t)) (org-show-children))))))
  6063. (defvar org-reveal-start-hook nil
  6064. "Hook run before revealing a location.")
  6065. (defun org-reveal (&optional siblings)
  6066. "Show current entry, hierarchy above it, and the following headline.
  6067. This can be used to show a consistent set of context around
  6068. locations exposed with `org-show-context'.
  6069. With optional argument SIBLINGS, on each level of the hierarchy all
  6070. siblings are shown. This repairs the tree structure to what it would
  6071. look like when opened with hierarchical calls to `org-cycle'.
  6072. With a \\[universal-argument] \\[universal-argument] prefix, \
  6073. go to the parent and show the entire tree."
  6074. (interactive "P")
  6075. (run-hooks 'org-reveal-start-hook)
  6076. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  6077. ((equal siblings '(16))
  6078. (save-excursion
  6079. (when (org-up-heading-safe)
  6080. (org-show-subtree)
  6081. (run-hook-with-args 'org-cycle-hook 'subtree))))
  6082. (t (org-show-set-visibility 'lineage))))
  6083. ;;; Indirect buffer display of subtrees
  6084. (defvar org-indirect-dedicated-frame nil
  6085. "This is the frame being used for indirect tree display.")
  6086. (defvar org-last-indirect-buffer nil)
  6087. (defun org-tree-to-indirect-buffer (&optional arg)
  6088. "Create indirect buffer and narrow it to current subtree.
  6089. With a numerical prefix ARG, go up to this level and then take that tree.
  6090. If ARG is negative, go up that many levels.
  6091. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6092. indirect buffer previously made with this command, to avoid proliferation of
  6093. indirect buffers. However, when you call the command with a \
  6094. `\\[universal-argument]' prefix, or
  6095. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  6096. so that you can work with several indirect buffers at the same time. If
  6097. `org-indirect-buffer-display' is `dedicated-frame', the \
  6098. `\\[universal-argument]' prefix also
  6099. requests that a new frame be made for the new buffer, so that the dedicated
  6100. frame is not changed."
  6101. (interactive "P")
  6102. (let ((cbuf (current-buffer))
  6103. (cwin (selected-window))
  6104. (pos (point))
  6105. beg end level heading ibuf)
  6106. (save-excursion
  6107. (org-back-to-heading t)
  6108. (when (numberp arg)
  6109. (setq level (org-outline-level))
  6110. (when (< arg 0) (setq arg (+ level arg)))
  6111. (while (> (setq level (org-outline-level)) arg)
  6112. (org-up-heading-safe)))
  6113. (setq beg (point)
  6114. heading (org-get-heading 'no-tags))
  6115. (org-end-of-subtree t t)
  6116. (when (and (not (eobp)) (org-at-heading-p)) (backward-char 1))
  6117. (setq end (point)))
  6118. (when (and (buffer-live-p org-last-indirect-buffer)
  6119. (not (eq org-indirect-buffer-display 'new-frame))
  6120. (not arg))
  6121. (kill-buffer org-last-indirect-buffer))
  6122. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6123. org-last-indirect-buffer ibuf)
  6124. (cond
  6125. ((or (eq org-indirect-buffer-display 'new-frame)
  6126. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6127. (select-frame (make-frame))
  6128. (delete-other-windows)
  6129. (pop-to-buffer-same-window ibuf)
  6130. (org-set-frame-title heading))
  6131. ((eq org-indirect-buffer-display 'dedicated-frame)
  6132. (raise-frame
  6133. (select-frame (or (and org-indirect-dedicated-frame
  6134. (frame-live-p org-indirect-dedicated-frame)
  6135. org-indirect-dedicated-frame)
  6136. (setq org-indirect-dedicated-frame (make-frame)))))
  6137. (delete-other-windows)
  6138. (pop-to-buffer-same-window ibuf)
  6139. (org-set-frame-title (concat "Indirect: " heading)))
  6140. ((eq org-indirect-buffer-display 'current-window)
  6141. (pop-to-buffer-same-window ibuf))
  6142. ((eq org-indirect-buffer-display 'other-window)
  6143. (pop-to-buffer ibuf))
  6144. (t (error "Invalid value")))
  6145. (narrow-to-region beg end)
  6146. (org-show-all '(headings drawers blocks))
  6147. (goto-char pos)
  6148. (run-hook-with-args 'org-cycle-hook 'all)
  6149. (and (window-live-p cwin) (select-window cwin))))
  6150. (defun org-get-indirect-buffer (&optional buffer heading)
  6151. (setq buffer (or buffer (current-buffer)))
  6152. (let ((n 1) (base (buffer-name buffer)) bname)
  6153. (while (buffer-live-p
  6154. (get-buffer
  6155. (setq bname
  6156. (concat base "-"
  6157. (if heading (concat heading "-" (number-to-string n))
  6158. (number-to-string n))))))
  6159. (setq n (1+ n)))
  6160. (condition-case nil
  6161. (make-indirect-buffer buffer bname 'clone)
  6162. (error (make-indirect-buffer buffer bname)))))
  6163. (defun org-set-frame-title (title)
  6164. "Set the title of the current frame to the string TITLE."
  6165. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6166. ;;;; Structure editing
  6167. ;;; Inserting headlines
  6168. (defun org--blank-before-heading-p (&optional parent)
  6169. "Non-nil when an empty line should precede a new heading here.
  6170. When optional argument PARENT is non-nil, consider parent
  6171. headline instead of current one."
  6172. (pcase (assq 'heading org-blank-before-new-entry)
  6173. (`(heading . auto)
  6174. (save-excursion
  6175. (org-with-limited-levels
  6176. (unless (and (org-before-first-heading-p)
  6177. (not (outline-next-heading)))
  6178. (org-back-to-heading t)
  6179. (when parent (org-up-heading-safe))
  6180. (cond ((not (bobp))
  6181. (org-previous-line-empty-p))
  6182. ((outline-next-heading)
  6183. (org-previous-line-empty-p))
  6184. ;; Ignore trailing spaces on last buffer line.
  6185. ((progn (skip-chars-backward " \t") (bolp))
  6186. (org-previous-line-empty-p))
  6187. (t nil))))))
  6188. (`(heading . ,value) value)
  6189. (_ nil)))
  6190. (defun org-insert-heading (&optional arg invisible-ok top)
  6191. "Insert a new heading or an item with the same depth at point.
  6192. If point is at the beginning of a heading, insert a new heading
  6193. or a new headline above the current one. When at the beginning
  6194. of a regular line of text, turn it into a heading.
  6195. If point is in the middle of a line, split it and create a new
  6196. headline with the text in the current line after point (see
  6197. `org-M-RET-may-split-line' on how to modify this behavior). As
  6198. a special case, on a headline, splitting can only happen on the
  6199. title itself. E.g., this excludes breaking stars or tags.
  6200. With a `\\[universal-argument]' prefix, set \
  6201. `org-insert-heading-respect-content' to
  6202. a non-nil value for the duration of the command. This forces the
  6203. insertion of a heading after the current subtree, independently
  6204. on the location of point.
  6205. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6206. insert the heading at the end of the tree
  6207. above the current heading. For example, if point is within a
  6208. 2nd-level heading, then it will insert a 2nd-level heading at
  6209. the end of the 1st-level parent subtree.
  6210. When INVISIBLE-OK is set, stop at invisible headlines when going
  6211. back. This is important for non-interactive uses of the
  6212. command.
  6213. When optional argument TOP is non-nil, insert a level 1 heading,
  6214. unconditionally."
  6215. (interactive "P")
  6216. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6217. (level (org-current-level))
  6218. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6219. (cond
  6220. ((or org-insert-heading-respect-content
  6221. (member arg '((4) (16)))
  6222. (and (not invisible-ok)
  6223. (invisible-p (max (1- (point)) (point-min)))))
  6224. ;; Position point at the location of insertion. Make sure we
  6225. ;; end up on a visible headline if INVISIBLE-OK is nil.
  6226. (org-with-limited-levels
  6227. (if (not level) (outline-next-heading) ;before first headline
  6228. (org-back-to-heading invisible-ok)
  6229. (when (equal arg '(16)) (org-up-heading-safe))
  6230. (org-end-of-subtree)))
  6231. (unless (bolp) (insert "\n"))
  6232. (when (and blank? (save-excursion
  6233. (backward-char)
  6234. (org-before-first-heading-p)))
  6235. (insert "\n")
  6236. (backward-char))
  6237. (when (and (not level) (not (eobp)) (not (bobp)))
  6238. (when (org-at-heading-p) (insert "\n"))
  6239. (backward-char))
  6240. (unless (and blank? (org-previous-line-empty-p))
  6241. (org-N-empty-lines-before-current (if blank? 1 0)))
  6242. (insert stars " ")
  6243. ;; When INVISIBLE-OK is non-nil, ensure newly created headline
  6244. ;; is visible.
  6245. (unless invisible-ok
  6246. (pcase (get-char-property-and-overlay (point) 'invisible)
  6247. (`(outline . ,o)
  6248. (move-overlay o (overlay-start o) (line-end-position 0)))
  6249. (_ nil))))
  6250. ;; At a headline...
  6251. ((org-at-heading-p)
  6252. (cond ((bolp)
  6253. (when blank? (save-excursion (insert "\n")))
  6254. (save-excursion (insert stars " \n"))
  6255. (unless (and blank? (org-previous-line-empty-p))
  6256. (org-N-empty-lines-before-current (if blank? 1 0)))
  6257. (end-of-line))
  6258. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6259. (org-match-line org-complex-heading-regexp)
  6260. (org-pos-in-match-range (point) 4))
  6261. ;; Grab the text that should moved to the new headline.
  6262. ;; Preserve tags.
  6263. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6264. (if (looking-at "[ \t]*$") (replace-match "")
  6265. (org-align-tags))
  6266. (end-of-line)
  6267. (when blank? (insert "\n"))
  6268. (insert "\n" stars " ")
  6269. (when (org-string-nw-p split) (insert split))))
  6270. (t
  6271. (end-of-line)
  6272. (when blank? (insert "\n"))
  6273. (insert "\n" stars " "))))
  6274. ;; On regular text, turn line into a headline or split, if
  6275. ;; appropriate.
  6276. ((bolp)
  6277. (insert stars " ")
  6278. (unless (and blank? (org-previous-line-empty-p))
  6279. (org-N-empty-lines-before-current (if blank? 1 0))))
  6280. (t
  6281. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6282. (end-of-line))
  6283. (insert "\n" stars " ")
  6284. (unless (and blank? (org-previous-line-empty-p))
  6285. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6286. (run-hooks 'org-insert-heading-hook))
  6287. (defun org-N-empty-lines-before-current (n)
  6288. "Make the number of empty lines before current exactly N.
  6289. So this will delete or add empty lines."
  6290. (let ((column (current-column)))
  6291. (beginning-of-line)
  6292. (unless (bobp)
  6293. (let ((start (save-excursion
  6294. (skip-chars-backward " \r\t\n")
  6295. (line-end-position))))
  6296. (delete-region start (line-end-position 0))))
  6297. (insert (make-string n ?\n))
  6298. (move-to-column column)))
  6299. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6300. "Return the heading of the current entry, without the stars.
  6301. When NO-TAGS is non-nil, don't include tags.
  6302. When NO-TODO is non-nil, don't include TODO keywords.
  6303. When NO-PRIORITY is non-nil, don't include priority cookie.
  6304. When NO-COMMENT is non-nil, don't include COMMENT string.
  6305. Return nil before first heading."
  6306. (unless (org-before-first-heading-p)
  6307. (save-excursion
  6308. (org-back-to-heading t)
  6309. (let ((case-fold-search nil))
  6310. (looking-at org-complex-heading-regexp)
  6311. (let ((todo (and (not no-todo) (match-string 2)))
  6312. (priority (and (not no-priority) (match-string 3)))
  6313. (headline (pcase (match-string 4)
  6314. (`nil "")
  6315. ((and (guard no-comment) h)
  6316. (replace-regexp-in-string
  6317. (eval-when-compile
  6318. (format "\\`%s[ \t]+" org-comment-string))
  6319. "" h))
  6320. (h h)))
  6321. (tags (and (not no-tags) (match-string 5))))
  6322. (mapconcat #'identity
  6323. (delq nil (list todo priority headline tags))
  6324. " "))))))
  6325. (defun org-heading-components ()
  6326. "Return the components of the current heading.
  6327. This is a list with the following elements:
  6328. - the level as an integer
  6329. - the reduced level, different if `org-odd-levels-only' is set.
  6330. - the TODO keyword, or nil
  6331. - the priority character, like ?A, or nil if no priority is given
  6332. - the headline text itself, or the tags string if no headline text
  6333. - the tags string, or nil."
  6334. (save-excursion
  6335. (org-back-to-heading t)
  6336. (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
  6337. (list (length (match-string 1))
  6338. (org-reduced-level (length (match-string 1)))
  6339. (match-string-no-properties 2)
  6340. (and (match-end 3) (aref (match-string 3) 2))
  6341. (match-string-no-properties 4)
  6342. (match-string-no-properties 5)))))
  6343. (defun org-get-entry ()
  6344. "Get the entry text, after heading, entire subtree."
  6345. (save-excursion
  6346. (org-back-to-heading t)
  6347. (buffer-substring (line-beginning-position 2) (org-end-of-subtree t))))
  6348. (defun org-edit-headline (&optional heading)
  6349. "Edit the current headline.
  6350. Set it to HEADING when provided."
  6351. (interactive)
  6352. (org-with-wide-buffer
  6353. (org-back-to-heading t)
  6354. (let ((case-fold-search nil))
  6355. (when (looking-at org-complex-heading-regexp)
  6356. (let* ((old (match-string-no-properties 4))
  6357. (new (save-match-data
  6358. (org-trim (or heading (read-string "Edit: " old))))))
  6359. (unless (equal old new)
  6360. (if old (replace-match new t t nil 4)
  6361. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  6362. (insert " " new))
  6363. (org-align-tags)
  6364. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  6365. (defun org-insert-heading-after-current ()
  6366. "Insert a new heading with same level as current, after current subtree."
  6367. (interactive)
  6368. (org-back-to-heading)
  6369. (org-insert-heading)
  6370. (org-move-subtree-down)
  6371. (end-of-line 1))
  6372. (defun org-insert-heading-respect-content (&optional invisible-ok)
  6373. "Insert heading with `org-insert-heading-respect-content' set to t."
  6374. (interactive)
  6375. (org-insert-heading '(4) invisible-ok))
  6376. (defun org-insert-todo-heading-respect-content (&optional force-state)
  6377. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  6378. (interactive)
  6379. (org-insert-todo-heading force-state '(4)))
  6380. (defun org-insert-todo-heading (arg &optional force-heading)
  6381. "Insert a new heading with the same level and TODO state as current heading.
  6382. If the heading has no TODO state, or if the state is DONE, use
  6383. the first state (TODO by default). Also with one prefix arg,
  6384. force first state. With two prefix args, force inserting at the
  6385. end of the parent subtree.
  6386. When called at a plain list item, insert a new item with an
  6387. unchecked check box."
  6388. (interactive "P")
  6389. (when (or force-heading (not (org-insert-item 'checkbox)))
  6390. (org-insert-heading (or (and (equal arg '(16)) '(16))
  6391. force-heading))
  6392. (save-excursion
  6393. (org-forward-heading-same-level -1)
  6394. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  6395. (let* ((new-mark-x
  6396. (if (or (equal arg '(4))
  6397. (not (match-beginning 2))
  6398. (member (match-string 2) org-done-keywords))
  6399. (car org-todo-keywords-1)
  6400. (match-string 2)))
  6401. (new-mark
  6402. (or
  6403. (run-hook-with-args-until-success
  6404. 'org-todo-get-default-hook new-mark-x nil)
  6405. new-mark-x)))
  6406. (beginning-of-line 1)
  6407. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  6408. (if org-treat-insert-todo-heading-as-state-change
  6409. (org-todo new-mark)
  6410. (insert new-mark " "))))
  6411. (when org-provide-todo-statistics
  6412. (org-update-parent-todo-statistics))))
  6413. (defun org-insert-subheading (arg)
  6414. "Insert a new subheading and demote it.
  6415. Works for outline headings and for plain lists alike."
  6416. (interactive "P")
  6417. (org-insert-heading arg)
  6418. (cond
  6419. ((org-at-heading-p) (org-do-demote))
  6420. ((org-at-item-p) (org-indent-item))))
  6421. (defun org-insert-todo-subheading (arg)
  6422. "Insert a new subheading with TODO keyword or checkbox and demote it.
  6423. Works for outline headings and for plain lists alike."
  6424. (interactive "P")
  6425. (org-insert-todo-heading arg)
  6426. (cond
  6427. ((org-at-heading-p) (org-do-demote))
  6428. ((org-at-item-p) (org-indent-item))))
  6429. ;;; Promotion and Demotion
  6430. (defvar org-after-demote-entry-hook nil
  6431. "Hook run after an entry has been demoted.
  6432. The cursor will be at the beginning of the entry.
  6433. When a subtree is being demoted, the hook will be called for each node.")
  6434. (defvar org-after-promote-entry-hook nil
  6435. "Hook run after an entry has been promoted.
  6436. The cursor will be at the beginning of the entry.
  6437. When a subtree is being promoted, the hook will be called for each node.")
  6438. (defun org-promote-subtree ()
  6439. "Promote the entire subtree.
  6440. See also `org-promote'."
  6441. (interactive)
  6442. (save-excursion
  6443. (org-with-limited-levels (org-map-tree 'org-promote)))
  6444. (org-fix-position-after-promote))
  6445. (defun org-demote-subtree ()
  6446. "Demote the entire subtree.
  6447. See `org-demote' and `org-promote'."
  6448. (interactive)
  6449. (save-excursion
  6450. (org-with-limited-levels (org-map-tree 'org-demote)))
  6451. (org-fix-position-after-promote))
  6452. (defun org-do-promote ()
  6453. "Promote the current heading higher up the tree.
  6454. If the region is active in `transient-mark-mode', promote all
  6455. headings in the region."
  6456. (interactive)
  6457. (save-excursion
  6458. (if (org-region-active-p)
  6459. (org-map-region 'org-promote (region-beginning) (region-end))
  6460. (org-promote)))
  6461. (org-fix-position-after-promote))
  6462. (defun org-do-demote ()
  6463. "Demote the current heading lower down the tree.
  6464. If the region is active in `transient-mark-mode', demote all
  6465. headings in the region."
  6466. (interactive)
  6467. (save-excursion
  6468. (if (org-region-active-p)
  6469. (org-map-region 'org-demote (region-beginning) (region-end))
  6470. (org-demote)))
  6471. (org-fix-position-after-promote))
  6472. (defun org-fix-position-after-promote ()
  6473. "Fix cursor position and indentation after demoting/promoting."
  6474. (let ((pos (point)))
  6475. (when (save-excursion
  6476. (beginning-of-line)
  6477. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  6478. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  6479. (cond ((eobp) (insert " "))
  6480. ((eolp) (insert " "))
  6481. ((equal (char-after) ?\s) (forward-char 1))))))
  6482. (defun org-current-level ()
  6483. "Return the level of the current entry, or nil if before the first headline.
  6484. The level is the number of stars at the beginning of the
  6485. headline. Use `org-reduced-level' to remove the effect of
  6486. `org-odd-levels'. Unlike to `org-outline-level', this function
  6487. ignores inlinetasks."
  6488. (let ((level (org-with-limited-levels (org-outline-level))))
  6489. (and (> level 0) level)))
  6490. (defun org-get-previous-line-level ()
  6491. "Return the outline depth of the last headline before the current line.
  6492. Returns 0 for the first headline in the buffer, and nil if before the
  6493. first headline."
  6494. (and (org-current-level)
  6495. (or (and (/= (line-beginning-position) (point-min))
  6496. (save-excursion (beginning-of-line 0) (org-current-level)))
  6497. 0)))
  6498. (defun org-reduced-level (l)
  6499. "Compute the effective level of a heading.
  6500. This takes into account the setting of `org-odd-levels-only'."
  6501. (cond
  6502. ((zerop l) 0)
  6503. (org-odd-levels-only (1+ (floor (/ l 2))))
  6504. (t l)))
  6505. (defun org-level-increment ()
  6506. "Return the number of stars that will be added or removed at a
  6507. time to headlines when structure editing, based on the value of
  6508. `org-odd-levels-only'."
  6509. (if org-odd-levels-only 2 1))
  6510. (defun org-get-valid-level (level &optional change)
  6511. "Rectify a level change under the influence of `org-odd-levels-only'.
  6512. LEVEL is a current level, CHANGE is by how much the level should
  6513. be modified. Even if CHANGE is nil, LEVEL may be returned
  6514. modified because even level numbers will become the next higher
  6515. odd number. Returns values greater than 0."
  6516. (if org-odd-levels-only
  6517. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  6518. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  6519. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  6520. (max 1 (+ level (or change 0)))))
  6521. (defun org-promote ()
  6522. "Promote the current heading higher up the tree."
  6523. (org-with-wide-buffer
  6524. (org-back-to-heading t)
  6525. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6526. after-change-functions))
  6527. (level (save-match-data (funcall outline-level)))
  6528. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  6529. (diff (abs (- level (length up-head) -1))))
  6530. (cond
  6531. ((and (= level 1) org-allow-promoting-top-level-subtree)
  6532. (replace-match "# " nil t))
  6533. ((= level 1)
  6534. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  6535. (t (replace-match up-head nil t)))
  6536. (unless (= level 1)
  6537. (when org-auto-align-tags (org-align-tags))
  6538. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  6539. (run-hooks 'org-after-promote-entry-hook))))
  6540. (defun org-demote ()
  6541. "Demote the current heading lower down the tree."
  6542. (org-with-wide-buffer
  6543. (org-back-to-heading t)
  6544. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6545. after-change-functions))
  6546. (level (save-match-data (funcall outline-level)))
  6547. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  6548. (diff (abs (- level (length down-head) -1))))
  6549. (replace-match down-head nil t)
  6550. (when org-auto-align-tags (org-align-tags))
  6551. (when org-adapt-indentation (org-fixup-indentation diff))
  6552. (run-hooks 'org-after-demote-entry-hook))))
  6553. (defun org-cycle-level ()
  6554. "Cycle the level of an empty headline through possible states.
  6555. This goes first to child, then to parent, level, then up the hierarchy.
  6556. After top level, it switches back to sibling level."
  6557. (interactive)
  6558. (let ((org-adapt-indentation nil))
  6559. (when (org-point-at-end-of-empty-headline)
  6560. (setq this-command 'org-cycle-level) ; Only needed for caching
  6561. (let ((cur-level (org-current-level))
  6562. (prev-level (org-get-previous-line-level)))
  6563. (cond
  6564. ;; If first headline in file, promote to top-level.
  6565. ((= prev-level 0)
  6566. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6567. do (org-do-promote)))
  6568. ;; If same level as prev, demote one.
  6569. ((= prev-level cur-level)
  6570. (org-do-demote))
  6571. ;; If parent is top-level, promote to top level if not already.
  6572. ((= prev-level 1)
  6573. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6574. do (org-do-promote)))
  6575. ;; If top-level, return to prev-level.
  6576. ((= cur-level 1)
  6577. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  6578. do (org-do-demote)))
  6579. ;; If less than prev-level, promote one.
  6580. ((< cur-level prev-level)
  6581. (org-do-promote))
  6582. ;; If deeper than prev-level, promote until higher than
  6583. ;; prev-level.
  6584. ((> cur-level prev-level)
  6585. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  6586. do (org-do-promote))))
  6587. t))))
  6588. (defun org-map-tree (fun)
  6589. "Call FUN for every heading underneath the current one."
  6590. (org-back-to-heading t)
  6591. (let ((level (funcall outline-level)))
  6592. (save-excursion
  6593. (funcall fun)
  6594. (while (and (progn
  6595. (outline-next-heading)
  6596. (> (funcall outline-level) level))
  6597. (not (eobp)))
  6598. (funcall fun)))))
  6599. (defun org-map-region (fun beg end)
  6600. "Call FUN for every heading between BEG and END."
  6601. (let ((org-ignore-region t))
  6602. (save-excursion
  6603. (setq end (copy-marker end))
  6604. (goto-char beg)
  6605. (when (and (re-search-forward org-outline-regexp-bol nil t)
  6606. (< (point) end))
  6607. (funcall fun))
  6608. (while (and (progn
  6609. (outline-next-heading)
  6610. (< (point) end))
  6611. (not (eobp)))
  6612. (funcall fun)))))
  6613. (defun org-fixup-indentation (diff)
  6614. "Change the indentation in the current entry by DIFF.
  6615. DIFF is an integer. Indentation is done according to the
  6616. following rules:
  6617. - Planning information and property drawers are always indented
  6618. according to the new level of the headline;
  6619. - Footnote definitions and their contents are ignored;
  6620. - Inlinetasks' boundaries are not shifted;
  6621. - Empty lines are ignored;
  6622. - Other lines' indentation are shifted by DIFF columns, unless
  6623. it would introduce a structural change in the document, in
  6624. which case no shifting is done at all.
  6625. Assume point is at a heading or an inlinetask beginning."
  6626. (org-with-wide-buffer
  6627. (narrow-to-region (line-beginning-position)
  6628. (save-excursion
  6629. (if (org-with-limited-levels (org-at-heading-p))
  6630. (org-with-limited-levels (outline-next-heading))
  6631. (org-inlinetask-goto-end))
  6632. (point)))
  6633. (forward-line)
  6634. ;; Indent properly planning info and property drawer.
  6635. (when (looking-at-p org-planning-line-re)
  6636. (org-indent-line)
  6637. (forward-line))
  6638. (when (looking-at org-property-drawer-re)
  6639. (goto-char (match-end 0))
  6640. (forward-line)
  6641. (org-indent-region (match-beginning 0) (match-end 0)))
  6642. (when (looking-at org-logbook-drawer-re)
  6643. (let ((end-marker (move-marker (make-marker) (match-end 0)))
  6644. (col (+ (current-indentation) diff)))
  6645. (when (wholenump col)
  6646. (while (< (point) end-marker)
  6647. (if (natnump diff)
  6648. (insert (make-string diff 32))
  6649. (delete-char (abs diff)))
  6650. (forward-line)))))
  6651. (catch 'no-shift
  6652. (when (or (zerop diff) (not (eq org-adapt-indentation t)))
  6653. (throw 'no-shift nil))
  6654. ;; If DIFF is negative, first check if a shift is possible at all
  6655. ;; (e.g., it doesn't break structure). This can only happen if
  6656. ;; some contents are not properly indented.
  6657. (let ((case-fold-search t))
  6658. (when (< diff 0)
  6659. (let ((diff (- diff))
  6660. (forbidden-re (concat org-outline-regexp
  6661. "\\|"
  6662. (substring org-footnote-definition-re 1))))
  6663. (save-excursion
  6664. (while (not (eobp))
  6665. (cond
  6666. ((looking-at-p "[ \t]*$") (forward-line))
  6667. ((and (looking-at-p org-footnote-definition-re)
  6668. (let ((e (org-element-at-point)))
  6669. (and (eq (org-element-type e) 'footnote-definition)
  6670. (goto-char (org-element-property :end e))))))
  6671. ((looking-at-p org-outline-regexp) (forward-line))
  6672. ;; Give up if shifting would move before column 0 or
  6673. ;; if it would introduce a headline or a footnote
  6674. ;; definition.
  6675. (t
  6676. (skip-chars-forward " \t")
  6677. (let ((ind (current-column)))
  6678. (when (or (< ind diff)
  6679. (and (= ind diff) (looking-at-p forbidden-re)))
  6680. (throw 'no-shift nil)))
  6681. ;; Ignore contents of example blocks and source
  6682. ;; blocks if their indentation is meant to be
  6683. ;; preserved. Jump to block's closing line.
  6684. (beginning-of-line)
  6685. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6686. (let ((e (org-element-at-point)))
  6687. (and (memq (org-element-type e)
  6688. '(example-block src-block))
  6689. (or org-src-preserve-indentation
  6690. (org-element-property :preserve-indent e))
  6691. (goto-char (org-element-property :end e))
  6692. (progn (skip-chars-backward " \r\t\n")
  6693. (beginning-of-line)
  6694. t))))
  6695. (forward-line))))))))
  6696. ;; Shift lines but footnote definitions, inlinetasks boundaries
  6697. ;; by DIFF. Also skip contents of source or example blocks
  6698. ;; when indentation is meant to be preserved.
  6699. (while (not (eobp))
  6700. (cond
  6701. ((and (looking-at-p org-footnote-definition-re)
  6702. (let ((e (org-element-at-point)))
  6703. (and (eq (org-element-type e) 'footnote-definition)
  6704. (goto-char (org-element-property :end e))))))
  6705. ((looking-at-p org-outline-regexp) (forward-line))
  6706. ((looking-at-p "[ \t]*$") (forward-line))
  6707. (t
  6708. (indent-line-to (+ (current-indentation) diff))
  6709. (beginning-of-line)
  6710. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6711. (let ((e (org-element-at-point)))
  6712. (and (memq (org-element-type e)
  6713. '(example-block src-block))
  6714. (or org-src-preserve-indentation
  6715. (org-element-property :preserve-indent e))
  6716. (goto-char (org-element-property :end e))
  6717. (progn (skip-chars-backward " \r\t\n")
  6718. (beginning-of-line)
  6719. t))))
  6720. (forward-line)))))))))
  6721. (defun org-convert-to-odd-levels ()
  6722. "Convert an Org file with all levels allowed to one with odd levels.
  6723. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  6724. level 5 etc."
  6725. (interactive)
  6726. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  6727. (let ((outline-level 'org-outline-level)
  6728. (org-odd-levels-only nil) n)
  6729. (save-excursion
  6730. (goto-char (point-min))
  6731. (while (re-search-forward "^\\*\\*+ " nil t)
  6732. (setq n (- (length (match-string 0)) 2))
  6733. (while (>= (setq n (1- n)) 0)
  6734. (org-demote))
  6735. (end-of-line 1))))))
  6736. (defun org-convert-to-oddeven-levels ()
  6737. "Convert an Org file with only odd levels to one with odd/even levels.
  6738. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  6739. file contains a section with an even level, conversion would
  6740. destroy the structure of the file. An error is signaled in this
  6741. case."
  6742. (interactive)
  6743. (goto-char (point-min))
  6744. ;; First check if there are no even levels
  6745. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  6746. (org-show-set-visibility 'canonical)
  6747. (error "Not all levels are odd in this file. Conversion not possible"))
  6748. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  6749. (let ((outline-regexp org-outline-regexp)
  6750. (outline-level 'org-outline-level)
  6751. (org-odd-levels-only nil) n)
  6752. (save-excursion
  6753. (goto-char (point-min))
  6754. (while (re-search-forward "^\\*\\*+ " nil t)
  6755. (setq n (/ (1- (length (match-string 0))) 2))
  6756. (while (>= (setq n (1- n)) 0)
  6757. (org-promote))
  6758. (end-of-line 1))))))
  6759. (defun org-tr-level (n)
  6760. "Make N odd if required."
  6761. (if org-odd-levels-only (1+ (/ n 2)) n))
  6762. ;;; Vertical tree motion, cutting and pasting of subtrees
  6763. (defun org-move-subtree-up (&optional arg)
  6764. "Move the current subtree up past ARG headlines of the same level."
  6765. (interactive "p")
  6766. (org-move-subtree-down (- (prefix-numeric-value arg))))
  6767. (defun org-move-subtree-down (&optional arg)
  6768. "Move the current subtree down past ARG headlines of the same level."
  6769. (interactive "p")
  6770. (setq arg (prefix-numeric-value arg))
  6771. (org-preserve-local-variables
  6772. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  6773. 'org-get-previous-sibling))
  6774. (ins-point (make-marker))
  6775. (cnt (abs arg))
  6776. (col (current-column))
  6777. beg end txt folded)
  6778. ;; Select the tree
  6779. (org-back-to-heading)
  6780. (setq beg (point))
  6781. (save-match-data
  6782. (save-excursion (outline-end-of-heading)
  6783. (setq folded (org-invisible-p)))
  6784. (progn (org-end-of-subtree nil t)
  6785. (unless (eobp) (backward-char))))
  6786. (outline-next-heading)
  6787. (setq end (point))
  6788. (goto-char beg)
  6789. ;; Find insertion point, with error handling
  6790. (while (> cnt 0)
  6791. (unless (and (funcall movfunc) (looking-at org-outline-regexp))
  6792. (goto-char beg)
  6793. (user-error "Cannot move past superior level or buffer limit"))
  6794. (setq cnt (1- cnt)))
  6795. (when (> arg 0)
  6796. ;; Moving forward - still need to move over subtree
  6797. (org-end-of-subtree t t)
  6798. (save-excursion
  6799. (org-back-over-empty-lines)
  6800. (or (bolp) (newline))))
  6801. (move-marker ins-point (point))
  6802. (setq txt (buffer-substring beg end))
  6803. (org-save-markers-in-region beg end)
  6804. (delete-region beg end)
  6805. (org-remove-empty-overlays-at beg)
  6806. (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
  6807. (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
  6808. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  6809. (let ((bbb (point)))
  6810. (insert-before-markers txt)
  6811. (org-reinstall-markers-in-region bbb)
  6812. (move-marker ins-point bbb))
  6813. (or (bolp) (insert "\n"))
  6814. (goto-char ins-point)
  6815. (org-skip-whitespace)
  6816. (move-marker ins-point nil)
  6817. (if folded
  6818. (org-flag-subtree t)
  6819. (org-show-entry)
  6820. (org-show-children))
  6821. (org-clean-visibility-after-subtree-move)
  6822. ;; move back to the initial column we were at
  6823. (move-to-column col))))
  6824. (defvar org-subtree-clip ""
  6825. "Clipboard for cut and paste of subtrees.
  6826. This is actually only a copy of the kill, because we use the normal kill
  6827. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  6828. (defvar org-subtree-clip-folded nil
  6829. "Was the last copied subtree folded?
  6830. This is used to fold the tree back after pasting.")
  6831. (defun org-cut-subtree (&optional n)
  6832. "Cut the current subtree into the clipboard.
  6833. With prefix arg N, cut this many sequential subtrees.
  6834. This is a short-hand for marking the subtree and then cutting it."
  6835. (interactive "p")
  6836. (org-copy-subtree n 'cut))
  6837. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  6838. "Copy the current subtree into the clipboard.
  6839. With prefix arg N, copy this many sequential subtrees.
  6840. This is a short-hand for marking the subtree and then copying it.
  6841. If CUT is non-nil, actually cut the subtree.
  6842. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  6843. of some markers in the region, even if CUT is non-nil. This is
  6844. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  6845. (interactive "p")
  6846. (org-preserve-local-variables
  6847. (let (beg end folded (beg0 (point)))
  6848. (if (called-interactively-p 'any)
  6849. (org-back-to-heading nil) ; take what looks like a subtree
  6850. (org-back-to-heading t)) ; take what is really there
  6851. (setq beg (point))
  6852. (skip-chars-forward " \t\r\n")
  6853. (save-match-data
  6854. (if nosubtrees
  6855. (outline-next-heading)
  6856. (save-excursion (outline-end-of-heading)
  6857. (setq folded (org-invisible-p)))
  6858. (ignore-errors (org-forward-heading-same-level (1- n) t))
  6859. (org-end-of-subtree t t)))
  6860. ;; Include the end of an inlinetask
  6861. (when (and (featurep 'org-inlinetask)
  6862. (looking-at-p (concat (org-inlinetask-outline-regexp)
  6863. "END[ \t]*$")))
  6864. (end-of-line))
  6865. (setq end (point))
  6866. (goto-char beg0)
  6867. (when (> end beg)
  6868. (setq org-subtree-clip-folded folded)
  6869. (when (or cut force-store-markers)
  6870. (org-save-markers-in-region beg end))
  6871. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  6872. (setq org-subtree-clip (current-kill 0))
  6873. (message "%s: Subtree(s) with %d characters"
  6874. (if cut "Cut" "Copied")
  6875. (length org-subtree-clip))))))
  6876. (defun org-paste-subtree (&optional level tree for-yank remove)
  6877. "Paste the clipboard as a subtree, with modification of headline level.
  6878. The entire subtree is promoted or demoted in order to match a new headline
  6879. level.
  6880. If the cursor is at the beginning of a headline, the same level as
  6881. that headline is used to paste the tree.
  6882. If not, the new level is derived from the *visible* headings
  6883. before and after the insertion point, and taken to be the inferior headline
  6884. level of the two. So if the previous visible heading is level 3 and the
  6885. next is level 4 (or vice versa), level 4 will be used for insertion.
  6886. This makes sure that the subtree remains an independent subtree and does
  6887. not swallow low level entries.
  6888. You can also force a different level, either by using a numeric prefix
  6889. argument, or by inserting the heading marker by hand. For example, if the
  6890. cursor is after \"*****\", then the tree will be shifted to level 5.
  6891. If optional TREE is given, use this text instead of the kill ring.
  6892. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  6893. move back over whitespace before inserting, and move point to the end of
  6894. the inserted text when done.
  6895. When REMOVE is non-nil, remove the subtree from the clipboard."
  6896. (interactive "P")
  6897. (setq tree (or tree (and kill-ring (current-kill 0))))
  6898. (unless (org-kill-is-subtree-p tree)
  6899. (user-error
  6900. (substitute-command-keys
  6901. "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
  6902. (org-with-limited-levels
  6903. (let* ((visp (not (org-invisible-p)))
  6904. (txt tree)
  6905. (old-level (if (string-match org-outline-regexp-bol txt)
  6906. (- (match-end 0) (match-beginning 0) 1)
  6907. -1))
  6908. (force-level
  6909. (cond
  6910. (level (prefix-numeric-value level))
  6911. ;; When point is after the stars in an otherwise empty
  6912. ;; headline, use the number of stars as the forced level.
  6913. ((and (org-match-line "^\\*+[ \t]*$")
  6914. (not (eq ?* (char-after))))
  6915. (org-outline-level))
  6916. ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
  6917. (previous-level
  6918. (save-excursion
  6919. (org-previous-visible-heading 1)
  6920. (if (org-at-heading-p) (org-outline-level) 1)))
  6921. (next-level
  6922. (save-excursion
  6923. (if (org-at-heading-p) (org-outline-level)
  6924. (org-next-visible-heading 1)
  6925. (if (org-at-heading-p) (org-outline-level) 1))))
  6926. (new-level (or force-level (max previous-level next-level)))
  6927. (shift (if (or (= old-level -1)
  6928. (= new-level -1)
  6929. (= old-level new-level))
  6930. 0
  6931. (- new-level old-level)))
  6932. (delta (if (> shift 0) -1 1))
  6933. (func (if (> shift 0) #'org-demote #'org-promote))
  6934. (org-odd-levels-only nil)
  6935. beg end newend)
  6936. ;; Remove the forced level indicator.
  6937. (when (and force-level (not level))
  6938. (delete-region (line-beginning-position) (point)))
  6939. ;; Paste before the next visible heading or at end of buffer,
  6940. ;; unless point is at the beginning of a headline.
  6941. (unless (and (bolp) (org-at-heading-p))
  6942. (org-next-visible-heading 1)
  6943. (unless (bolp) (insert "\n")))
  6944. (setq beg (point))
  6945. (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  6946. (insert-before-markers txt)
  6947. (unless (string-suffix-p "\n" txt) (insert "\n"))
  6948. (setq newend (point))
  6949. (org-reinstall-markers-in-region beg)
  6950. (setq end (point))
  6951. (goto-char beg)
  6952. (skip-chars-forward " \t\n\r")
  6953. (setq beg (point))
  6954. (when (and (org-invisible-p) visp)
  6955. (save-excursion (outline-show-heading)))
  6956. ;; Shift if necessary.
  6957. (unless (= shift 0)
  6958. (save-restriction
  6959. (narrow-to-region beg end)
  6960. (while (not (= shift 0))
  6961. (org-map-region func (point-min) (point-max))
  6962. (setq shift (+ delta shift)))
  6963. (goto-char (point-min))
  6964. (setq newend (point-max))))
  6965. (when (or for-yank (called-interactively-p 'interactive))
  6966. (message "Clipboard pasted as level %d subtree" new-level))
  6967. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  6968. kill-ring
  6969. (equal org-subtree-clip (current-kill 0))
  6970. org-subtree-clip-folded)
  6971. ;; The tree was folded before it was killed/copied
  6972. (org-flag-subtree t))
  6973. (when for-yank (goto-char newend))
  6974. (when remove (pop kill-ring)))))
  6975. (defun org-kill-is-subtree-p (&optional txt)
  6976. "Check if the current kill is an outline subtree, or a set of trees.
  6977. Returns nil if kill does not start with a headline, or if the first
  6978. headline level is not the largest headline level in the tree.
  6979. So this will actually accept several entries of equal levels as well,
  6980. which is OK for `org-paste-subtree'.
  6981. If optional TXT is given, check this string instead of the current kill."
  6982. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  6983. (re (org-get-limited-outline-regexp))
  6984. (^re (concat "^" re))
  6985. (start-level (and kill
  6986. (string-match
  6987. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  6988. kill)
  6989. (- (match-end 2) (match-beginning 2) 1)))
  6990. (start (1+ (or (match-beginning 2) -1))))
  6991. (if (not start-level)
  6992. (progn
  6993. nil) ;; does not even start with a heading
  6994. (catch 'exit
  6995. (while (setq start (string-match ^re kill (1+ start)))
  6996. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  6997. (throw 'exit nil)))
  6998. t))))
  6999. (defvar org-markers-to-move nil
  7000. "Markers that should be moved with a cut-and-paste operation.
  7001. Those markers are stored together with their positions relative to
  7002. the start of the region.")
  7003. (defun org-save-markers-in-region (beg end)
  7004. "Check markers in region.
  7005. If these markers are between BEG and END, record their position relative
  7006. to BEG, so that after moving the block of text, we can put the markers back
  7007. into place.
  7008. This function gets called just before an entry or tree gets cut from the
  7009. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  7010. called immediately, to move the markers with the entries."
  7011. (setq org-markers-to-move nil)
  7012. (when (featurep 'org-clock)
  7013. (org-clock-save-markers-for-cut-and-paste beg end))
  7014. (when (featurep 'org-agenda)
  7015. (org-agenda-save-markers-for-cut-and-paste beg end)))
  7016. (defun org-check-and-save-marker (marker beg end)
  7017. "Check if MARKER is between BEG and END.
  7018. If yes, remember the marker and the distance to BEG."
  7019. (when (and (marker-buffer marker)
  7020. (or (equal (marker-buffer marker) (current-buffer))
  7021. (equal (marker-buffer marker) (buffer-base-buffer (current-buffer))))
  7022. (>= marker beg) (< marker end))
  7023. (push (cons marker (- marker beg)) org-markers-to-move)))
  7024. (defun org-reinstall-markers-in-region (beg)
  7025. "Move all remembered markers to their position relative to BEG."
  7026. (dolist (x org-markers-to-move)
  7027. (move-marker (car x) (+ beg (cdr x))))
  7028. (setq org-markers-to-move nil))
  7029. (defun org-narrow-to-subtree ()
  7030. "Narrow buffer to the current subtree."
  7031. (interactive)
  7032. (save-excursion
  7033. (save-match-data
  7034. (org-with-limited-levels
  7035. (narrow-to-region
  7036. (progn (org-back-to-heading t) (point))
  7037. (progn (org-end-of-subtree t t)
  7038. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  7039. (point)))))))
  7040. (defun org-toggle-narrow-to-subtree ()
  7041. "Narrow to the subtree at point or widen a narrowed buffer."
  7042. (interactive)
  7043. (if (buffer-narrowed-p)
  7044. (progn (widen) (message "Buffer widen"))
  7045. (org-narrow-to-subtree)
  7046. (message "Buffer narrowed to current subtree")))
  7047. (defun org-narrow-to-block ()
  7048. "Narrow buffer to the current block."
  7049. (interactive)
  7050. (let* ((case-fold-search t)
  7051. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7052. "^[ \t]*#\\+end_.*")))
  7053. (if blockp
  7054. (narrow-to-region (car blockp) (cdr blockp))
  7055. (user-error "Not in a block"))))
  7056. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7057. "Clone the task (subtree) at point N times.
  7058. The clones will be inserted as siblings.
  7059. In interactive use, the user will be prompted for the number of
  7060. clones to be produced. If the entry has a timestamp, the user
  7061. will also be prompted for a time shift, which may be a repeater
  7062. as used in time stamps, for example `+3d'. To disable this,
  7063. you can call the function with a universal prefix argument.
  7064. When a valid repeater is given and the entry contains any time
  7065. stamps, the clones will become a sequence in time, with time
  7066. stamps in the subtree shifted for each clone produced. If SHIFT
  7067. is nil or the empty string, time stamps will be left alone. The
  7068. ID property of the original subtree is removed.
  7069. In each clone, all the CLOCK entries will be removed. This
  7070. prevents Org from considering that the clocked times overlap.
  7071. If the original subtree did contain time stamps with a repeater,
  7072. the following will happen:
  7073. - the repeater will be removed in each clone
  7074. - an additional clone will be produced, with the current, unshifted
  7075. date(s) in the entry.
  7076. - the original entry will be placed *after* all the clones, with
  7077. repeater intact.
  7078. - the start days in the repeater in the original entry will be shifted
  7079. to past the last clone.
  7080. In this way you can spell out a number of instances of a repeating task,
  7081. and still retain the repeater to cover future instances of the task.
  7082. As described above, N+1 clones are produced when the original
  7083. subtree has a repeater. Setting N to 0, then, can be used to
  7084. remove the repeater from a subtree and create a shifted clone
  7085. with the original repeater."
  7086. (interactive "nNumber of clones to produce: ")
  7087. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  7088. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  7089. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  7090. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  7091. (shift
  7092. (or shift
  7093. (if (and (not (equal current-prefix-arg '(4)))
  7094. (save-excursion
  7095. (goto-char beg)
  7096. (re-search-forward org-ts-regexp-both end-of-tree t)))
  7097. (read-from-minibuffer
  7098. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7099. ""))) ;No time shift
  7100. (doshift
  7101. (and (org-string-nw-p shift)
  7102. (or (string-match "\\`[ \t]*\\([+-]?[0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
  7103. shift)
  7104. (user-error "Invalid shift specification %s" shift)))))
  7105. (goto-char end-of-tree)
  7106. (unless (bolp) (insert "\n"))
  7107. (let* ((end (point))
  7108. (template (buffer-substring beg end))
  7109. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  7110. (shift-what (pcase (and doshift (match-string 2 shift))
  7111. (`nil nil)
  7112. ("h" 'hour)
  7113. ("d" 'day)
  7114. ("w" (setq shift-n (* 7 shift-n)) 'day)
  7115. ("m" 'month)
  7116. ("y" 'year)
  7117. (_ (error "Unsupported time unit"))))
  7118. (nmin 1)
  7119. (nmax n)
  7120. (n-no-remove -1)
  7121. (org-id-overriding-file-name (buffer-file-name (buffer-base-buffer)))
  7122. (idprop (org-entry-get beg "ID")))
  7123. (when (and doshift
  7124. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  7125. template))
  7126. (delete-region beg end)
  7127. (setq end beg)
  7128. (setq nmin 0)
  7129. (setq nmax (1+ nmax))
  7130. (setq n-no-remove nmax))
  7131. (goto-char end)
  7132. (cl-loop for n from nmin to nmax do
  7133. (insert
  7134. ;; Prepare clone.
  7135. (with-temp-buffer
  7136. (insert template)
  7137. (org-mode)
  7138. (goto-char (point-min))
  7139. (org-show-subtree)
  7140. (and idprop (if org-clone-delete-id
  7141. (org-entry-delete nil "ID")
  7142. (org-id-get-create t)))
  7143. (unless (= n 0)
  7144. (while (re-search-forward org-clock-line-re nil t)
  7145. (delete-region (line-beginning-position)
  7146. (line-beginning-position 2)))
  7147. (goto-char (point-min))
  7148. (while (re-search-forward org-drawer-regexp nil t)
  7149. (org-remove-empty-drawer-at (point))))
  7150. (goto-char (point-min))
  7151. (when doshift
  7152. (while (re-search-forward org-ts-regexp-both nil t)
  7153. (org-timestamp-change (* n shift-n) shift-what))
  7154. (unless (= n n-no-remove)
  7155. (goto-char (point-min))
  7156. (while (re-search-forward org-ts-regexp nil t)
  7157. (save-excursion
  7158. (goto-char (match-beginning 0))
  7159. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7160. (delete-region (match-beginning 1) (match-end 1)))))))
  7161. (buffer-string)))))
  7162. (goto-char beg)))
  7163. ;;; Outline path
  7164. (defvar org-outline-path-cache nil
  7165. "Alist between buffer positions and outline paths.
  7166. It value is an alist (POSITION . PATH) where POSITION is the
  7167. buffer position at the beginning of an entry and PATH is a list
  7168. of strings describing the outline path for that entry, in reverse
  7169. order.")
  7170. (defun org--get-outline-path-1 (&optional use-cache)
  7171. "Return outline path to current headline.
  7172. Outline path is a list of strings, in reverse order. When
  7173. optional argument USE-CACHE is non-nil, make use of a cache. See
  7174. `org-get-outline-path' for details.
  7175. Assume buffer is widened and point is on a headline."
  7176. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  7177. (let ((p (point))
  7178. (heading (let ((case-fold-search nil))
  7179. (looking-at org-complex-heading-regexp)
  7180. (if (not (match-end 4)) ""
  7181. ;; Remove statistics cookies.
  7182. (org-trim
  7183. (org-link-display-format
  7184. (replace-regexp-in-string
  7185. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  7186. (match-string-no-properties 4))))))))
  7187. (if (org-up-heading-safe)
  7188. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  7189. (when use-cache
  7190. (push (cons p path) org-outline-path-cache))
  7191. path)
  7192. ;; This is a new root node. Since we assume we are moving
  7193. ;; forward, we can drop previous cache so as to limit number
  7194. ;; of associations there.
  7195. (let ((path (list heading)))
  7196. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  7197. path)))))
  7198. (defun org-get-outline-path (&optional with-self use-cache)
  7199. "Return the outline path to the current entry.
  7200. An outline path is a list of ancestors for current headline, as
  7201. a list of strings. Statistics cookies are removed and links are
  7202. replaced with their description, if any, or their path otherwise.
  7203. When optional argument WITH-SELF is non-nil, the path also
  7204. includes the current headline.
  7205. When optional argument USE-CACHE is non-nil, cache outline paths
  7206. between calls to this function so as to avoid backtracking. This
  7207. argument is useful when planning to find more than one outline
  7208. path in the same document. In that case, there are two
  7209. conditions to satisfy:
  7210. - `org-outline-path-cache' is set to nil before starting the
  7211. process;
  7212. - outline paths are computed by increasing buffer positions."
  7213. (org-with-wide-buffer
  7214. (and (or (and with-self (org-back-to-heading t))
  7215. (org-up-heading-safe))
  7216. (reverse (org--get-outline-path-1 use-cache)))))
  7217. (defun org-format-outline-path (path &optional width prefix separator)
  7218. "Format the outline path PATH for display.
  7219. WIDTH is the maximum number of characters that is available.
  7220. PREFIX is a prefix to be included in the returned string,
  7221. such as the file name.
  7222. SEPARATOR is inserted between the different parts of the path,
  7223. the default is \"/\"."
  7224. (setq width (or width 79))
  7225. (setq path (delq nil path))
  7226. (unless (> width 0)
  7227. (user-error "Argument `width' must be positive"))
  7228. (setq separator (or separator "/"))
  7229. (let* ((org-odd-levels-only nil)
  7230. (fpath (concat
  7231. prefix (and prefix path separator)
  7232. (mapconcat
  7233. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  7234. (cl-loop for head in path
  7235. for n from 0
  7236. collect (org-add-props
  7237. head nil 'face
  7238. (nth (% n org-n-level-faces) org-level-faces)))
  7239. separator))))
  7240. (when (> (length fpath) width)
  7241. (if (< width 7)
  7242. ;; It's unlikely that `width' will be this small, but don't
  7243. ;; waste characters by adding ".." if it is.
  7244. (setq fpath (substring fpath 0 width))
  7245. (setf (substring fpath (- width 2)) "..")))
  7246. fpath))
  7247. (defun org-display-outline-path (&optional file current separator just-return-string)
  7248. "Display the current outline path in the echo area.
  7249. If FILE is non-nil, prepend the output with the file name.
  7250. If CURRENT is non-nil, append the current heading to the output.
  7251. SEPARATOR is passed through to `org-format-outline-path'. It separates
  7252. the different parts of the path and defaults to \"/\".
  7253. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  7254. (interactive "P")
  7255. (let* (case-fold-search
  7256. (bfn (buffer-file-name (buffer-base-buffer)))
  7257. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  7258. res)
  7259. (when current (setq path (append path
  7260. (save-excursion
  7261. (org-back-to-heading t)
  7262. (when (looking-at org-complex-heading-regexp)
  7263. (list (match-string 4)))))))
  7264. (setq res
  7265. (org-format-outline-path
  7266. path
  7267. (1- (frame-width))
  7268. (and file bfn (concat (file-name-nondirectory bfn) separator))
  7269. separator))
  7270. (add-face-text-property 0 (length res)
  7271. `(:height ,(face-attribute 'default :height))
  7272. nil res)
  7273. (if just-return-string
  7274. res
  7275. (org-unlogged-message "%s" res))))
  7276. ;;; Outline Sorting
  7277. (defun org-sort (&optional with-case)
  7278. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7279. Optional argument WITH-CASE means sort case-sensitively."
  7280. (interactive "P")
  7281. (org-call-with-arg
  7282. (cond ((org-at-table-p) #'org-table-sort-lines)
  7283. ((org-at-item-p) #'org-sort-list)
  7284. (t #'org-sort-entries))
  7285. with-case))
  7286. (defun org-sort-remove-invisible (s)
  7287. "Remove emphasis markers and any invisible property from string S.
  7288. Assume S may contain only objects."
  7289. ;; org-element-interpret-data clears any text property, including
  7290. ;; invisible part.
  7291. (org-element-interpret-data
  7292. (let ((tree (org-element-parse-secondary-string
  7293. s (org-element-restriction 'paragraph))))
  7294. (org-element-map tree '(bold code italic link strike-through underline verbatim)
  7295. (lambda (o)
  7296. (pcase (org-element-type o)
  7297. ;; Terminal object. Replace it with its value.
  7298. ((or `code `verbatim)
  7299. (let ((new (org-element-property :value o)))
  7300. (org-element-insert-before new o)
  7301. (org-element-put-property
  7302. new :post-blank (org-element-property :post-blank o))))
  7303. ;; Non-terminal objects. Splice contents.
  7304. (type
  7305. (let ((contents
  7306. (or (org-element-contents o)
  7307. (and (eq type 'link)
  7308. (list (org-element-property :raw-link o)))))
  7309. (c nil))
  7310. (while contents
  7311. (setq c (pop contents))
  7312. (org-element-insert-before c o))
  7313. (org-element-put-property
  7314. c :post-blank (org-element-property :post-blank o)))))
  7315. (org-element-extract-element o)))
  7316. ;; Return modified tree.
  7317. tree)))
  7318. (defvar org-after-sorting-entries-or-items-hook nil
  7319. "Hook that is run after a bunch of entries or items have been sorted.
  7320. When children are sorted, the cursor is in the parent line when this
  7321. hook gets called. When a region or a plain list is sorted, the cursor
  7322. will be in the first entry of the sorted region/list.")
  7323. (defun org-sort-entries
  7324. (&optional with-case sorting-type getkey-func compare-func property
  7325. interactive?)
  7326. "Sort entries on a certain level of an outline tree.
  7327. If there is an active region, the entries in the region are sorted.
  7328. Else, if the cursor is before the first entry, sort the top-level items.
  7329. Else, the children of the entry at point are sorted.
  7330. Sorting can be alphabetically, numerically, by date/time as given by
  7331. a time stamp, by a property, by priority order, or by a custom function.
  7332. The command prompts for the sorting type unless it has been given to the
  7333. function through the SORTING-TYPE argument, which needs to be a character,
  7334. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7335. the precise meaning of each character:
  7336. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7337. c By creation time, which is assumed to be the first inactive time stamp
  7338. at the beginning of a line.
  7339. d By deadline date/time.
  7340. k By clocking time.
  7341. n Numerically, by converting the beginning of the entry/item to a number.
  7342. o By order of TODO keywords.
  7343. p By priority according to the cookie.
  7344. r By the value of a property.
  7345. s By scheduled date/time.
  7346. t By date/time, either the first active time stamp in the entry, or, if
  7347. none exist, by the first inactive one.
  7348. Capital letters will reverse the sort order.
  7349. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7350. called with point at the beginning of the record. It must return a
  7351. value that is compatible with COMPARE-FUNC, the function used to
  7352. compare entries.
  7353. Comparing entries ignores case by default. However, with an optional argument
  7354. WITH-CASE, the sorting considers case as well.
  7355. Sorting is done against the visible part of the headlines, it ignores hidden
  7356. links.
  7357. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  7358. A non-nil value for INTERACTIVE? is used to signal that this
  7359. function is being called interactively."
  7360. (interactive (list current-prefix-arg nil nil nil nil t))
  7361. (let ((case-func (if with-case 'identity 'downcase))
  7362. start beg end stars re re2
  7363. txt what tmp)
  7364. ;; Find beginning and end of region to sort
  7365. (cond
  7366. ((org-region-active-p)
  7367. ;; we will sort the region
  7368. (setq end (region-end)
  7369. what "region")
  7370. (goto-char (region-beginning))
  7371. (unless (org-at-heading-p) (outline-next-heading))
  7372. (setq start (point)))
  7373. ((or (org-at-heading-p)
  7374. (ignore-errors (progn (org-back-to-heading) t)))
  7375. ;; we will sort the children of the current headline
  7376. (org-back-to-heading)
  7377. (setq start (point)
  7378. end (progn (org-end-of-subtree t t)
  7379. (or (bolp) (insert "\n"))
  7380. (when (>= (org-back-over-empty-lines) 1)
  7381. (forward-line 1))
  7382. (point))
  7383. what "children")
  7384. (goto-char start)
  7385. (outline-show-subtree)
  7386. (outline-next-heading))
  7387. (t
  7388. ;; we will sort the top-level entries in this file
  7389. (goto-char (point-min))
  7390. (or (org-at-heading-p) (outline-next-heading))
  7391. (setq start (point))
  7392. (goto-char (point-max))
  7393. (beginning-of-line 1)
  7394. (when (looking-at ".*?\\S-")
  7395. ;; File ends in a non-white line
  7396. (end-of-line 1)
  7397. (insert "\n"))
  7398. (setq end (point-max))
  7399. (setq what "top-level")
  7400. (goto-char start)
  7401. (org-show-all '(headings drawers blocks))))
  7402. (setq beg (point))
  7403. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7404. (looking-at "\\(\\*+\\)")
  7405. (setq stars (match-string 1)
  7406. re (concat "^" (regexp-quote stars) " +")
  7407. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7408. txt (buffer-substring beg end))
  7409. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7410. (when (and (not (equal stars "*")) (string-match re2 txt))
  7411. (user-error "Region to sort contains a level above the first entry"))
  7412. (unless sorting-type
  7413. (message
  7414. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7415. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7416. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7417. what)
  7418. (setq sorting-type (read-char-exclusive)))
  7419. (unless getkey-func
  7420. (and (= (downcase sorting-type) ?f)
  7421. (setq getkey-func
  7422. (or (and interactive?
  7423. (org-read-function
  7424. "Function for extracting keys: "))
  7425. (error "Missing key extractor")))))
  7426. (and (= (downcase sorting-type) ?r)
  7427. (not property)
  7428. (setq property
  7429. (completing-read "Property: "
  7430. (mapcar #'list (org-buffer-property-keys t))
  7431. nil t)))
  7432. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  7433. (message "Sorting entries...")
  7434. (save-restriction
  7435. (narrow-to-region start end)
  7436. (let ((restore-clock?
  7437. ;; The clock marker is lost when using `sort-subr'; mark
  7438. ;; the clock with temporary `:org-clock-marker-backup'
  7439. ;; text property.
  7440. (when (and (eq (org-clocking-buffer) (current-buffer))
  7441. (<= start (marker-position org-clock-marker))
  7442. (>= end (marker-position org-clock-marker)))
  7443. (with-silent-modifications
  7444. (put-text-property (1- org-clock-marker) org-clock-marker
  7445. :org-clock-marker-backup t))
  7446. t))
  7447. (dcst (downcase sorting-type))
  7448. (case-fold-search nil)
  7449. (now (current-time)))
  7450. (org-preserve-local-variables
  7451. (sort-subr
  7452. (/= dcst sorting-type)
  7453. ;; This function moves to the beginning character of the
  7454. ;; "record" to be sorted.
  7455. (lambda nil
  7456. (if (re-search-forward re nil t)
  7457. (goto-char (match-beginning 0))
  7458. (goto-char (point-max))))
  7459. ;; This function moves to the last character of the "record" being
  7460. ;; sorted.
  7461. (lambda nil
  7462. (save-match-data
  7463. (condition-case nil
  7464. (outline-forward-same-level 1)
  7465. (error
  7466. (goto-char (point-max))))))
  7467. ;; This function returns the value that gets sorted against.
  7468. (lambda ()
  7469. (cond
  7470. ((= dcst ?n)
  7471. (string-to-number
  7472. (org-sort-remove-invisible (org-get-heading t t t t))))
  7473. ((= dcst ?a)
  7474. (funcall case-func
  7475. (org-sort-remove-invisible (org-get-heading t t t t))))
  7476. ((= dcst ?k)
  7477. (or (get-text-property (point) :org-clock-minutes) 0))
  7478. ((= dcst ?t)
  7479. (let ((end (save-excursion (outline-next-heading) (point))))
  7480. (if (or (re-search-forward org-ts-regexp end t)
  7481. (re-search-forward org-ts-regexp-both end t))
  7482. (org-time-string-to-seconds (match-string 0))
  7483. (float-time now))))
  7484. ((= dcst ?c)
  7485. (let ((end (save-excursion (outline-next-heading) (point))))
  7486. (if (re-search-forward
  7487. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  7488. end t)
  7489. (org-time-string-to-seconds (match-string 0))
  7490. (float-time now))))
  7491. ((= dcst ?s)
  7492. (let ((end (save-excursion (outline-next-heading) (point))))
  7493. (if (re-search-forward org-scheduled-time-regexp end t)
  7494. (org-time-string-to-seconds (match-string 1))
  7495. (float-time now))))
  7496. ((= dcst ?d)
  7497. (let ((end (save-excursion (outline-next-heading) (point))))
  7498. (if (re-search-forward org-deadline-time-regexp end t)
  7499. (org-time-string-to-seconds (match-string 1))
  7500. (float-time now))))
  7501. ((= dcst ?p)
  7502. (if (re-search-forward org-priority-regexp (line-end-position) t)
  7503. (string-to-char (match-string 2))
  7504. org-priority-default))
  7505. ((= dcst ?r)
  7506. (or (org-entry-get nil property) ""))
  7507. ((= dcst ?o)
  7508. (when (looking-at org-complex-heading-regexp)
  7509. (let* ((m (match-string 2))
  7510. (s (if (member m org-done-keywords) '- '+)))
  7511. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  7512. ((= dcst ?f)
  7513. (if getkey-func
  7514. (progn
  7515. (setq tmp (funcall getkey-func))
  7516. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  7517. tmp)
  7518. (error "Invalid key function `%s'" getkey-func)))
  7519. (t (error "Invalid sorting type `%c'" sorting-type))))
  7520. nil
  7521. (cond
  7522. ((= dcst ?a) 'org-string-collate-lessp)
  7523. ((= dcst ?f)
  7524. (or compare-func
  7525. (and interactive?
  7526. (org-read-function
  7527. (concat "Function for comparing keys "
  7528. "(empty for default `sort-subr' predicate): ")
  7529. 'allow-empty))))
  7530. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
  7531. (org-cycle-hide-drawers 'all)
  7532. (when restore-clock?
  7533. (move-marker org-clock-marker
  7534. (1+ (next-single-property-change
  7535. start :org-clock-marker-backup)))
  7536. (remove-text-properties (1- org-clock-marker) org-clock-marker
  7537. '(:org-clock-marker-backup t)))))
  7538. (run-hooks 'org-after-sorting-entries-or-items-hook)
  7539. (message "Sorting entries...done")))
  7540. (defun org-contextualize-keys (alist contexts)
  7541. "Return valid elements in ALIST depending on CONTEXTS.
  7542. `org-agenda-custom-commands' or `org-capture-templates' are the
  7543. values used for ALIST, and `org-agenda-custom-commands-contexts'
  7544. or `org-capture-templates-contexts' are the associated contexts
  7545. definitions."
  7546. (let ((contexts
  7547. ;; normalize contexts
  7548. (mapcar
  7549. (lambda(c) (cond ((listp (cadr c))
  7550. (list (car c) (car c) (nth 1 c)))
  7551. ((string= "" (cadr c))
  7552. (list (car c) (car c) (nth 2 c)))
  7553. (t c)))
  7554. contexts))
  7555. (a alist) r s)
  7556. ;; loop over all commands or templates
  7557. (dolist (c a)
  7558. (let (vrules repl)
  7559. (cond
  7560. ((not (assoc (car c) contexts))
  7561. (push c r))
  7562. ((and (assoc (car c) contexts)
  7563. (setq vrules (org-contextualize-validate-key
  7564. (car c) contexts)))
  7565. (mapc (lambda (vr)
  7566. (unless (equal (car vr) (cadr vr))
  7567. (setq repl vr)))
  7568. vrules)
  7569. (if (not repl) (push c r)
  7570. (push (cadr repl) s)
  7571. (push
  7572. (cons (car c)
  7573. (cdr (or (assoc (cadr repl) alist)
  7574. (error "Undefined key `%s' as contextual replacement for `%s'"
  7575. (cadr repl) (car c)))))
  7576. r))))))
  7577. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  7578. (delq
  7579. nil
  7580. (delete-dups
  7581. (mapcar (lambda (x)
  7582. (let ((tpl (car x)))
  7583. (unless (delq
  7584. nil
  7585. (mapcar (lambda (y)
  7586. (equal y tpl))
  7587. s))
  7588. x)))
  7589. (reverse r))))))
  7590. (defun org-contextualize-validate-key (key contexts)
  7591. "Check CONTEXTS for agenda or capture KEY."
  7592. (let (res)
  7593. (dolist (r contexts)
  7594. (dolist (rr (car (last r)))
  7595. (when
  7596. (and (equal key (car r))
  7597. (if (functionp rr) (funcall rr)
  7598. (or (and (eq (car rr) 'in-file)
  7599. (buffer-file-name)
  7600. (string-match (cdr rr) (buffer-file-name)))
  7601. (and (eq (car rr) 'in-mode)
  7602. (string-match (cdr rr) (symbol-name major-mode)))
  7603. (and (eq (car rr) 'in-buffer)
  7604. (string-match (cdr rr) (buffer-name)))
  7605. (when (and (eq (car rr) 'not-in-file)
  7606. (buffer-file-name))
  7607. (not (string-match (cdr rr) (buffer-file-name))))
  7608. (when (eq (car rr) 'not-in-mode)
  7609. (not (string-match (cdr rr) (symbol-name major-mode))))
  7610. (when (eq (car rr) 'not-in-buffer)
  7611. (not (string-match (cdr rr) (buffer-name)))))))
  7612. (push r res))))
  7613. (delete-dups (delq nil res))))
  7614. ;; Defined to provide a value for defcustom, since there is no
  7615. ;; string-collate-greaterp in Emacs.
  7616. (defun org-string-collate-greaterp (s1 s2)
  7617. "Return non-nil if S1 is greater than S2 in collation order."
  7618. (not (org-string-collate-lessp s1 s2)))
  7619. ;;;###autoload
  7620. (defun org-run-like-in-org-mode (cmd)
  7621. "Run a command, pretending that the current buffer is in Org mode.
  7622. This will temporarily bind local variables that are typically bound in
  7623. Org mode to the values they have in Org mode, and then interactively
  7624. call CMD."
  7625. (org-load-modules-maybe)
  7626. (let (binds)
  7627. (dolist (var (org-get-local-variables))
  7628. (when (or (not (boundp (car var)))
  7629. (eq (symbol-value (car var))
  7630. (default-value (car var))))
  7631. (push (list (car var) `(quote ,(cadr var))) binds)))
  7632. (eval `(let ,binds
  7633. (call-interactively (quote ,cmd))))))
  7634. (defun org-get-category (&optional pos force-refresh)
  7635. "Get the category applying to position POS."
  7636. (save-match-data
  7637. (when force-refresh (org-refresh-category-properties))
  7638. (let ((pos (or pos (point))))
  7639. (or (get-text-property pos 'org-category)
  7640. (progn (org-refresh-category-properties)
  7641. (get-text-property pos 'org-category))))))
  7642. ;;; Refresh properties
  7643. (defun org-refresh-properties (dprop tprop)
  7644. "Refresh buffer text properties.
  7645. DPROP is the drawer property and TPROP is either the
  7646. corresponding text property to set, or an alist with each element
  7647. being a text property (as a symbol) and a function to apply to
  7648. the value of the drawer property."
  7649. (let* ((case-fold-search t)
  7650. (inhibit-read-only t)
  7651. (inherit? (org-property-inherit-p dprop))
  7652. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  7653. (global-or-keyword (and inherit?
  7654. (org--property-global-or-keyword-value dprop nil))))
  7655. (with-silent-modifications
  7656. (org-with-point-at 1
  7657. ;; Set global and keyword based values to the whole buffer.
  7658. (when global-or-keyword
  7659. (put-text-property (point-min) (point-max) tprop global-or-keyword))
  7660. ;; Set values based on property-drawers throughout the document.
  7661. (while (re-search-forward property-re nil t)
  7662. (when (org-at-property-p)
  7663. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  7664. (outline-next-heading))))))
  7665. (defun org-refresh-property (tprop p &optional inherit)
  7666. "Refresh the buffer text property TPROP from the drawer property P.
  7667. The refresh happens only for the current entry, or the whole
  7668. sub-tree if optional argument INHERIT is non-nil.
  7669. If point is before first headline, the function applies to the
  7670. part before the first headline. In that particular case, when
  7671. optional argument INHERIT is non-nil, it refreshes properties for
  7672. the whole buffer."
  7673. (save-excursion
  7674. (org-back-to-heading-or-point-min t)
  7675. (let ((start (point))
  7676. (end (save-excursion
  7677. (cond ((and inherit (org-before-first-heading-p))
  7678. (point-max))
  7679. (inherit
  7680. (org-end-of-subtree t t))
  7681. ((outline-next-heading))
  7682. ((point-max))))))
  7683. (if (symbolp tprop)
  7684. ;; TPROP is a text property symbol.
  7685. (put-text-property start end tprop p)
  7686. ;; TPROP is an alist with (property . function) elements.
  7687. (pcase-dolist (`(,prop . ,f) tprop)
  7688. (put-text-property start end prop (funcall f p)))))))
  7689. (defun org-refresh-category-properties ()
  7690. "Refresh category text properties in the buffer."
  7691. (let ((case-fold-search t)
  7692. (inhibit-read-only t)
  7693. (default-category
  7694. (cond ((null org-category)
  7695. (if buffer-file-name
  7696. (file-name-sans-extension
  7697. (file-name-nondirectory buffer-file-name))
  7698. "???"))
  7699. ((symbolp org-category) (symbol-name org-category))
  7700. (t org-category))))
  7701. (with-silent-modifications
  7702. (org-with-wide-buffer
  7703. ;; Set buffer-wide property from keyword. Search last #+CATEGORY
  7704. ;; keyword. If none is found, fall-back to `org-category' or
  7705. ;; buffer file name, or set it by the document property drawer.
  7706. (put-text-property
  7707. (point-min) (point-max)
  7708. 'org-category
  7709. (catch 'buffer-category
  7710. (goto-char (point-max))
  7711. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  7712. (let ((element (org-element-at-point)))
  7713. (when (eq (org-element-type element) 'keyword)
  7714. (throw 'buffer-category
  7715. (org-element-property :value element)))))
  7716. default-category))
  7717. ;; Set categories from the document property drawer or
  7718. ;; property drawers in the outline. If category is found in
  7719. ;; the property drawer for the whole buffer that value
  7720. ;; overrides the keyword-based value set above.
  7721. (goto-char (point-min))
  7722. (let ((regexp (org-re-property "CATEGORY")))
  7723. (while (re-search-forward regexp nil t)
  7724. (let ((value (match-string-no-properties 3)))
  7725. (when (org-at-property-p)
  7726. (put-text-property
  7727. (save-excursion (org-back-to-heading-or-point-min t))
  7728. (save-excursion (if (org-before-first-heading-p)
  7729. (point-max)
  7730. (org-end-of-subtree t t)))
  7731. 'org-category
  7732. value)))))))))
  7733. (defun org-refresh-stats-properties ()
  7734. "Refresh stats text properties in the buffer."
  7735. (with-silent-modifications
  7736. (org-with-point-at 1
  7737. (let ((regexp (concat org-outline-regexp-bol
  7738. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  7739. (while (re-search-forward regexp nil t)
  7740. (let* ((numerator (string-to-number (match-string 1)))
  7741. (denominator (and (match-end 2)
  7742. (string-to-number (match-string 2))))
  7743. (stats (cond ((not denominator) numerator) ;percent
  7744. ((= denominator 0) 0)
  7745. (t (/ (* numerator 100) denominator)))))
  7746. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  7747. 'org-stats stats)))))))
  7748. (defun org-refresh-effort-properties ()
  7749. "Refresh effort properties."
  7750. (org-refresh-properties
  7751. org-effort-property
  7752. '((effort . identity)
  7753. (effort-minutes . org-duration-to-minutes))))
  7754. (defun org-find-file-at-mouse (ev)
  7755. "Open file link or URL at mouse."
  7756. (interactive "e")
  7757. (mouse-set-point ev)
  7758. (org-open-at-point 'in-emacs))
  7759. (defun org-open-at-mouse (ev)
  7760. "Open file link or URL at mouse.
  7761. See the docstring of `org-open-file' for details."
  7762. (interactive "e")
  7763. (mouse-set-point ev)
  7764. (when (eq major-mode 'org-agenda-mode)
  7765. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  7766. (org-open-at-point))
  7767. (defvar org-window-config-before-follow-link nil
  7768. "The window configuration before following a link.
  7769. This is saved in case the need arises to restore it.")
  7770. (defun org--file-default-apps ()
  7771. "Return the default applications for this operating system."
  7772. (pcase system-type
  7773. (`darwin org-file-apps-macos)
  7774. (`windows-nt org-file-apps-windowsnt)
  7775. (_ org-file-apps-gnu)))
  7776. (defun org--file-apps-entry-dlink-p (entry)
  7777. "Non-nil if ENTRY should be matched against the link by `org-open-file'.
  7778. It assumes that is the case when the entry uses a regular
  7779. expression which has at least one grouping construct and the
  7780. action is either a Lisp form or a command string containing
  7781. \"%1\", i.e., using at least one subexpression match as
  7782. a parameter."
  7783. (pcase entry
  7784. (`(,selector . ,action)
  7785. (and (stringp selector)
  7786. (> (regexp-opt-depth selector) 0)
  7787. (or (and (stringp action)
  7788. (string-match "%[0-9]" action))
  7789. (consp action))))
  7790. (_ nil)))
  7791. (defun org--file-apps-regexp-alist (list &optional add-auto-mode)
  7792. "Convert extensions to regular expressions in the cars of LIST.
  7793. Also, weed out any non-string entries, because the return value
  7794. is used only for regexp matching.
  7795. When ADD-AUTO-MODE is non-nil, make all matches in `auto-mode-alist'
  7796. point to the symbol `emacs', indicating that the file should be
  7797. opened in Emacs."
  7798. (append
  7799. (delq nil
  7800. (mapcar (lambda (x)
  7801. (unless (not (stringp (car x)))
  7802. (if (string-match "\\W" (car x))
  7803. x
  7804. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  7805. list))
  7806. (when add-auto-mode
  7807. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  7808. ;;;###autoload
  7809. (defun org-open-file (path &optional in-emacs line search)
  7810. "Open the file at PATH.
  7811. First, this expands any special file name abbreviations. Then the
  7812. configuration variable `org-file-apps' is checked if it contains an
  7813. entry for this file type, and if yes, the corresponding command is launched.
  7814. If no application is found, Emacs simply visits the file.
  7815. With optional prefix argument IN-EMACS, Emacs will visit the file.
  7816. With a double \\[universal-argument] \\[universal-argument] \
  7817. prefix arg, Org tries to avoid opening in Emacs
  7818. and to use an external application to visit the file.
  7819. Optional LINE specifies a line to go to, optional SEARCH a string
  7820. to search for. If LINE or SEARCH is given, the file will be
  7821. opened in Emacs, unless an entry from `org-file-apps' that makes
  7822. use of groups in a regexp matches.
  7823. If you want to change the way frames are used when following a
  7824. link, please customize `org-link-frame-setup'.
  7825. If the file does not exist, throw an error."
  7826. (let* ((file (if (equal path "") buffer-file-name
  7827. (substitute-in-file-name (expand-file-name path))))
  7828. (file-apps (append org-file-apps (org--file-default-apps)))
  7829. (apps (cl-remove-if #'org--file-apps-entry-dlink-p file-apps))
  7830. (apps-dlink (cl-remove-if-not #'org--file-apps-entry-dlink-p
  7831. file-apps))
  7832. (remp (and (assq 'remote apps) (file-remote-p file)))
  7833. (dirp (unless remp (file-directory-p file)))
  7834. (file (if (and dirp org-open-directory-means-index-dot-org)
  7835. (concat (file-name-as-directory file) "index.org")
  7836. file))
  7837. (a-m-a-p (assq 'auto-mode apps))
  7838. (dfile (downcase file))
  7839. ;; Reconstruct the original link from the PATH, LINE and
  7840. ;; SEARCH args.
  7841. (link (cond (line (concat file "::" (number-to-string line)))
  7842. (search (concat file "::" search))
  7843. (t file)))
  7844. (dlink (downcase link))
  7845. (ext
  7846. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  7847. (match-string 1 dfile)))
  7848. (save-position-maybe
  7849. (let ((old-buffer (current-buffer))
  7850. (old-pos (point))
  7851. (old-mode major-mode))
  7852. (lambda ()
  7853. (and (derived-mode-p 'org-mode)
  7854. (eq old-mode 'org-mode)
  7855. (or (not (eq old-buffer (current-buffer)))
  7856. (not (eq old-pos (point))))
  7857. (org-mark-ring-push old-pos old-buffer)))))
  7858. cmd link-match-data)
  7859. (cond
  7860. ((member in-emacs '((16) system))
  7861. (setq cmd (cdr (assq 'system apps))))
  7862. (in-emacs (setq cmd 'emacs))
  7863. (t
  7864. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  7865. (and dirp (cdr (assq 'directory apps)))
  7866. ;; First, try matching against apps-dlink if we
  7867. ;; get a match here, store the match data for
  7868. ;; later.
  7869. (let ((match (assoc-default dlink apps-dlink
  7870. 'string-match)))
  7871. (if match
  7872. (progn (setq link-match-data (match-data))
  7873. match)
  7874. (progn (setq in-emacs (or in-emacs line search))
  7875. nil))) ; if we have no match in apps-dlink,
  7876. ; always open the file in emacs if line or search
  7877. ; is given (for backwards compatibility)
  7878. (assoc-default dfile
  7879. (org--file-apps-regexp-alist apps a-m-a-p)
  7880. 'string-match)
  7881. (cdr (assoc ext apps))
  7882. (cdr (assq t apps))))))
  7883. (when (eq cmd 'system)
  7884. (setq cmd (cdr (assq 'system apps))))
  7885. (when (eq cmd 'default)
  7886. (setq cmd (cdr (assoc t apps))))
  7887. (when (eq cmd 'mailcap)
  7888. (require 'mailcap)
  7889. (mailcap-parse-mailcaps)
  7890. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  7891. (command (mailcap-mime-info mime-type)))
  7892. (if (stringp command)
  7893. (setq cmd command)
  7894. (setq cmd 'emacs))))
  7895. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  7896. (not (file-exists-p file))
  7897. (not org-open-non-existing-files))
  7898. (user-error "No such file: %s" file))
  7899. (cond
  7900. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  7901. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  7902. (while (string-match "['\"]%s['\"]" cmd)
  7903. (setq cmd (replace-match "%s" t t cmd)))
  7904. (setq cmd (replace-regexp-in-string
  7905. "%s"
  7906. (shell-quote-argument (convert-standard-filename file))
  7907. cmd
  7908. nil t))
  7909. ;; Replace "%1", "%2" etc. in command with group matches from regex
  7910. (save-match-data
  7911. (let ((match-index 1)
  7912. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  7913. (set-match-data link-match-data)
  7914. (while (<= match-index number-of-groups)
  7915. (let ((regex (concat "%" (number-to-string match-index)))
  7916. (replace-with (match-string match-index dlink)))
  7917. (while (string-match regex cmd)
  7918. (setq cmd (replace-match replace-with t t cmd))))
  7919. (setq match-index (+ match-index 1)))))
  7920. (save-window-excursion
  7921. (message "Running %s...done" cmd)
  7922. ;; Handlers such as "gio open" and kde-open5 start viewer in background
  7923. ;; and exit immediately. Use pipe connection type instead of pty to
  7924. ;; avoid killing children processes with SIGHUP when temporary terminal
  7925. ;; session is finished.
  7926. ;;
  7927. ;; TODO: Once minimum Emacs version is 25.1 or above, consider using
  7928. ;; the `make-process' invocation from 5db61eb0f929 to get more helpful
  7929. ;; error messages.
  7930. (let ((process-connection-type nil))
  7931. (start-process-shell-command cmd nil cmd))
  7932. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  7933. ((or (stringp cmd)
  7934. (eq cmd 'emacs))
  7935. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  7936. (widen)
  7937. (cond (line (org-goto-line line)
  7938. (when (derived-mode-p 'org-mode) (org-reveal)))
  7939. (search (condition-case err
  7940. (org-link-search search)
  7941. ;; Save position before error-ing out so user
  7942. ;; can easily move back to the original buffer.
  7943. (error (funcall save-position-maybe)
  7944. (error (nth 1 err)))))))
  7945. ((functionp cmd)
  7946. (save-match-data
  7947. (set-match-data link-match-data)
  7948. (condition-case nil
  7949. (funcall cmd file link)
  7950. ;; FIXME: Remove this check when most default installations
  7951. ;; of Emacs have at least Org 9.0.
  7952. ((debug wrong-number-of-arguments wrong-type-argument
  7953. invalid-function)
  7954. (user-error "Please see Org News for version 9.0 about \
  7955. `org-file-apps'--Lisp error: %S" cmd)))))
  7956. ((consp cmd)
  7957. ;; FIXME: Remove this check when most default installations of
  7958. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  7959. ;; fall back to `org-link-frame-setup' for an old usage of
  7960. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  7961. (user-error "Please see Org News for version 9.0 about \
  7962. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  7963. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  7964. (funcall save-position-maybe)))
  7965. ;;;###autoload
  7966. (defun org-open-at-point-global ()
  7967. "Follow a link or a time-stamp like Org mode does.
  7968. Also follow links and emails as seen by `thing-at-point'.
  7969. This command can be called in any mode to follow an external
  7970. link or a time-stamp that has Org mode syntax. Its behavior
  7971. is undefined when called on internal links like fuzzy links.
  7972. Raise a user error when there is nothing to follow."
  7973. (interactive)
  7974. (let ((tap-url (thing-at-point 'url))
  7975. (tap-email (thing-at-point 'email)))
  7976. (cond ((org-in-regexp org-link-any-re)
  7977. (org-link-open-from-string (match-string-no-properties 0)))
  7978. ((or (org-in-regexp org-ts-regexp-both nil t)
  7979. (org-in-regexp org-tsr-regexp-both nil t))
  7980. (org-follow-timestamp-link))
  7981. (tap-url (org-link-open-from-string tap-url))
  7982. (tap-email (org-link-open-from-string
  7983. (concat "mailto:" tap-email)))
  7984. (t (user-error "No link found")))))
  7985. (defvar org-open-at-point-functions nil
  7986. "Hook that is run when following a link at point.
  7987. Functions in this hook must return t if they identify and follow
  7988. a link at point. If they don't find anything interesting at point,
  7989. they must return nil.")
  7990. (defun org-open-at-point (&optional arg)
  7991. "Open link, timestamp, footnote or tags at point.
  7992. When point is on a link, follow it. Normally, files will be
  7993. opened by an appropriate application. If the optional prefix
  7994. argument ARG is non-nil, Emacs will visit the file. With
  7995. a double prefix argument, try to open outside of Emacs, in the
  7996. application the system uses for this file type.
  7997. When point is on a timestamp, open the agenda at the day
  7998. specified.
  7999. When point is a footnote definition, move to the first reference
  8000. found. If it is on a reference, move to the associated
  8001. definition.
  8002. When point is on a headline, display a list of every link in the
  8003. entry, so it is possible to pick one, or all, of them. If point
  8004. is on a tag, call `org-tags-view' instead.
  8005. On top of syntactically correct links, this function also tries
  8006. to open links and time-stamps in comments, node properties, and
  8007. keywords if point is on something looking like a timestamp or
  8008. a link."
  8009. (interactive "P")
  8010. (org-load-modules-maybe)
  8011. (setq org-window-config-before-follow-link (current-window-configuration))
  8012. (org-remove-occur-highlights nil nil t)
  8013. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  8014. (let* ((context
  8015. ;; Only consider supported types, even if they are not the
  8016. ;; closest one.
  8017. (org-element-lineage
  8018. (org-element-context)
  8019. '(citation citation-reference clock comment comment-block
  8020. footnote-definition footnote-reference headline
  8021. inline-src-block inlinetask keyword link node-property
  8022. planning src-block timestamp)
  8023. t))
  8024. (type (org-element-type context))
  8025. (value (org-element-property :value context)))
  8026. (cond
  8027. ((not type) (user-error "No link found"))
  8028. ;; No valid link at point. For convenience, look if something
  8029. ;; looks like a link under point in some specific places.
  8030. ((memq type '(comment comment-block node-property keyword))
  8031. (call-interactively #'org-open-at-point-global))
  8032. ;; On a headline or an inlinetask, but not on a timestamp,
  8033. ;; a link, a footnote reference or a citation.
  8034. ((memq type '(headline inlinetask))
  8035. (org-match-line org-complex-heading-regexp)
  8036. (let ((tags-beg (match-beginning 5))
  8037. (tags-end (match-end 5)))
  8038. (if (and tags-beg (>= (point) tags-beg) (< (point) tags-end))
  8039. ;; On tags.
  8040. (org-tags-view
  8041. arg
  8042. (save-excursion
  8043. (let* ((beg-tag (or (search-backward ":" tags-beg 'at-limit) (point)))
  8044. (end-tag (search-forward ":" tags-end nil 2)))
  8045. (buffer-substring (1+ beg-tag) (1- end-tag)))))
  8046. ;; Not on tags.
  8047. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  8048. (`(nil . ,_)
  8049. (require 'org-attach)
  8050. (when (org-attach-dir)
  8051. (message "Opening attachment")
  8052. (if (equal arg '(4))
  8053. (org-attach-reveal-in-emacs)
  8054. (org-attach-reveal))))
  8055. (`(,links . ,links-end)
  8056. (dolist (link (if (stringp links) (list links) links))
  8057. (search-forward link nil links-end)
  8058. (goto-char (match-beginning 0))
  8059. (org-open-at-point arg)))))))
  8060. ;; On a footnote reference or at definition's label.
  8061. ((or (eq type 'footnote-reference)
  8062. (and (eq type 'footnote-definition)
  8063. (save-excursion
  8064. ;; Do not validate action when point is on the
  8065. ;; spaces right after the footnote label, in order
  8066. ;; to be on par with behavior on links.
  8067. (skip-chars-forward " \t")
  8068. (let ((begin
  8069. (org-element-property :contents-begin context)))
  8070. (if begin (< (point) begin)
  8071. (= (org-element-property :post-affiliated context)
  8072. (line-beginning-position)))))))
  8073. (org-footnote-action))
  8074. ;; On a planning line. Check if we are really on a timestamp.
  8075. ((and (eq type 'planning)
  8076. (org-in-regexp org-ts-regexp-both nil t))
  8077. (org-follow-timestamp-link))
  8078. ;; On a clock line, make sure point is on the timestamp
  8079. ;; before opening it.
  8080. ((and (eq type 'clock)
  8081. value
  8082. (>= (point) (org-element-property :begin value))
  8083. (<= (point) (org-element-property :end value)))
  8084. (org-follow-timestamp-link))
  8085. ((eq type 'src-block) (org-babel-open-src-block-result))
  8086. ;; Do nothing on white spaces after an object.
  8087. ((>= (point)
  8088. (save-excursion
  8089. (goto-char (org-element-property :end context))
  8090. (skip-chars-backward " \t")
  8091. (point)))
  8092. (user-error "No link found"))
  8093. ((eq type 'inline-src-block) (org-babel-open-src-block-result))
  8094. ((eq type 'timestamp) (org-follow-timestamp-link))
  8095. ((eq type 'link) (org-link-open context arg))
  8096. ((memq type '(citation citation-reference)) (org-cite-follow context arg))
  8097. (t (user-error "No link found")))))
  8098. (run-hook-with-args 'org-follow-link-hook))
  8099. ;;;###autoload
  8100. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  8101. "Offer links in the current entry and return the selected link.
  8102. If there is only one link, return it.
  8103. If NTH is an integer, return the NTH link found.
  8104. If ZERO is a string, check also this string for a link, and if
  8105. there is one, return it."
  8106. (with-current-buffer buffer
  8107. (org-with-wide-buffer
  8108. (goto-char marker)
  8109. (let ((cnt ?0)
  8110. have-zero end links link c)
  8111. (when (and (stringp zero) (string-match org-link-bracket-re zero))
  8112. (push (match-string 0 zero) links)
  8113. (setq cnt (1- cnt) have-zero t))
  8114. (save-excursion
  8115. (org-back-to-heading t)
  8116. (setq end (save-excursion (outline-next-heading) (point)))
  8117. (while (re-search-forward org-link-any-re end t)
  8118. (push (match-string 0) links))
  8119. (setq links (org-uniquify (reverse links))))
  8120. (cond
  8121. ((null links)
  8122. (message "No links"))
  8123. ((equal (length links) 1)
  8124. (setq link (car links)))
  8125. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  8126. (setq link (nth (if have-zero nth (1- nth)) links)))
  8127. (t ; we have to select a link
  8128. (save-excursion
  8129. (save-window-excursion
  8130. (delete-other-windows)
  8131. (with-output-to-temp-buffer "*Select Link*"
  8132. (dolist (l links)
  8133. (cond
  8134. ((not (string-match org-link-bracket-re l))
  8135. (princ (format "[%c] %s\n" (cl-incf cnt)
  8136. (org-unbracket-string "<" ">" l))))
  8137. ((match-end 2)
  8138. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  8139. (match-string 2 l) (match-string 1 l))))
  8140. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  8141. (match-string 1 l)))))))
  8142. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  8143. (message "Select link to open, RET to open all:")
  8144. (setq c (read-char-exclusive))
  8145. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  8146. (when (equal c ?q) (user-error "Abort"))
  8147. (if (equal c ?\C-m)
  8148. (setq link links)
  8149. (setq nth (- c ?0))
  8150. (when have-zero (setq nth (1+ nth)))
  8151. (unless (and (integerp nth) (>= (length links) nth))
  8152. (user-error "Invalid link selection"))
  8153. (setq link (nth (1- nth) links)))))
  8154. (cons link end)))))
  8155. ;;; File search
  8156. (defun org-do-occur (regexp &optional cleanup)
  8157. "Call the Emacs command `occur'.
  8158. If CLEANUP is non-nil, remove the printout of the regular expression
  8159. in the *Occur* buffer. This is useful if the regex is long and not useful
  8160. to read."
  8161. (occur regexp)
  8162. (when cleanup
  8163. (let ((cwin (selected-window)) win beg end)
  8164. (when (setq win (get-buffer-window "*Occur*"))
  8165. (select-window win))
  8166. (goto-char (point-min))
  8167. (when (re-search-forward "match[a-z]+" nil t)
  8168. (setq beg (match-end 0))
  8169. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  8170. (setq end (1- (match-beginning 0)))))
  8171. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  8172. (goto-char (point-min))
  8173. (select-window cwin))))
  8174. ;;; The Mark Ring
  8175. (defvar org-mark-ring nil
  8176. "Mark ring for positions before jumps in Org mode.")
  8177. (defvar org-mark-ring-last-goto nil
  8178. "Last position in the mark ring used to go back.")
  8179. ;; Fill and close the ring
  8180. (setq org-mark-ring nil)
  8181. (setq org-mark-ring-last-goto nil) ;in case file is reloaded
  8182. (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
  8183. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  8184. org-mark-ring)
  8185. (defun org-mark-ring-push (&optional pos buffer)
  8186. "Put the current position into the mark ring and rotate it.
  8187. Also push position into the Emacs mark ring. If optional
  8188. argument POS and BUFFER are not nil, mark this location instead."
  8189. (interactive)
  8190. (let ((pos (or pos (point)))
  8191. (buffer (or buffer (current-buffer))))
  8192. (with-current-buffer buffer
  8193. (org-with-point-at pos (push-mark nil t)))
  8194. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  8195. (move-marker (car org-mark-ring) pos buffer))
  8196. (message
  8197. (substitute-command-keys
  8198. "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
  8199. (defun org-mark-ring-goto (&optional n)
  8200. "Jump to the previous position in the mark ring.
  8201. With prefix arg N, jump back that many stored positions. When
  8202. called several times in succession, walk through the entire ring.
  8203. Org mode commands jumping to a different position in the current file,
  8204. or to another Org file, automatically push the old position onto the ring."
  8205. (interactive "p")
  8206. (let (p m)
  8207. (if (eq last-command this-command)
  8208. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  8209. (setq p org-mark-ring))
  8210. (setq org-mark-ring-last-goto p)
  8211. (setq m (car p))
  8212. (pop-to-buffer-same-window (marker-buffer m))
  8213. (goto-char m)
  8214. (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  8215. ;;; Following specific links
  8216. (defvar org-agenda-buffer-tmp-name)
  8217. (defvar org-agenda-start-on-weekday)
  8218. (defvar org-agenda-buffer-name)
  8219. (defun org-follow-timestamp-link ()
  8220. "Open an agenda view for the time-stamp date/range at point."
  8221. ;; Avoid changing the global value.
  8222. (let ((org-agenda-buffer-name org-agenda-buffer-name))
  8223. (cond
  8224. ((org-at-date-range-p t)
  8225. (let ((org-agenda-start-on-weekday)
  8226. (t1 (match-string 1))
  8227. (t2 (match-string 2)) tt1 tt2)
  8228. (setq tt1 (time-to-days (org-time-string-to-time t1))
  8229. tt2 (time-to-days (org-time-string-to-time t2)))
  8230. (let ((org-agenda-buffer-tmp-name
  8231. (format "*Org Agenda(a:%s)"
  8232. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  8233. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  8234. ((org-at-timestamp-p 'lax)
  8235. (let ((org-agenda-buffer-tmp-name
  8236. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  8237. (org-agenda-list nil (time-to-days (org-time-string-to-time
  8238. (substring (match-string 1) 0 10)))
  8239. 1)))
  8240. (t (error "This should not happen")))))
  8241. ;;; Following file links
  8242. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  8243. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  8244. (declare-function mailcap-mime-info
  8245. "mailcap" (string &optional request no-decode))
  8246. (defvar org-wait nil)
  8247. ;;;; Refiling
  8248. (defun org-get-org-file ()
  8249. "Read a filename, with default directory `org-directory'."
  8250. (let ((default (or org-default-notes-file remember-data-file)))
  8251. (read-file-name (format "File name [%s]: " default)
  8252. (file-name-as-directory org-directory)
  8253. default)))
  8254. (defun org-notes-order-reversed-p ()
  8255. "Check if the current file should receive notes in reversed order."
  8256. (cond
  8257. ((not org-reverse-note-order) nil)
  8258. ((eq t org-reverse-note-order) t)
  8259. ((not (listp org-reverse-note-order)) nil)
  8260. (t (catch 'exit
  8261. (dolist (entry org-reverse-note-order)
  8262. (when (string-match (car entry) buffer-file-name)
  8263. (throw 'exit (cdr entry))))))))
  8264. (defvar org-agenda-new-buffers nil
  8265. "Buffers created to visit agenda files.")
  8266. (declare-function org-string-nw-p "org-macs" (s))
  8267. ;;;; Dynamic blocks
  8268. (defun org-find-dblock (name)
  8269. "Find the first dynamic block with name NAME in the buffer.
  8270. If not found, stay at current position and return nil."
  8271. (let ((case-fold-search t) pos)
  8272. (save-excursion
  8273. (goto-char (point-min))
  8274. (setq pos (and (re-search-forward
  8275. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  8276. (match-beginning 0))))
  8277. (when pos (goto-char pos))
  8278. pos))
  8279. (defun org-create-dblock (plist)
  8280. "Create a dynamic block section, with parameters taken from PLIST.
  8281. PLIST must contain a :name entry which is used as the name of the block."
  8282. (when (string-match "\\S-" (buffer-substring (line-beginning-position)
  8283. (line-end-position)))
  8284. (end-of-line 1)
  8285. (newline))
  8286. (let ((col (current-column))
  8287. (name (plist-get plist :name)))
  8288. (insert "#+BEGIN: " name)
  8289. (while plist
  8290. (if (eq (car plist) :name)
  8291. (setq plist (cddr plist))
  8292. (insert " " (prin1-to-string (pop plist)))))
  8293. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  8294. (beginning-of-line -2)))
  8295. (defun org-prepare-dblock ()
  8296. "Prepare dynamic block for refresh.
  8297. This empties the block, puts the cursor at the insert position and returns
  8298. the property list including an extra property :name with the block name."
  8299. (unless (looking-at org-dblock-start-re)
  8300. (user-error "Not at a dynamic block"))
  8301. (let* ((begdel (1+ (match-end 0)))
  8302. (name (org-no-properties (match-string 1)))
  8303. (params (append (list :name name)
  8304. (read (concat "(" (match-string 3) ")")))))
  8305. (save-excursion
  8306. (beginning-of-line 1)
  8307. (skip-chars-forward " \t")
  8308. (setq params (plist-put params :indentation-column (current-column))))
  8309. (unless (re-search-forward org-dblock-end-re nil t)
  8310. (error "Dynamic block not terminated"))
  8311. (setq params
  8312. (append params
  8313. (list :content (buffer-substring
  8314. begdel (match-beginning 0)))))
  8315. (delete-region begdel (match-beginning 0))
  8316. (goto-char begdel)
  8317. (open-line 1)
  8318. params))
  8319. (defun org-map-dblocks (&optional command)
  8320. "Apply COMMAND to all dynamic blocks in the current buffer.
  8321. If COMMAND is not given, use `org-update-dblock'."
  8322. (let ((cmd (or command 'org-update-dblock)))
  8323. (save-excursion
  8324. (goto-char (point-min))
  8325. (while (re-search-forward org-dblock-start-re nil t)
  8326. (goto-char (match-beginning 0))
  8327. (save-excursion
  8328. (condition-case nil
  8329. (funcall cmd)
  8330. (error (message "Error during update of dynamic block"))))
  8331. (unless (re-search-forward org-dblock-end-re nil t)
  8332. (error "Dynamic block not terminated"))))))
  8333. (defvar org-dynamic-block-alist nil
  8334. "Alist defining all the Org dynamic blocks.
  8335. The key is the dynamic block type name, as a string. The value
  8336. is the function used to insert the dynamic block.
  8337. Use `org-dynamic-block-define' to populate it.")
  8338. (defun org-dynamic-block-function (type)
  8339. "Return function associated to a given dynamic block type.
  8340. TYPE is the dynamic block type, as a string."
  8341. (cdr (assoc type org-dynamic-block-alist)))
  8342. (defun org-dynamic-block-types ()
  8343. "List all defined dynamic block types."
  8344. (mapcar #'car org-dynamic-block-alist))
  8345. ;;;###org-autoload
  8346. (defun org-dynamic-block-define (type func)
  8347. "Define dynamic block TYPE with FUNC.
  8348. TYPE is a string. FUNC is the function creating the dynamic
  8349. block of such type."
  8350. (pcase (assoc type org-dynamic-block-alist)
  8351. (`nil (push (cons type func) org-dynamic-block-alist))
  8352. (def (setcdr def func))))
  8353. (defun org-dynamic-block-insert-dblock (type &optional interactive-p)
  8354. "Insert a dynamic block of type TYPE.
  8355. When used interactively, select the dynamic block types among
  8356. defined types, per `org-dynamic-block-define'. If INTERACTIVE-P
  8357. is non-nil, call the dynamic block function interactively."
  8358. (interactive (list (completing-read "Dynamic block: "
  8359. (org-dynamic-block-types))
  8360. t))
  8361. (pcase (org-dynamic-block-function type)
  8362. (`nil (error "No such dynamic block: %S" type))
  8363. ((and f (pred functionp))
  8364. (if interactive-p (call-interactively f) (funcall f)))
  8365. (_ (error "Invalid function for dynamic block %S" type))))
  8366. (defun org-dblock-update (&optional arg)
  8367. "User command for updating dynamic blocks.
  8368. Update the dynamic block at point. With prefix ARG, update all dynamic
  8369. blocks in the buffer."
  8370. (interactive "P")
  8371. (if arg
  8372. (org-update-all-dblocks)
  8373. (or (looking-at org-dblock-start-re)
  8374. (org-beginning-of-dblock))
  8375. (org-update-dblock)))
  8376. (defun org-update-dblock ()
  8377. "Update the dynamic block at point.
  8378. This means to empty the block, parse for parameters and then call
  8379. the correct writing function."
  8380. (interactive)
  8381. (save-excursion
  8382. (let* ((win (selected-window))
  8383. (pos (point))
  8384. (line (org-current-line))
  8385. (params (org-prepare-dblock))
  8386. (name (plist-get params :name))
  8387. (indent (plist-get params :indentation-column))
  8388. (cmd (intern (concat "org-dblock-write:" name))))
  8389. (message "Updating dynamic block `%s' at line %d..." name line)
  8390. (funcall cmd params)
  8391. (message "Updating dynamic block `%s' at line %d...done" name line)
  8392. (goto-char pos)
  8393. (when (and indent (> indent 0))
  8394. (setq indent (make-string indent ?\ ))
  8395. (save-excursion
  8396. (select-window win)
  8397. (org-beginning-of-dblock)
  8398. (forward-line 1)
  8399. (while (not (looking-at org-dblock-end-re))
  8400. (insert indent)
  8401. (beginning-of-line 2))
  8402. (when (looking-at org-dblock-end-re)
  8403. (and (looking-at "[ \t]+")
  8404. (replace-match ""))
  8405. (insert indent)))))))
  8406. (defun org-beginning-of-dblock ()
  8407. "Find the beginning of the dynamic block at point.
  8408. Error if there is no such block at point."
  8409. (let ((pos (point))
  8410. beg)
  8411. (end-of-line 1)
  8412. (if (and (re-search-backward org-dblock-start-re nil t)
  8413. (setq beg (match-beginning 0))
  8414. (re-search-forward org-dblock-end-re nil t)
  8415. (> (match-end 0) pos))
  8416. (goto-char beg)
  8417. (goto-char pos)
  8418. (error "Not in a dynamic block"))))
  8419. (defun org-update-all-dblocks ()
  8420. "Update all dynamic blocks in the buffer.
  8421. This function can be used in a hook."
  8422. (interactive)
  8423. (when (derived-mode-p 'org-mode)
  8424. (org-map-dblocks 'org-update-dblock)))
  8425. ;;;; Completion
  8426. (declare-function org-export-backend-options "ox" (cl-x) t)
  8427. (defun org-get-export-keywords ()
  8428. "Return a list of all currently understood export keywords.
  8429. Export keywords include options, block names, attributes and
  8430. keywords relative to each registered export back-end."
  8431. (let (keywords)
  8432. (dolist (backend
  8433. (bound-and-true-p org-export-registered-backends)
  8434. (delq nil keywords))
  8435. ;; Back-end name (for keywords, like #+LATEX:)
  8436. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  8437. (dolist (option-entry (org-export-backend-options backend))
  8438. ;; Back-end options.
  8439. (push (nth 1 option-entry) keywords)))))
  8440. (defconst org-options-keywords
  8441. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  8442. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  8443. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  8444. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  8445. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  8446. (defcustom org-structure-template-alist
  8447. '(("a" . "export ascii")
  8448. ("c" . "center")
  8449. ("C" . "comment")
  8450. ("e" . "example")
  8451. ("E" . "export")
  8452. ("h" . "export html")
  8453. ("l" . "export latex")
  8454. ("q" . "quote")
  8455. ("s" . "src")
  8456. ("v" . "verse"))
  8457. "An alist of keys and block types.
  8458. `org-insert-structure-template' will display a menu with this
  8459. list of templates to choose from. The block type is inserted,
  8460. with \"#+BEGIN_\" and \"#+END_\" added automatically.
  8461. The menu keys are defined by the car of each entry in this alist.
  8462. If two entries have the keys \"a\" and \"aa\" respectively, the
  8463. former will be inserted by typing \"a TAB/RET/SPC\" and the
  8464. latter will be inserted by typing \"aa\". If an entry with the
  8465. key \"aab\" is later added, it can be inserted by typing \"ab\".
  8466. If loaded, Org Tempo also uses `org-structure-template-alist'. A
  8467. block can be inserted by pressing TAB after the string \"<KEY\"."
  8468. :group 'org-edit-structure
  8469. :type '(repeat
  8470. (cons (string :tag "Key")
  8471. (string :tag "Template")))
  8472. :package-version '(Org . "9.2"))
  8473. (defun org--check-org-structure-template-alist (&optional checklist)
  8474. "Check whether `org-structure-template-alist' is set up correctly.
  8475. In particular, check if the Org 9.2 format is used as opposed to
  8476. previous format."
  8477. (let ((elm (cl-remove-if-not (lambda (x) (listp (cdr x)))
  8478. (or (eval checklist)
  8479. org-structure-template-alist))))
  8480. (when elm
  8481. (org-display-warning
  8482. (format "
  8483. Please update the entries of `%s'.
  8484. In Org 9.2 the format was changed from something like
  8485. (\"s\" \"#+BEGIN_SRC ?\\n#+END_SRC\")
  8486. to something like
  8487. (\"s\" . \"src\")
  8488. Please refer to the documentation of `org-structure-template-alist'.
  8489. The following entries must be updated:
  8490. %s"
  8491. (or checklist 'org-structure-template-alist)
  8492. (pp-to-string elm))))))
  8493. (defun org--insert-structure-template-mks ()
  8494. "Present `org-structure-template-alist' with `org-mks'.
  8495. Menus are added if keys require more than one keystroke. Tabs
  8496. are added to single key entries when more than one stroke is
  8497. needed. Keys longer than two characters are reduced to two
  8498. characters."
  8499. (org--check-org-structure-template-alist)
  8500. (let* (case-fold-search
  8501. (templates (append org-structure-template-alist
  8502. '(("\t" . "Press TAB, RET or SPC to write block name"))))
  8503. (keys (mapcar #'car templates))
  8504. (start-letters
  8505. (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
  8506. ;; Sort each element of `org-structure-template-alist' into
  8507. ;; sublists according to the first letter.
  8508. (superlist
  8509. (mapcar (lambda (letter)
  8510. (list letter
  8511. (cl-remove-if-not
  8512. (apply-partially #'string-match-p (concat "^" letter))
  8513. templates :key #'car)))
  8514. start-letters)))
  8515. (org-mks
  8516. (apply #'append
  8517. ;; Make an `org-mks' table. If only one element is
  8518. ;; present in a sublist, make it part of the top-menu,
  8519. ;; otherwise make a submenu according to the starting
  8520. ;; letter and populate it.
  8521. (mapcar (lambda (sublist)
  8522. (if (eq 1 (length (cadr sublist)))
  8523. (mapcar (lambda (elm)
  8524. (list (substring (car elm) 0 1)
  8525. (cdr elm) ""))
  8526. (cadr sublist))
  8527. ;; Create submenu.
  8528. (let* ((topkey (car sublist))
  8529. (elms (cadr sublist))
  8530. (keys (mapcar #'car elms))
  8531. (long (> (length elms) 3)))
  8532. (append
  8533. (list
  8534. ;; Make a description of the submenu.
  8535. (list topkey
  8536. (concat
  8537. (mapconcat #'cdr
  8538. (cl-subseq elms 0 (if long 3 (length elms)))
  8539. ", ")
  8540. (when long ", ..."))))
  8541. ;; List of entries in submenu.
  8542. (cl-mapcar #'list
  8543. (org--insert-structure-template-unique-keys keys)
  8544. (mapcar #'cdr elms)
  8545. (make-list (length elms) ""))))))
  8546. superlist))
  8547. "Select a key\n============"
  8548. "Key: ")))
  8549. (defun org--insert-structure-template-unique-keys (keys)
  8550. "Make a list of unique, two characters long elements from KEYS.
  8551. Elements of length one have a tab appended. Elements of length
  8552. two are kept as is. Longer elements are truncated to length two.
  8553. If an element cannot be made unique, an error is raised."
  8554. (let ((ordered-keys (cl-sort (copy-sequence keys) #'< :key #'length))
  8555. menu-keys)
  8556. (dolist (key ordered-keys)
  8557. (let ((potential-key
  8558. (cl-case (length key)
  8559. (1 (concat key "\t"))
  8560. (2 key)
  8561. (otherwise
  8562. (cl-find-if-not (lambda (k) (assoc k menu-keys))
  8563. (mapcar (apply-partially #'concat (substring key 0 1))
  8564. (split-string (substring key 1) "" t)))))))
  8565. (if (or (not potential-key) (assoc potential-key menu-keys))
  8566. (user-error "Could not make unique key for `%s'" key)
  8567. (push (cons potential-key key) menu-keys))))
  8568. (mapcar #'car
  8569. (cl-sort menu-keys #'<
  8570. :key (lambda (elm) (cl-position (cdr elm) keys))))))
  8571. (defun org-insert-structure-template (type)
  8572. "Insert a block structure of the type #+begin_foo/#+end_foo.
  8573. Select a block from `org-structure-template-alist' then type
  8574. either RET, TAB or SPC to write the block type. With an active
  8575. region, wrap the region in the block. Otherwise, insert an empty
  8576. block."
  8577. (interactive
  8578. (list (pcase (org--insert-structure-template-mks)
  8579. (`("\t" . ,_) (read-string "Structure type: "))
  8580. (`(,_ ,choice . ,_) choice))))
  8581. (let* ((region? (use-region-p))
  8582. (region-start (and region? (region-beginning)))
  8583. (region-end (and region? (copy-marker (region-end))))
  8584. (extended? (string-match-p "\\`\\(src\\|export\\)\\'" type))
  8585. (verbatim? (string-match-p
  8586. (concat "\\`" (regexp-opt '("example" "export" "src")))
  8587. type)))
  8588. (when region? (goto-char region-start))
  8589. (let ((column (current-indentation)))
  8590. (if (save-excursion (skip-chars-backward " \t") (bolp))
  8591. (beginning-of-line)
  8592. (insert "\n"))
  8593. (save-excursion
  8594. (indent-to column)
  8595. (insert (format "#+begin_%s%s\n" type (if extended? " " "")))
  8596. (when region?
  8597. (when verbatim? (org-escape-code-in-region (point) region-end))
  8598. (goto-char region-end)
  8599. ;; Ignore empty lines at the end of the region.
  8600. (skip-chars-backward " \r\t\n")
  8601. (end-of-line))
  8602. (unless (bolp) (insert "\n"))
  8603. (indent-to column)
  8604. (insert (format "#+end_%s" (car (split-string type))))
  8605. (if (looking-at "[ \t]*$") (replace-match "")
  8606. (insert "\n"))
  8607. (when (and (eobp) (not (bolp))) (insert "\n")))
  8608. (if extended? (end-of-line)
  8609. (forward-line)
  8610. (skip-chars-forward " \t")))))
  8611. ;;;; TODO, DEADLINE, Comments
  8612. (defun org-toggle-comment ()
  8613. "Change the COMMENT state of an entry."
  8614. (interactive)
  8615. (save-excursion
  8616. (org-back-to-heading)
  8617. (let ((case-fold-search nil))
  8618. (looking-at org-complex-heading-regexp))
  8619. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  8620. (skip-chars-forward " \t")
  8621. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  8622. (if (org-in-commented-heading-p t)
  8623. (delete-region (point)
  8624. (progn (search-forward " " (line-end-position) 'move)
  8625. (skip-chars-forward " \t")
  8626. (point)))
  8627. (insert org-comment-string)
  8628. (unless (eolp) (insert " ")))))
  8629. (defvar org-last-todo-state-is-todo nil
  8630. "This is non-nil when the last TODO state change led to a TODO state.
  8631. If the last change removed the TODO tag or switched to DONE, then
  8632. this is nil.")
  8633. (defvar org-todo-setup-filter-hook nil
  8634. "Hook for functions that pre-filter todo specs.
  8635. Each function takes a todo spec and returns either nil or the spec
  8636. transformed into canonical form." )
  8637. (defvar org-todo-get-default-hook nil
  8638. "Hook for functions that get a default item for todo.
  8639. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  8640. nil or a string to be used for the todo mark." )
  8641. (defvar org-agenda-headline-snapshot-before-repeat)
  8642. (defun org-current-effective-time ()
  8643. "Return current time adjusted for `org-extend-today-until' variable."
  8644. (let* ((ct (org-current-time))
  8645. (dct (decode-time ct))
  8646. (ct1
  8647. (cond
  8648. (org-use-last-clock-out-time-as-effective-time
  8649. (or (org-clock-get-last-clock-out-time) ct))
  8650. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  8651. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  8652. (t ct))))
  8653. ct1))
  8654. (defun org-todo-yesterday (&optional arg)
  8655. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  8656. (interactive "P")
  8657. (if (eq major-mode 'org-agenda-mode)
  8658. (apply 'org-agenda-todo-yesterday arg)
  8659. (let* ((org-use-effective-time t)
  8660. (hour (nth 2 (decode-time (org-current-time))))
  8661. (org-extend-today-until (1+ hour)))
  8662. (org-todo arg))))
  8663. (defvar org-block-entry-blocking ""
  8664. "First entry preventing the TODO state change.")
  8665. (defun org-cancel-repeater ()
  8666. "Cancel a repeater by setting its numeric value to zero."
  8667. (interactive)
  8668. (save-excursion
  8669. (org-back-to-heading t)
  8670. (let ((bound1 (point))
  8671. (bound0 (save-excursion (outline-next-heading) (point))))
  8672. (when (and (re-search-forward
  8673. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  8674. org-deadline-time-regexp "\\)\\|\\("
  8675. org-ts-regexp "\\)")
  8676. bound0 t)
  8677. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  8678. bound1 t))
  8679. (replace-match "0" t nil nil 1)))))
  8680. (defvar org-state)
  8681. (defvar org-blocked-by-checkboxes)
  8682. (defun org-todo (&optional arg)
  8683. "Change the TODO state of an item.
  8684. The state of an item is given by a keyword at the start of the heading,
  8685. like
  8686. *** TODO Write paper
  8687. *** DONE Call mom
  8688. The different keywords are specified in the variable `org-todo-keywords'.
  8689. By default the available states are \"TODO\" and \"DONE\". So, for this
  8690. example: when the item starts with TODO, it is changed to DONE.
  8691. When it starts with DONE, the DONE is removed. And when neither TODO nor
  8692. DONE are present, add TODO at the beginning of the heading.
  8693. You can set up single-character keys to fast-select the new state. See the
  8694. `org-todo-keywords' and `org-use-fast-todo-selection' for details.
  8695. With `\\[universal-argument]' prefix ARG, force logging the state change \
  8696. and take a
  8697. logging note.
  8698. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  8699. next set of TODO \
  8700. keywords (nextset).
  8701. Another way to achieve this is `S-C-<right>'.
  8702. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8703. prefix, circumvent any state blocking.
  8704. With numeric prefix arg, switch to the Nth state.
  8705. With a numeric prefix arg of 0, inhibit note taking for the change.
  8706. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  8707. When called through ELisp, arg is also interpreted in the following way:
  8708. `none' -> empty state
  8709. \"\" -> switch to empty state
  8710. `done' -> switch to DONE
  8711. `nextset' -> switch to the next set of keywords
  8712. `previousset' -> switch to the previous set of keywords
  8713. \"WAITING\" -> switch to the specified keyword, but only if it
  8714. really is a member of `org-todo-keywords'."
  8715. (interactive "P")
  8716. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  8717. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  8718. 'region-start-level 'region))
  8719. org-loop-over-headlines-in-active-region)
  8720. (org-map-entries
  8721. (lambda () (org-todo arg))
  8722. nil cl
  8723. (when (org-invisible-p) (org-end-of-subtree nil t))))
  8724. (when (equal arg '(16)) (setq arg 'nextset))
  8725. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  8726. (let ((org-blocker-hook org-blocker-hook)
  8727. commentp
  8728. case-fold-search)
  8729. (when (equal arg '(64))
  8730. (setq arg nil org-blocker-hook nil))
  8731. (when (and org-blocker-hook
  8732. (or org-inhibit-blocking
  8733. (org-entry-get nil "NOBLOCKING")))
  8734. (setq org-blocker-hook nil))
  8735. (save-excursion
  8736. (catch 'exit
  8737. (org-back-to-heading t)
  8738. (when (org-in-commented-heading-p t)
  8739. (org-toggle-comment)
  8740. (setq commentp t))
  8741. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  8742. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  8743. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  8744. (let* ((match-data (match-data))
  8745. (startpos (copy-marker (line-beginning-position)))
  8746. (force-log (and (equal arg '(4)) (prog1 t (setq arg nil))))
  8747. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  8748. (org-log-done org-log-done)
  8749. (org-log-repeat org-log-repeat)
  8750. (org-todo-log-states org-todo-log-states)
  8751. (org-inhibit-logging
  8752. (if (equal arg 0)
  8753. (progn (setq arg nil) 'note) org-inhibit-logging))
  8754. (this (match-string 1))
  8755. (hl-pos (match-beginning 0))
  8756. (head (org-get-todo-sequence-head this))
  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. (org-last-state (or this ""))
  8762. (completion-ignore-case t)
  8763. (member (member this org-todo-keywords-1))
  8764. (tail (cdr member))
  8765. (org-state (cond
  8766. ((eq arg 'right)
  8767. ;; Next state
  8768. (if this
  8769. (if tail (car tail) nil)
  8770. (car org-todo-keywords-1)))
  8771. ((eq arg 'left)
  8772. ;; Previous state
  8773. (unless (equal member org-todo-keywords-1)
  8774. (if this
  8775. (nth (- (length org-todo-keywords-1)
  8776. (length tail) 2)
  8777. org-todo-keywords-1)
  8778. (org-last org-todo-keywords-1))))
  8779. (arg
  8780. ;; User or caller requests a specific state.
  8781. (cond
  8782. ((equal arg "") nil)
  8783. ((eq arg 'none) nil)
  8784. ((eq arg 'done) (or done-word (car org-done-keywords)))
  8785. ((eq arg 'nextset)
  8786. (or (car (cdr (member head org-todo-heads)))
  8787. (car org-todo-heads)))
  8788. ((eq arg 'previousset)
  8789. (let ((org-todo-heads (reverse org-todo-heads)))
  8790. (or (car (cdr (member head org-todo-heads)))
  8791. (car org-todo-heads))))
  8792. ((car (member arg org-todo-keywords-1)))
  8793. ((stringp arg)
  8794. (user-error "State `%s' not valid in this file" arg))
  8795. ((nth (1- (prefix-numeric-value arg))
  8796. org-todo-keywords-1))))
  8797. ((and org-todo-key-trigger org-use-fast-todo-selection)
  8798. ;; Use fast selection.
  8799. (org-fast-todo-selection this))
  8800. ((null member) (or head (car org-todo-keywords-1)))
  8801. ((equal this final-done-word) nil) ;-> make empty
  8802. ((null tail) nil) ;-> first entry
  8803. ((memq interpret '(type priority))
  8804. (if (eq this-command last-command)
  8805. (car tail)
  8806. (if (> (length tail) 0)
  8807. (or done-word (car org-done-keywords))
  8808. nil)))
  8809. (t
  8810. (car tail))))
  8811. (org-state (or
  8812. (run-hook-with-args-until-success
  8813. 'org-todo-get-default-hook org-state org-last-state)
  8814. org-state))
  8815. (next (if (org-string-nw-p org-state) (concat " " org-state " ") " "))
  8816. (change-plist (list :type 'todo-state-change :from this :to org-state
  8817. :position startpos))
  8818. dolog now-done-p)
  8819. (when org-blocker-hook
  8820. (let (org-blocked-by-checkboxes block-reason)
  8821. (setq org-last-todo-state-is-todo
  8822. (not (member this org-done-keywords)))
  8823. (unless (save-excursion
  8824. (save-match-data
  8825. (org-with-wide-buffer
  8826. (run-hook-with-args-until-failure
  8827. 'org-blocker-hook change-plist))))
  8828. (setq block-reason (if org-blocked-by-checkboxes
  8829. "contained checkboxes"
  8830. (format "\"%s\"" org-block-entry-blocking)))
  8831. (if (called-interactively-p 'interactive)
  8832. (user-error "TODO state change from %s to %s blocked (by %s)"
  8833. this org-state block-reason)
  8834. ;; Fail silently.
  8835. (message "TODO state change from %s to %s blocked (by %s)"
  8836. this org-state block-reason)
  8837. (throw 'exit nil)))))
  8838. (store-match-data match-data)
  8839. (replace-match next t t)
  8840. (cond ((and org-state (equal this org-state))
  8841. (message "TODO state was already %s" (org-trim next)))
  8842. ((not (pos-visible-in-window-p hl-pos))
  8843. (message "TODO state changed to %s" (org-trim next))))
  8844. (unless head
  8845. (setq head (org-get-todo-sequence-head org-state)
  8846. ass (assoc head org-todo-kwd-alist)
  8847. interpret (nth 1 ass)
  8848. done-word (nth 3 ass)
  8849. final-done-word (nth 4 ass)))
  8850. (when (memq arg '(nextset previousset))
  8851. (message "Keyword-Set %d/%d: %s"
  8852. (- (length org-todo-sets) -1
  8853. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  8854. (length org-todo-sets)
  8855. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  8856. (setq org-last-todo-state-is-todo
  8857. (not (member org-state org-done-keywords)))
  8858. (setq now-done-p (and (member org-state org-done-keywords)
  8859. (not (member this org-done-keywords))))
  8860. (and logging (org-local-logging logging))
  8861. (when (or (and (or org-todo-log-states org-log-done)
  8862. (not (eq org-inhibit-logging t))
  8863. (not (memq arg '(nextset previousset))))
  8864. force-log)
  8865. ;; We need to look at recording a time and note.
  8866. (setq dolog (or (if force-log 'note)
  8867. (nth 1 (assoc org-state org-todo-log-states))
  8868. (nth 2 (assoc this org-todo-log-states))))
  8869. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  8870. (setq dolog 'time))
  8871. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  8872. (and org-state
  8873. (member org-state org-not-done-keywords)
  8874. (not (member this org-not-done-keywords))))
  8875. ;; This is now a todo state and was not one before
  8876. ;; If there was a CLOSED time stamp, get rid of it.
  8877. (org-add-planning-info nil nil 'closed))
  8878. (when (and now-done-p org-log-done)
  8879. ;; It is now done, and it was not done before.
  8880. (org-add-planning-info 'closed (org-current-effective-time))
  8881. (when (and (not dolog) (eq 'note org-log-done))
  8882. (org-add-log-setup 'done org-state this 'note)))
  8883. (when (and org-state dolog)
  8884. ;; This is a non-nil state, and we need to log it.
  8885. (org-add-log-setup 'state org-state this dolog)))
  8886. ;; Fixup tag positioning.
  8887. (org-todo-trigger-tag-changes org-state)
  8888. (when org-auto-align-tags (org-align-tags))
  8889. (when org-provide-todo-statistics
  8890. (org-update-parent-todo-statistics))
  8891. (when (bound-and-true-p org-clock-out-when-done)
  8892. (org-clock-out-if-current))
  8893. (run-hooks 'org-after-todo-state-change-hook)
  8894. (when (and arg (not (member org-state org-done-keywords)))
  8895. (setq head (org-get-todo-sequence-head org-state)))
  8896. (put-text-property (line-beginning-position)
  8897. (line-end-position) 'org-todo-head head)
  8898. ;; Do we need to trigger a repeat?
  8899. (when now-done-p
  8900. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  8901. ;; This is for the agenda, take a snapshot of the headline.
  8902. (save-match-data
  8903. (setq org-agenda-headline-snapshot-before-repeat
  8904. (org-get-heading))))
  8905. (org-auto-repeat-maybe org-state))
  8906. ;; Fixup cursor location if close to the keyword.
  8907. (when (and (outline-on-heading-p)
  8908. (not (bolp))
  8909. (save-excursion (beginning-of-line 1)
  8910. (looking-at org-todo-line-regexp))
  8911. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  8912. (goto-char (or (match-end 2) (match-end 1)))
  8913. (and (looking-at " ")
  8914. (not (looking-at " *:"))
  8915. (just-one-space)))
  8916. (when org-trigger-hook
  8917. (save-excursion
  8918. (run-hook-with-args 'org-trigger-hook change-plist)))
  8919. (when commentp (org-toggle-comment))))))))
  8920. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  8921. "Block turning an entry into a TODO, using the hierarchy.
  8922. This checks whether the current task should be blocked from state
  8923. changes. Such blocking occurs when:
  8924. 1. The task has children which are not all in a completed state.
  8925. 2. A task has a parent with the property :ORDERED:, and there
  8926. are siblings prior to the current task with incomplete
  8927. status.
  8928. 3. The parent of the task is blocked because it has siblings that should
  8929. be done first, or is child of a block grandparent TODO entry."
  8930. (if (not org-enforce-todo-dependencies)
  8931. t ; if locally turned off don't block
  8932. (catch 'dont-block
  8933. ;; If this is not a todo state change, or if this entry is already DONE,
  8934. ;; do not block
  8935. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  8936. (member (plist-get change-plist :from)
  8937. (cons 'done org-done-keywords))
  8938. (member (plist-get change-plist :to)
  8939. (cons 'todo org-not-done-keywords))
  8940. (not (plist-get change-plist :to)))
  8941. (throw 'dont-block t))
  8942. ;; If this task has children, and any are undone, it's blocked
  8943. (save-excursion
  8944. (org-back-to-heading t)
  8945. (let ((this-level (funcall outline-level)))
  8946. (outline-next-heading)
  8947. (let ((child-level (funcall outline-level)))
  8948. (while (and (not (eobp))
  8949. (> child-level this-level))
  8950. ;; this todo has children, check whether they are all
  8951. ;; completed
  8952. (when (and (not (org-entry-is-done-p))
  8953. (org-entry-is-todo-p))
  8954. (setq org-block-entry-blocking (org-get-heading))
  8955. (throw 'dont-block nil))
  8956. (outline-next-heading)
  8957. (setq child-level (funcall outline-level))))))
  8958. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  8959. ;; any previous siblings are undone, it's blocked
  8960. (save-excursion
  8961. (org-back-to-heading t)
  8962. (let* ((pos (point))
  8963. (parent-pos (and (org-up-heading-safe) (point)))
  8964. (case-fold-search nil))
  8965. (unless parent-pos (throw 'dont-block t)) ; no parent
  8966. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  8967. (forward-line 1)
  8968. (re-search-forward org-not-done-heading-regexp pos t))
  8969. (setq org-block-entry-blocking (match-string 0))
  8970. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  8971. ;; Search further up the hierarchy, to see if an ancestor is blocked
  8972. (while t
  8973. (goto-char parent-pos)
  8974. (unless (looking-at org-not-done-heading-regexp)
  8975. (throw 'dont-block t)) ; do not block, parent is not a TODO
  8976. (setq pos (point))
  8977. (setq parent-pos (and (org-up-heading-safe) (point)))
  8978. (unless parent-pos (throw 'dont-block t)) ; no parent
  8979. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  8980. (forward-line 1)
  8981. (re-search-forward org-not-done-heading-regexp pos t)
  8982. (setq org-block-entry-blocking (org-get-heading)))
  8983. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  8984. (defcustom org-track-ordered-property-with-tag nil
  8985. "Should the ORDERED property also be shown as a tag?
  8986. The ORDERED property decides if an entry should require subtasks to be
  8987. completed in sequence. Since a property is not very visible, setting
  8988. this option means that toggling the ORDERED property with the command
  8989. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  8990. not relevant for the behavior, but it makes things more visible.
  8991. Note that toggling the tag with tags commands will not change the property
  8992. and therefore not influence behavior!
  8993. This can be t, meaning the tag ORDERED should be used. It can also be a
  8994. string to select a different tag for this task."
  8995. :group 'org-todo
  8996. :type '(choice
  8997. (const :tag "No tracking" nil)
  8998. (const :tag "Track with ORDERED tag" t)
  8999. (string :tag "Use other tag")))
  9000. (defun org-toggle-ordered-property ()
  9001. "Toggle the ORDERED property of the current entry.
  9002. For better visibility, you can track the value of this property with a tag.
  9003. See variable `org-track-ordered-property-with-tag'."
  9004. (interactive)
  9005. (let* ((t1 org-track-ordered-property-with-tag)
  9006. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  9007. (save-excursion
  9008. (org-back-to-heading)
  9009. (if (org-entry-get nil "ORDERED")
  9010. (progn
  9011. (org-delete-property "ORDERED")
  9012. (and tag (org-toggle-tag tag 'off))
  9013. (message "Subtasks can be completed in arbitrary order"))
  9014. (org-entry-put nil "ORDERED" "t")
  9015. (and tag (org-toggle-tag tag 'on))
  9016. (message "Subtasks must be completed in sequence")))))
  9017. (defun org-block-todo-from-checkboxes (change-plist)
  9018. "Block turning an entry into a TODO, using checkboxes.
  9019. This checks whether the current task should be blocked from state
  9020. changes because there are unchecked boxes in this entry."
  9021. (if (not org-enforce-todo-checkbox-dependencies)
  9022. t ; if locally turned off don't block
  9023. (catch 'dont-block
  9024. ;; If this is not a todo state change, or if this entry is already DONE,
  9025. ;; do not block
  9026. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  9027. (member (plist-get change-plist :from)
  9028. (cons 'done org-done-keywords))
  9029. (member (plist-get change-plist :to)
  9030. (cons 'todo org-not-done-keywords))
  9031. (not (plist-get change-plist :to)))
  9032. (throw 'dont-block t))
  9033. ;; If this task has checkboxes that are not checked, it's blocked
  9034. (save-excursion
  9035. (org-back-to-heading t)
  9036. (let ((beg (point)) end)
  9037. (outline-next-heading)
  9038. (setq end (point))
  9039. (goto-char beg)
  9040. (when (org-list-search-forward
  9041. (concat (org-item-beginning-re)
  9042. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  9043. "\\[[- ]\\]")
  9044. end t)
  9045. (when (boundp 'org-blocked-by-checkboxes)
  9046. (setq org-blocked-by-checkboxes t))
  9047. (throw 'dont-block nil))))
  9048. t))) ; do not block
  9049. (defun org-entry-blocked-p ()
  9050. "Non-nil if entry at point is blocked."
  9051. (and (not (org-entry-get nil "NOBLOCKING"))
  9052. (member (org-entry-get nil "TODO") org-not-done-keywords)
  9053. (not (run-hook-with-args-until-failure
  9054. 'org-blocker-hook
  9055. (list :type 'todo-state-change
  9056. :position (point)
  9057. :from 'todo
  9058. :to 'done)))))
  9059. (defun org-update-statistics-cookies (all)
  9060. "Update the statistics cookie, either from TODO or from checkboxes.
  9061. This should be called with the cursor in a line with a statistics
  9062. cookie. When called with a \\[universal-argument] prefix, update
  9063. all statistics cookies in the buffer."
  9064. (interactive "P")
  9065. (if all
  9066. (progn
  9067. (org-update-checkbox-count 'all)
  9068. (org-map-region 'org-update-parent-todo-statistics
  9069. (point-min) (point-max)))
  9070. (if (not (org-at-heading-p))
  9071. (org-update-checkbox-count)
  9072. (let ((pos (point-marker))
  9073. end l1 l2)
  9074. (ignore-errors (org-back-to-heading t))
  9075. (if (not (org-at-heading-p))
  9076. (org-update-checkbox-count)
  9077. (setq l1 (org-outline-level))
  9078. (setq end
  9079. (save-excursion
  9080. (outline-next-heading)
  9081. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  9082. (point)))
  9083. (if (and (save-excursion
  9084. (re-search-forward
  9085. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  9086. (not (save-excursion
  9087. (re-search-forward
  9088. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  9089. (org-update-checkbox-count)
  9090. (if (and l2 (> l2 l1))
  9091. (progn
  9092. (goto-char end)
  9093. (org-update-parent-todo-statistics))
  9094. (goto-char pos)
  9095. (beginning-of-line 1)
  9096. (while (re-search-forward
  9097. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  9098. (line-end-position) t)
  9099. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  9100. (goto-char pos)
  9101. (move-marker pos nil)))))
  9102. (defvar org-entry-property-inherited-from) ;; defined below
  9103. (defun org-update-parent-todo-statistics ()
  9104. "Update any statistics cookie in the parent of the current headline.
  9105. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  9106. the entire subtree and this will travel up the hierarchy and update
  9107. statistics everywhere."
  9108. (let* ((prop (save-excursion
  9109. (org-up-heading-safe)
  9110. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  9111. (recursive (or (not org-hierarchical-todo-statistics)
  9112. (and prop (string-match "\\<recursive\\>" prop))))
  9113. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  9114. 0))
  9115. (first t)
  9116. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  9117. level ltoggle l1 new ndel
  9118. (cnt-all 0) (cnt-done 0) is-percent kwd
  9119. checkbox-beg cookie-present)
  9120. (catch 'exit
  9121. (save-excursion
  9122. (beginning-of-line 1)
  9123. (setq ltoggle (funcall outline-level))
  9124. ;; Three situations are to consider:
  9125. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  9126. ;; to the top-level ancestor on the headline;
  9127. ;; 2. If parent has "recursive" property, repeat up to the
  9128. ;; headline setting that property, taking inheritance into
  9129. ;; account;
  9130. ;; 3. Else, move up to direct parent and proceed only once.
  9131. (while (and (setq level (org-up-heading-safe))
  9132. (or recursive first)
  9133. (>= (point) lim))
  9134. (setq first nil cookie-present nil)
  9135. (unless (and level
  9136. (not (string-match
  9137. "\\<checkbox\\>"
  9138. (downcase (or (org-entry-get nil "COOKIE_DATA")
  9139. "")))))
  9140. (throw 'exit nil))
  9141. (while (re-search-forward box-re (line-end-position) t)
  9142. (setq cnt-all 0 cnt-done 0 cookie-present t)
  9143. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  9144. (save-match-data
  9145. (unless (outline-next-heading) (throw 'exit nil))
  9146. (while (and (looking-at org-complex-heading-regexp)
  9147. (> (setq l1 (length (match-string 1))) level))
  9148. (setq kwd (and (or recursive (= l1 ltoggle))
  9149. (match-string 2)))
  9150. (if (or (eq org-provide-todo-statistics 'all-headlines)
  9151. (and (eq org-provide-todo-statistics t)
  9152. (or (member kwd org-done-keywords)))
  9153. (and (listp org-provide-todo-statistics)
  9154. (stringp (car org-provide-todo-statistics))
  9155. (or (member kwd org-provide-todo-statistics)
  9156. (member kwd org-done-keywords)))
  9157. (and (listp org-provide-todo-statistics)
  9158. (listp (car org-provide-todo-statistics))
  9159. (or (member kwd (car org-provide-todo-statistics))
  9160. (and (member kwd org-done-keywords)
  9161. (member kwd (cadr org-provide-todo-statistics))))))
  9162. (setq cnt-all (1+ cnt-all))
  9163. (and (eq org-provide-todo-statistics t)
  9164. kwd
  9165. (setq cnt-all (1+ cnt-all))))
  9166. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  9167. (member kwd org-done-keywords))
  9168. (and (listp org-provide-todo-statistics)
  9169. (listp (car org-provide-todo-statistics))
  9170. (member kwd org-done-keywords)
  9171. (member kwd (cadr org-provide-todo-statistics)))
  9172. (and (listp org-provide-todo-statistics)
  9173. (stringp (car org-provide-todo-statistics))
  9174. (member kwd org-done-keywords)))
  9175. (setq cnt-done (1+ cnt-done)))
  9176. (outline-next-heading)))
  9177. (setq new
  9178. (if is-percent
  9179. (format "[%d%%]" (floor (* 100.0 cnt-done)
  9180. (max 1 cnt-all)))
  9181. (format "[%d/%d]" cnt-done cnt-all))
  9182. ndel (- (match-end 0) checkbox-beg))
  9183. (goto-char checkbox-beg)
  9184. (insert new)
  9185. (delete-region (point) (+ (point) ndel))
  9186. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  9187. (when cookie-present
  9188. (run-hook-with-args 'org-after-todo-statistics-hook
  9189. cnt-done (- cnt-all cnt-done))))))
  9190. (run-hooks 'org-todo-statistics-hook)))
  9191. (defvar org-after-todo-statistics-hook nil
  9192. "Hook that is called after a TODO statistics cookie has been updated.
  9193. Each function is called with two arguments: the number of not-done entries
  9194. and the number of done entries.
  9195. For example, the following function, when added to this hook, will switch
  9196. an entry to DONE when all children are done, and back to TODO when new
  9197. entries are set to a TODO status. Note that this hook is only called
  9198. when there is a statistics cookie in the headline!
  9199. (defun org-summary-todo (n-done n-not-done)
  9200. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  9201. (let (org-log-done org-log-states) ; turn off logging
  9202. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))")
  9203. (defvar org-todo-statistics-hook nil
  9204. "Hook that is run whenever Org thinks TODO statistics should be updated.
  9205. This hook runs even if there is no statistics cookie present, in which case
  9206. `org-after-todo-statistics-hook' would not run.")
  9207. (defun org-todo-trigger-tag-changes (state)
  9208. "Apply the changes defined in `org-todo-state-tags-triggers'."
  9209. (let ((l org-todo-state-tags-triggers)
  9210. changes)
  9211. (when (or (not state) (equal state ""))
  9212. (setq changes (append changes (cdr (assoc "" l)))))
  9213. (when (and (stringp state) (> (length state) 0))
  9214. (setq changes (append changes (cdr (assoc state l)))))
  9215. (when (member state org-not-done-keywords)
  9216. (setq changes (append changes (cdr (assq 'todo l)))))
  9217. (when (member state org-done-keywords)
  9218. (setq changes (append changes (cdr (assq 'done l)))))
  9219. (dolist (c changes)
  9220. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  9221. (defun org-local-logging (value)
  9222. "Get logging settings from a property VALUE."
  9223. ;; Directly set the variables, they are already local.
  9224. (setq org-log-done nil
  9225. org-log-repeat nil
  9226. org-todo-log-states nil)
  9227. (dolist (w (split-string value))
  9228. (let (a)
  9229. (cond
  9230. ((setq a (assoc w org-startup-options))
  9231. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  9232. (set (nth 1 a) (nth 2 a))))
  9233. ((setq a (org-extract-log-state-settings w))
  9234. (and (member (car a) org-todo-keywords-1)
  9235. (push a org-todo-log-states)))))))
  9236. (defun org-get-todo-sequence-head (kwd)
  9237. "Return the head of the TODO sequence to which KWD belongs.
  9238. If KWD is not set, check if there is a text property remembering the
  9239. right sequence."
  9240. (let (p)
  9241. (cond
  9242. ((not kwd)
  9243. (or (get-text-property (line-beginning-position) 'org-todo-head)
  9244. (progn
  9245. (setq p (next-single-property-change (line-beginning-position)
  9246. 'org-todo-head
  9247. nil (line-end-position)))
  9248. (get-text-property p 'org-todo-head))))
  9249. ((not (member kwd org-todo-keywords-1))
  9250. (car org-todo-keywords-1))
  9251. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  9252. (defun org-fast-todo-selection (&optional current-state)
  9253. "Fast TODO keyword selection with single keys.
  9254. Returns the new TODO keyword, or nil if no state change should occur.
  9255. When CURRENT-STATE is given and selection letters are not unique globally,
  9256. prefer a state in the current sequence over on in another sequence."
  9257. (let* ((fulltable org-todo-key-alist)
  9258. (head (org-get-todo-sequence-head current-state))
  9259. (done-keywords org-done-keywords) ;; needed for the faces.
  9260. (maxlen (apply 'max (mapcar
  9261. (lambda (x)
  9262. (if (stringp (car x)) (string-width (car x)) 0))
  9263. fulltable)))
  9264. (expert (equal org-use-fast-todo-selection 'expert))
  9265. (prompt "")
  9266. (fwidth (+ maxlen 3 1 3))
  9267. (ncol (/ (- (window-width) 4) fwidth))
  9268. tg cnt e c tbl subtable
  9269. groups ingroup in-current-sequence)
  9270. (save-excursion
  9271. (save-window-excursion
  9272. (if expert
  9273. (set-buffer (get-buffer-create " *Org todo*"))
  9274. (delete-other-windows)
  9275. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org todo*"))
  9276. (org-switch-to-buffer-other-window " *Org todo*"))
  9277. (erase-buffer)
  9278. (setq-local org-done-keywords done-keywords)
  9279. (setq tbl fulltable cnt 0)
  9280. (while (setq e (pop tbl))
  9281. (cond
  9282. ((equal e '(:startgroup))
  9283. (push '() groups) (setq ingroup t)
  9284. (unless (= cnt 0)
  9285. (setq cnt 0)
  9286. (insert "\n"))
  9287. (setq prompt (concat prompt "{"))
  9288. (insert "{ "))
  9289. ((equal e '(:endgroup))
  9290. (setq ingroup nil cnt 0 in-current-sequence nil)
  9291. (setq prompt (concat prompt "}"))
  9292. (insert "}\n"))
  9293. ((equal e '(:newline))
  9294. (unless (= cnt 0)
  9295. (setq cnt 0)
  9296. (insert "\n")
  9297. (setq e (car tbl))
  9298. (while (equal (car tbl) '(:newline))
  9299. (insert "\n")
  9300. (setq tbl (cdr tbl)))))
  9301. (t
  9302. (setq tg (car e) c (cdr e))
  9303. (if (equal tg head) (setq in-current-sequence t))
  9304. (when ingroup (push tg (car groups)))
  9305. (when in-current-sequence (push e subtable))
  9306. (setq tg (org-add-props tg nil 'face
  9307. (org-get-todo-face tg)))
  9308. (when (and (= cnt 0) (not ingroup)) (insert " "))
  9309. (setq prompt (concat prompt "[" (char-to-string c) "] " tg " "))
  9310. (insert "[" c "] " tg (make-string
  9311. (- fwidth 4 (length tg)) ?\ ))
  9312. (when (and (= (setq cnt (1+ cnt)) ncol)
  9313. ;; Avoid lines with just a closing delimiter.
  9314. (not (equal (car tbl) '(:endgroup))))
  9315. (insert "\n")
  9316. (when ingroup (insert " "))
  9317. (setq cnt 0)))))
  9318. (insert "\n")
  9319. (goto-char (point-min))
  9320. (unless expert (org-fit-window-to-buffer))
  9321. (message (concat "[a-z..]:Set [SPC]:clear"
  9322. (if expert (concat "\n" prompt) "")))
  9323. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  9324. (setq subtable (nreverse subtable))
  9325. (cond
  9326. ((or (= c ?\C-g)
  9327. (and (= c ?q) (not (rassoc c fulltable))))
  9328. (setq quit-flag t))
  9329. ((= c ?\ ) nil)
  9330. ((setq e (or (rassoc c subtable) (rassoc c fulltable))
  9331. tg (car e))
  9332. tg)
  9333. (t (setq quit-flag t)))))))
  9334. (defun org-entry-is-todo-p ()
  9335. (member (org-get-todo-state) org-not-done-keywords))
  9336. (defun org-entry-is-done-p ()
  9337. (member (org-get-todo-state) org-done-keywords))
  9338. (defun org-get-todo-state ()
  9339. "Return the TODO keyword of the current subtree."
  9340. (save-excursion
  9341. (org-back-to-heading t)
  9342. (and (let ((case-fold-search nil))
  9343. (looking-at org-todo-line-regexp))
  9344. (match-end 2)
  9345. (match-string 2))))
  9346. (defun org-at-date-range-p (&optional inactive-ok)
  9347. "Non-nil if point is inside a date range.
  9348. When optional argument INACTIVE-OK is non-nil, also consider
  9349. inactive time ranges.
  9350. When this function returns a non-nil value, match data is set
  9351. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  9352. on INACTIVE-OK."
  9353. (interactive)
  9354. (save-excursion
  9355. (catch 'exit
  9356. (let ((pos (point)))
  9357. (skip-chars-backward "^[<\r\n")
  9358. (skip-chars-backward "<[")
  9359. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  9360. (>= (match-end 0) pos)
  9361. (throw 'exit t))
  9362. (skip-chars-backward "^<[\r\n")
  9363. (skip-chars-backward "<[")
  9364. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  9365. (>= (match-end 0) pos)
  9366. (throw 'exit t)))
  9367. nil)))
  9368. (defun org-get-repeat (&optional timestamp)
  9369. "Check if there is a time-stamp with repeater in this entry.
  9370. Return the repeater, as a string, or nil. Also return nil when
  9371. this function is called before first heading.
  9372. When optional argument TIMESTAMP is a string, extract the
  9373. repeater from there instead."
  9374. (save-match-data
  9375. (cond
  9376. (timestamp
  9377. (and (string-match org-repeat-re timestamp)
  9378. (match-string-no-properties 1 timestamp)))
  9379. ((org-before-first-heading-p) nil)
  9380. (t
  9381. (save-excursion
  9382. (org-back-to-heading t)
  9383. (let ((end (org-entry-end-position)))
  9384. (catch :repeat
  9385. (while (re-search-forward org-repeat-re end t)
  9386. (when (save-match-data (org-at-timestamp-p 'agenda))
  9387. (throw :repeat (match-string-no-properties 1)))))))))))
  9388. (defvar org-last-changed-timestamp)
  9389. (defvar org-last-inserted-timestamp)
  9390. (defvar org-log-post-message)
  9391. (defvar org-log-note-purpose)
  9392. (defvar org-log-note-how nil)
  9393. (defvar org-log-note-extra)
  9394. (defvar org-log-setup nil)
  9395. (defun org-auto-repeat-maybe (done-word)
  9396. "Check if the current headline contains a repeated time-stamp.
  9397. If yes, set TODO state back to what it was and change the base date
  9398. of repeating deadline/scheduled time stamps to new date.
  9399. This function is run automatically after each state change to a DONE state."
  9400. (let* ((repeat (org-get-repeat))
  9401. (aa (assoc org-last-state org-todo-kwd-alist))
  9402. (interpret (nth 1 aa))
  9403. (head (nth 2 aa))
  9404. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  9405. (msg "Entry repeats: ")
  9406. (org-log-done nil)
  9407. (org-todo-log-states nil)
  9408. (end (copy-marker (org-entry-end-position))))
  9409. (when (and repeat (not (= 0 (string-to-number (substring repeat 1)))))
  9410. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  9411. (let ((to-state
  9412. (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  9413. (and (stringp org-todo-repeat-to-state)
  9414. org-todo-repeat-to-state)
  9415. (and org-todo-repeat-to-state org-last-state))))
  9416. (org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
  9417. to-state)
  9418. ((eq interpret 'type) org-last-state)
  9419. (head)
  9420. (t 'none))))
  9421. (org-back-to-heading t)
  9422. (org-add-planning-info nil nil 'closed)
  9423. ;; When `org-log-repeat' is non-nil or entry contains
  9424. ;; a clock, set LAST_REPEAT property.
  9425. (when (or org-log-repeat
  9426. (catch :clock
  9427. (save-excursion
  9428. (while (re-search-forward org-clock-line-re end t)
  9429. (when (org-at-clock-log-p) (throw :clock t))))))
  9430. (org-entry-put nil "LAST_REPEAT" (format-time-string
  9431. (org-time-stamp-format t t))))
  9432. (when org-log-repeat
  9433. (if org-log-setup
  9434. ;; We are already setup for some record.
  9435. (when (eq org-log-repeat 'note)
  9436. ;; Make sure we take a note, not only a time stamp.
  9437. (setq org-log-note-how 'note))
  9438. ;; Set up for taking a record.
  9439. (org-add-log-setup 'state
  9440. (or done-word (car org-done-keywords))
  9441. org-last-state
  9442. org-log-repeat)))
  9443. ;; Time-stamps without a repeater are usually skipped. However,
  9444. ;; a SCHEDULED time-stamp without one is removed, as they are no
  9445. ;; longer relevant.
  9446. (save-excursion
  9447. (let ((scheduled (org-entry-get (point) "SCHEDULED")))
  9448. (when (and scheduled (not (string-match-p org-repeat-re scheduled)))
  9449. (org-remove-timestamp-with-keyword org-scheduled-string))))
  9450. ;; Update every time-stamp with a repeater in the entry.
  9451. (let ((planning-re (regexp-opt
  9452. (list org-scheduled-string org-deadline-string))))
  9453. (while (re-search-forward org-repeat-re end t)
  9454. (let* ((ts (match-string 0))
  9455. (type (if (not (org-at-planning-p)) "Plain:"
  9456. (save-excursion
  9457. (re-search-backward
  9458. planning-re (line-beginning-position) t)
  9459. (match-string 0)))))
  9460. (when (and (org-at-timestamp-p 'agenda)
  9461. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  9462. (let ((n (string-to-number (match-string 2 ts)))
  9463. (what (match-string 3 ts)))
  9464. (when (equal what "w") (setq n (* n 7) what "d"))
  9465. (when (and (equal what "h")
  9466. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  9467. ts)))
  9468. (user-error
  9469. "Cannot repeat in %d hour(s) because no hour has been set"
  9470. n))
  9471. ;; Preparation, see if we need to modify the start
  9472. ;; date for the change.
  9473. (when (match-end 1)
  9474. (let ((time (save-match-data (org-time-string-to-time ts)))
  9475. (repeater-type (match-string 1 ts)))
  9476. (cond
  9477. ((equal "." repeater-type)
  9478. ;; Shift starting date to today, or now if
  9479. ;; repeater is by hours.
  9480. (if (equal what "h")
  9481. (org-timestamp-change
  9482. (floor (- (org-time-stamp-to-now ts t)) 60) 'minute)
  9483. (org-timestamp-change
  9484. (- (org-today) (time-to-days time)) 'day)))
  9485. ((equal "+" repeater-type)
  9486. (let ((nshiftmax 10)
  9487. (nshift 0))
  9488. (while (or (= nshift 0)
  9489. (not (org-time-less-p nil time)))
  9490. (when (= nshiftmax (cl-incf nshift))
  9491. (or (y-or-n-p
  9492. (format "%d repeater intervals were not \
  9493. enough to shift date past today. Continue? "
  9494. nshift))
  9495. (user-error "Abort")))
  9496. (org-timestamp-change n (cdr (assoc what whata)))
  9497. (org-in-regexp org-ts-regexp3)
  9498. (setq ts (match-string 1))
  9499. (setq time
  9500. (save-match-data
  9501. (org-time-string-to-time ts)))))
  9502. (org-timestamp-change (- n) (cdr (assoc what whata)))
  9503. ;; Rematch, so that we have everything in place
  9504. ;; for the real shift.
  9505. (org-in-regexp org-ts-regexp3)
  9506. (setq ts (match-string 1))
  9507. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  9508. ts)))))
  9509. (save-excursion
  9510. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  9511. (setq msg
  9512. (concat msg type " " org-last-changed-timestamp " ")))))))
  9513. (run-hooks 'org-todo-repeat-hook)
  9514. (setq org-log-post-message msg)
  9515. (message msg))))
  9516. (defun org-show-todo-tree (arg)
  9517. "Make a compact tree which shows all headlines marked with TODO.
  9518. The tree will show the lines where the regexp matches, and all higher
  9519. headlines above the match.
  9520. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  9521. With a numeric prefix N, construct a sparse tree for the Nth element
  9522. of `org-todo-keywords-1'."
  9523. (interactive "P")
  9524. (let ((case-fold-search nil)
  9525. (kwd-re
  9526. (cond ((null arg) (concat org-not-done-regexp "\\s-"))
  9527. ((equal arg '(4))
  9528. (let ((kwd
  9529. (completing-read "Keyword (or KWD1|KWD2|...): "
  9530. (mapcar #'list org-todo-keywords-1))))
  9531. (concat "\\("
  9532. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  9533. "\\)\\>")))
  9534. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  9535. (regexp-quote (nth (1- (prefix-numeric-value arg))
  9536. org-todo-keywords-1)))
  9537. (t (user-error "Invalid prefix argument: %s" arg)))))
  9538. (message "%d TODO entries found"
  9539. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  9540. (defun org--deadline-or-schedule (arg type time)
  9541. "Insert DEADLINE or SCHEDULE information in current entry.
  9542. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  9543. `org-schedule' for information about ARG and TIME arguments."
  9544. (let* ((deadline? (eq type 'deadline))
  9545. (keyword (if deadline? org-deadline-string org-scheduled-string))
  9546. (log (if deadline? org-log-redeadline org-log-reschedule))
  9547. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  9548. (old-date-time (and old-date (org-time-string-to-time old-date)))
  9549. ;; Save repeater cookie from either TIME or current scheduled
  9550. ;; time stamp. We are going to insert it back at the end of
  9551. ;; the process.
  9552. (repeater (or (and (org-string-nw-p time)
  9553. ;; We use `org-repeat-re' because we need
  9554. ;; to tell the difference between a real
  9555. ;; repeater and a time delta, e.g. "+2d".
  9556. (string-match org-repeat-re time)
  9557. (match-string 1 time))
  9558. (and (org-string-nw-p old-date)
  9559. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  9560. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  9561. old-date)
  9562. (match-string 1 old-date)))))
  9563. (pcase arg
  9564. (`(4)
  9565. (if (not old-date)
  9566. (message (if deadline? "Entry had no deadline to remove"
  9567. "Entry was not scheduled"))
  9568. (when (and old-date log)
  9569. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  9570. nil old-date log))
  9571. (org-remove-timestamp-with-keyword keyword)
  9572. (message (if deadline? "Entry no longer has a deadline."
  9573. "Entry is no longer scheduled."))))
  9574. (`(16)
  9575. (save-excursion
  9576. (org-back-to-heading t)
  9577. (let ((regexp (if deadline? org-deadline-time-regexp
  9578. org-scheduled-time-regexp)))
  9579. (if (not (re-search-forward regexp (line-end-position 2) t))
  9580. (user-error (if deadline? "No deadline information to update"
  9581. "No scheduled information to update"))
  9582. (let* ((rpl0 (match-string 1))
  9583. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  9584. (msg (if deadline? "Warn starting from" "Delay until")))
  9585. (replace-match
  9586. (concat keyword
  9587. " <" rpl
  9588. (format " -%dd"
  9589. (abs (- (time-to-days
  9590. (save-match-data
  9591. (org-read-date
  9592. nil t nil msg old-date-time)))
  9593. (time-to-days old-date-time))))
  9594. ">") t t))))))
  9595. (_
  9596. (org-add-planning-info type time 'closed)
  9597. (when (and old-date
  9598. log
  9599. (not (equal old-date org-last-inserted-timestamp)))
  9600. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  9601. org-last-inserted-timestamp
  9602. old-date
  9603. log))
  9604. (when repeater
  9605. (save-excursion
  9606. (org-back-to-heading t)
  9607. (when (re-search-forward
  9608. (concat keyword " " org-last-inserted-timestamp)
  9609. (line-end-position 2)
  9610. t)
  9611. (goto-char (1- (match-end 0)))
  9612. (insert " " repeater)
  9613. (setq org-last-inserted-timestamp
  9614. (concat (substring org-last-inserted-timestamp 0 -1)
  9615. " " repeater
  9616. (substring org-last-inserted-timestamp -1))))))
  9617. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  9618. org-last-inserted-timestamp)))))
  9619. (defun org-deadline (arg &optional time)
  9620. "Insert a \"DEADLINE:\" string with a timestamp to make a deadline.
  9621. When called interactively, this command pops up the Emacs calendar to let
  9622. the user select a date.
  9623. With one universal prefix argument, remove any deadline from the item.
  9624. With two universal prefix arguments, prompt for a warning delay.
  9625. With argument TIME, set the deadline at the corresponding date. TIME
  9626. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9627. (interactive "P")
  9628. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9629. (org-map-entries
  9630. (lambda () (org--deadline-or-schedule arg 'deadline time))
  9631. nil
  9632. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9633. 'region-start-level
  9634. 'region)
  9635. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9636. (org--deadline-or-schedule arg 'deadline time)))
  9637. (defun org-schedule (arg &optional time)
  9638. "Insert a \"SCHEDULED:\" string with a timestamp to schedule an item.
  9639. When called interactively, this command pops up the Emacs calendar to let
  9640. the user select a date.
  9641. With one universal prefix argument, remove any scheduling date from the item.
  9642. With two universal prefix arguments, prompt for a delay cookie.
  9643. With argument TIME, scheduled at the corresponding date. TIME can
  9644. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9645. (interactive "P")
  9646. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9647. (org-map-entries
  9648. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  9649. nil
  9650. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9651. 'region-start-level
  9652. 'region)
  9653. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9654. (org--deadline-or-schedule arg 'scheduled time)))
  9655. (defun org-get-scheduled-time (pom &optional inherit)
  9656. "Get the scheduled time as a time tuple, of a format suitable
  9657. for calling org-schedule with, or if there is no scheduling,
  9658. returns nil."
  9659. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  9660. (when time
  9661. (org-time-string-to-time time))))
  9662. (defun org-get-deadline-time (pom &optional inherit)
  9663. "Get the deadline as a time tuple, of a format suitable for
  9664. calling org-deadline with, or if there is no scheduling, returns
  9665. nil."
  9666. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  9667. (when time
  9668. (org-time-string-to-time time))))
  9669. (defun org-remove-timestamp-with-keyword (keyword)
  9670. "Remove all time stamps with KEYWORD in the current entry."
  9671. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  9672. beg)
  9673. (save-excursion
  9674. (org-back-to-heading t)
  9675. (setq beg (point))
  9676. (outline-next-heading)
  9677. (while (re-search-backward re beg t)
  9678. (replace-match "")
  9679. (if (and (string-match "\\S-" (buffer-substring (line-beginning-position) (point)))
  9680. (equal (char-before) ?\ ))
  9681. (backward-delete-char 1)
  9682. (when (string-match "^[ \t]*$" (buffer-substring
  9683. (line-beginning-position) (line-end-position)))
  9684. (delete-region (line-beginning-position)
  9685. (min (point-max) (1+ (line-end-position))))))))))
  9686. (defvar org-time-was-given) ; dynamically scoped parameter
  9687. (defvar org-end-time-was-given) ; dynamically scoped parameter
  9688. (defun org-at-planning-p ()
  9689. "Non-nil when point is on a planning info line."
  9690. ;; This is as accurate and faster than `org-element-at-point' since
  9691. ;; planning info location is fixed in the section.
  9692. (org-with-wide-buffer
  9693. (beginning-of-line)
  9694. (and (looking-at-p org-planning-line-re)
  9695. (eq (point)
  9696. (ignore-errors
  9697. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  9698. (org-back-to-heading t)
  9699. (org-with-limited-levels (org-back-to-heading t)))
  9700. (line-beginning-position 2))))))
  9701. (defun org-add-planning-info (what &optional time &rest remove)
  9702. "Insert new timestamp with keyword in the planning line.
  9703. WHAT indicates what kind of time stamp to add. It is a symbol
  9704. among `closed', `deadline', `scheduled' and nil. TIME indicates
  9705. the time to use. If none is given, the user is prompted for
  9706. a date. REMOVE indicates what kind of entries to remove. An old
  9707. WHAT entry will also be removed."
  9708. (let (org-time-was-given org-end-time-was-given default-time default-input)
  9709. (when (and (memq what '(scheduled deadline))
  9710. (or (not time)
  9711. (and (stringp time)
  9712. (string-match "^[-+]+[0-9]" time))))
  9713. ;; Try to get a default date/time from existing timestamp
  9714. (save-excursion
  9715. (org-back-to-heading t)
  9716. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  9717. (when (re-search-forward (if (eq what 'scheduled)
  9718. org-scheduled-time-regexp
  9719. org-deadline-time-regexp)
  9720. end t)
  9721. (setq ts (match-string 1)
  9722. default-time (org-time-string-to-time ts)
  9723. default-input (and ts (org-get-compact-tod ts)))))))
  9724. (when what
  9725. (setq time
  9726. (if (stringp time)
  9727. ;; This is a string (relative or absolute), set
  9728. ;; proper date.
  9729. (apply #'encode-time
  9730. (org-read-date-analyze
  9731. time default-time (decode-time default-time)))
  9732. ;; If necessary, get the time from the user
  9733. (or time (org-read-date nil 'to-time nil
  9734. (cl-case what
  9735. (deadline "DEADLINE")
  9736. (scheduled "SCHEDULED")
  9737. (otherwise nil))
  9738. default-time default-input)))))
  9739. (org-with-wide-buffer
  9740. (org-back-to-heading t)
  9741. (let ((planning? (save-excursion
  9742. (forward-line)
  9743. (looking-at-p org-planning-line-re))))
  9744. (cond
  9745. (planning?
  9746. (forward-line)
  9747. ;; Move to current indentation.
  9748. (skip-chars-forward " \t")
  9749. ;; Check if we have to remove something.
  9750. (dolist (type (if what (cons what remove) remove))
  9751. (save-excursion
  9752. (when (re-search-forward
  9753. (cl-case type
  9754. (closed org-closed-time-regexp)
  9755. (deadline org-deadline-time-regexp)
  9756. (scheduled org-scheduled-time-regexp)
  9757. (otherwise (error "Invalid planning type: %s" type)))
  9758. (line-end-position)
  9759. t)
  9760. ;; Delete until next keyword or end of line.
  9761. (delete-region
  9762. (match-beginning 0)
  9763. (if (re-search-forward org-keyword-time-not-clock-regexp
  9764. (line-end-position)
  9765. t)
  9766. (match-beginning 0)
  9767. (line-end-position))))))
  9768. ;; If there is nothing more to add and no more keyword is
  9769. ;; left, remove the line completely.
  9770. (if (and (looking-at-p "[ \t]*$") (not what))
  9771. (delete-region (line-end-position 0)
  9772. (line-end-position))
  9773. ;; If we removed last keyword, do not leave trailing white
  9774. ;; space at the end of line.
  9775. (let ((p (point)))
  9776. (save-excursion
  9777. (end-of-line)
  9778. (unless (= (skip-chars-backward " \t" p) 0)
  9779. (delete-region (point) (line-end-position)))))))
  9780. (what
  9781. (end-of-line)
  9782. (insert "\n")
  9783. (when org-adapt-indentation
  9784. (indent-to-column (1+ (org-outline-level)))))
  9785. (t nil)))
  9786. (when what
  9787. ;; Insert planning keyword.
  9788. (insert (cl-case what
  9789. (closed org-closed-string)
  9790. (deadline org-deadline-string)
  9791. (scheduled org-scheduled-string)
  9792. (otherwise (error "Invalid planning type: %s" what)))
  9793. " ")
  9794. ;; Insert associated timestamp.
  9795. (let ((ts (org-insert-time-stamp
  9796. time
  9797. (or org-time-was-given
  9798. (and (eq what 'closed) org-log-done-with-time))
  9799. (eq what 'closed)
  9800. nil nil (list org-end-time-was-given))))
  9801. (unless (eolp) (insert " "))
  9802. ts)))))
  9803. (defvar org-log-note-marker (make-marker)
  9804. "Marker pointing at the entry where the note is to be inserted.")
  9805. (defvar org-log-note-purpose nil)
  9806. (defvar org-log-note-state nil)
  9807. (defvar org-log-note-previous-state nil)
  9808. (defvar org-log-note-extra nil)
  9809. (defvar org-log-note-window-configuration nil)
  9810. (defvar org-log-note-return-to (make-marker))
  9811. (defvar org-log-note-effective-time nil
  9812. "Remembered current time.
  9813. So that dynamically scoped `org-extend-today-until' affects
  9814. timestamps in state change log.")
  9815. (defvar org-log-post-message nil
  9816. "Message to be displayed after a log note has been stored.
  9817. The auto-repeater uses this.")
  9818. (defun org-add-note ()
  9819. "Add a note to the current entry.
  9820. This is done in the same way as adding a state change note."
  9821. (interactive)
  9822. (org-add-log-setup 'note))
  9823. (defun org-log-beginning (&optional create)
  9824. "Return expected start of log notes in current entry.
  9825. When optional argument CREATE is non-nil, the function creates
  9826. a drawer to store notes, if necessary. Returned position ignores
  9827. narrowing."
  9828. (org-with-wide-buffer
  9829. (let ((drawer (org-log-into-drawer)))
  9830. (cond
  9831. (drawer
  9832. (org-end-of-meta-data)
  9833. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  9834. (end (if (org-at-heading-p) (point)
  9835. (save-excursion (outline-next-heading) (point))))
  9836. (case-fold-search t))
  9837. (catch 'exit
  9838. ;; Try to find existing drawer.
  9839. (while (re-search-forward regexp end t)
  9840. (let ((element (org-element-at-point)))
  9841. (when (eq (org-element-type element) 'drawer)
  9842. (let ((cend (org-element-property :contents-end element)))
  9843. (when (and (not org-log-states-order-reversed) cend)
  9844. (goto-char cend)))
  9845. (throw 'exit nil))))
  9846. ;; No drawer found. Create one, if permitted.
  9847. (when create
  9848. (unless (bolp) (insert "\n"))
  9849. (let ((beg (point)))
  9850. (insert ":" drawer ":\n:END:\n")
  9851. (org-indent-region beg (point))
  9852. (org-flag-region (line-end-position -1)
  9853. (1- (point)) t 'outline))
  9854. (end-of-line -1)))))
  9855. (t
  9856. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  9857. (skip-chars-forward " \t\n")
  9858. (beginning-of-line)
  9859. (unless org-log-states-order-reversed
  9860. (org-skip-over-state-notes)
  9861. (skip-chars-backward " \t\n")
  9862. (forward-line)))))
  9863. (if (bolp) (point) (line-beginning-position 2))))
  9864. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  9865. "Set up the post command hook to take a note.
  9866. If this is about to TODO state change, the new state is expected in STATE.
  9867. HOW is an indicator what kind of note should be created.
  9868. EXTRA is additional text that will be inserted into the notes buffer."
  9869. (move-marker org-log-note-marker (point))
  9870. (setq org-log-note-purpose purpose
  9871. org-log-note-state state
  9872. org-log-note-previous-state prev-state
  9873. org-log-note-how how
  9874. org-log-note-extra extra
  9875. org-log-note-effective-time (org-current-effective-time)
  9876. org-log-setup t)
  9877. (add-hook 'post-command-hook 'org-add-log-note 'append))
  9878. (defun org-skip-over-state-notes ()
  9879. "Skip past the list of State notes in an entry."
  9880. (when (ignore-errors (goto-char (org-in-item-p)))
  9881. (let* ((struct (org-list-struct))
  9882. (prevs (org-list-prevs-alist struct))
  9883. (regexp
  9884. (concat "[ \t]*- +"
  9885. (replace-regexp-in-string
  9886. " +" " +"
  9887. (org-replace-escapes
  9888. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  9889. `(("%d" . ,org-ts-regexp-inactive)
  9890. ("%D" . ,org-ts-regexp)
  9891. ("%s" . "\\(?:\"\\S-+\"\\)?")
  9892. ("%S" . "\\(?:\"\\S-+\"\\)?")
  9893. ("%t" . ,org-ts-regexp-inactive)
  9894. ("%T" . ,org-ts-regexp)
  9895. ("%u" . ".*?")
  9896. ("%U" . ".*?")))))))
  9897. (while (looking-at-p regexp)
  9898. (goto-char (or (org-list-get-next-item (point) struct prevs)
  9899. (org-list-get-item-end (point) struct)))))))
  9900. (defun org-add-log-note (&optional _purpose)
  9901. "Pop up a window for taking a note, and add this note later."
  9902. (remove-hook 'post-command-hook 'org-add-log-note)
  9903. (setq org-log-setup nil)
  9904. (setq org-log-note-window-configuration (current-window-configuration))
  9905. (delete-other-windows)
  9906. (move-marker org-log-note-return-to (point))
  9907. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  9908. (goto-char org-log-note-marker)
  9909. (org-switch-to-buffer-other-window "*Org Note*")
  9910. (erase-buffer)
  9911. (if (memq org-log-note-how '(time state))
  9912. (org-store-log-note)
  9913. (let ((org-inhibit-startup t)) (org-mode))
  9914. (insert (format "# Insert note for %s.
  9915. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  9916. (cl-case org-log-note-purpose
  9917. (clock-out "stopped clock")
  9918. (done "closed todo item")
  9919. (reschedule "rescheduling")
  9920. (delschedule "no longer scheduled")
  9921. (redeadline "changing deadline")
  9922. (deldeadline "removing deadline")
  9923. (refile "refiling")
  9924. (note "this entry")
  9925. (state
  9926. (format "state change from \"%s\" to \"%s\""
  9927. (or org-log-note-previous-state "")
  9928. (or org-log-note-state "")))
  9929. (t (error "This should not happen")))))
  9930. (when org-log-note-extra (insert org-log-note-extra))
  9931. (setq-local org-finish-function 'org-store-log-note)
  9932. (run-hooks 'org-log-buffer-setup-hook)))
  9933. (defvar org-note-abort nil) ; dynamically scoped
  9934. (defun org-store-log-note ()
  9935. "Finish taking a log note, and insert it to where it belongs."
  9936. (let ((txt (prog1 (buffer-string)
  9937. (kill-buffer)))
  9938. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  9939. lines)
  9940. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  9941. (setq txt (replace-match "" t t txt)))
  9942. (when (string-match "\\s-+\\'" txt)
  9943. (setq txt (replace-match "" t t txt)))
  9944. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  9945. (when (org-string-nw-p note)
  9946. (setq note
  9947. (org-replace-escapes
  9948. note
  9949. (list (cons "%u" (user-login-name))
  9950. (cons "%U" user-full-name)
  9951. (cons "%t" (format-time-string
  9952. (org-time-stamp-format 'long 'inactive)
  9953. org-log-note-effective-time))
  9954. (cons "%T" (format-time-string
  9955. (org-time-stamp-format 'long nil)
  9956. org-log-note-effective-time))
  9957. (cons "%d" (format-time-string
  9958. (org-time-stamp-format nil 'inactive)
  9959. org-log-note-effective-time))
  9960. (cons "%D" (format-time-string
  9961. (org-time-stamp-format nil nil)
  9962. org-log-note-effective-time))
  9963. (cons "%s" (cond
  9964. ((not org-log-note-state) "")
  9965. ((string-match-p org-ts-regexp
  9966. org-log-note-state)
  9967. (format "\"[%s]\""
  9968. (substring org-log-note-state 1 -1)))
  9969. (t (format "\"%s\"" org-log-note-state))))
  9970. (cons "%S"
  9971. (cond
  9972. ((not org-log-note-previous-state) "")
  9973. ((string-match-p org-ts-regexp
  9974. org-log-note-previous-state)
  9975. (format "\"[%s]\""
  9976. (substring
  9977. org-log-note-previous-state 1 -1)))
  9978. (t (format "\"%s\""
  9979. org-log-note-previous-state)))))))
  9980. (when lines (setq note (concat note " \\\\")))
  9981. (push note lines))
  9982. (when (and lines (not org-note-abort))
  9983. (with-current-buffer (marker-buffer org-log-note-marker)
  9984. (org-with-wide-buffer
  9985. ;; Find location for the new note.
  9986. (goto-char org-log-note-marker)
  9987. (set-marker org-log-note-marker nil)
  9988. ;; Note associated to a clock is to be located right after
  9989. ;; the clock. Do not move point.
  9990. (unless (eq org-log-note-purpose 'clock-out)
  9991. (goto-char (org-log-beginning t)))
  9992. ;; Make sure point is at the beginning of an empty line.
  9993. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  9994. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  9995. ;; In an existing list, add a new item at the top level.
  9996. ;; Otherwise, indent line like a regular one.
  9997. (let ((itemp (org-in-item-p)))
  9998. (if itemp
  9999. (indent-line-to
  10000. (let ((struct (save-excursion
  10001. (goto-char itemp) (org-list-struct))))
  10002. (org-list-get-ind (org-list-get-top-point struct) struct)))
  10003. (org-indent-line)))
  10004. (insert (org-list-bullet-string "-") (pop lines))
  10005. (let ((ind (org-list-item-body-column (line-beginning-position))))
  10006. (dolist (line lines)
  10007. (insert "\n")
  10008. (indent-line-to ind)
  10009. (insert line)))
  10010. (message "Note stored")
  10011. (org-back-to-heading t)))))
  10012. ;; Don't add undo information when called from `org-agenda-todo'.
  10013. (set-window-configuration org-log-note-window-configuration)
  10014. (with-current-buffer (marker-buffer org-log-note-return-to)
  10015. (goto-char org-log-note-return-to))
  10016. (move-marker org-log-note-return-to nil)
  10017. (when org-log-post-message (message "%s" org-log-post-message)))
  10018. (defun org-remove-empty-drawer-at (pos)
  10019. "Remove an empty drawer at position POS.
  10020. POS may also be a marker."
  10021. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  10022. (org-with-wide-buffer
  10023. (goto-char pos)
  10024. (let ((drawer (org-element-at-point)))
  10025. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  10026. (not (org-element-property :contents-begin drawer)))
  10027. (delete-region (org-element-property :begin drawer)
  10028. (progn (goto-char (org-element-property :end drawer))
  10029. (skip-chars-backward " \r\t\n")
  10030. (forward-line)
  10031. (point))))))))
  10032. (defvar org-ts-type nil)
  10033. (defun org-sparse-tree (&optional arg type)
  10034. "Create a sparse tree, prompt for the details.
  10035. This command can create sparse trees. You first need to select the type
  10036. of match used to create the tree:
  10037. t Show all TODO entries.
  10038. T Show entries with a specific TODO keyword.
  10039. m Show entries selected by a tags/property match.
  10040. p Enter a property name and its value (both with completion on existing
  10041. names/values) and show entries with that property.
  10042. r Show entries matching a regular expression (`/' can be used as well).
  10043. b Show deadlines and scheduled items before a date.
  10044. a Show deadlines and scheduled items after a date.
  10045. d Show deadlines due within `org-deadline-warning-days'.
  10046. D Show deadlines and scheduled items between a date range."
  10047. (interactive "P")
  10048. (setq type (or type org-sparse-tree-default-date-type))
  10049. (setq org-ts-type type)
  10050. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  10051. [d]eadlines [b]efore-date [a]fter-date [D]ates range
  10052. [c]ycle through date types: %s"
  10053. (cl-case type
  10054. (all "all timestamps")
  10055. (scheduled "only scheduled")
  10056. (deadline "only deadline")
  10057. (active "only active timestamps")
  10058. (inactive "only inactive timestamps")
  10059. (closed "with a closed time-stamp")
  10060. (otherwise "scheduled/deadline")))
  10061. (let ((answer (read-char-exclusive)))
  10062. (cl-case answer
  10063. (?c
  10064. (org-sparse-tree
  10065. arg
  10066. (cadr
  10067. (memq type '(nil all scheduled deadline active inactive closed)))))
  10068. (?d (call-interactively 'org-check-deadlines))
  10069. (?b (call-interactively 'org-check-before-date))
  10070. (?a (call-interactively 'org-check-after-date))
  10071. (?D (call-interactively 'org-check-dates-range))
  10072. (?t (call-interactively 'org-show-todo-tree))
  10073. (?T (org-show-todo-tree '(4)))
  10074. (?m (call-interactively 'org-match-sparse-tree))
  10075. ((?p ?P)
  10076. (let* ((kwd (completing-read
  10077. "Property: " (mapcar #'list (org-buffer-property-keys))))
  10078. (value (completing-read
  10079. "Value: " (mapcar #'list (org-property-values kwd)))))
  10080. (unless (string-match "\\`{.*}\\'" value)
  10081. (setq value (concat "\"" value "\"")))
  10082. (org-match-sparse-tree arg (concat kwd "=" value))))
  10083. ((?r ?R ?/) (call-interactively 'org-occur))
  10084. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  10085. (defvar-local org-occur-highlights nil
  10086. "List of overlays used for occur matches.")
  10087. (defvar-local org-occur-parameters nil
  10088. "Parameters of the active org-occur calls.
  10089. This is a list, each call to org-occur pushes as cons cell,
  10090. containing the regular expression and the callback, onto the list.
  10091. The list can contain several entries if `org-occur' has been called
  10092. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  10093. will only contain one set of parameters. When the highlights are
  10094. removed (for example with `C-c C-c', or with the next edit (depending
  10095. on `org-remove-highlights-with-change'), this variable is emptied
  10096. as well.")
  10097. (defun org-occur (regexp &optional keep-previous callback)
  10098. "Make a compact tree showing all matches of REGEXP.
  10099. The tree will show the lines where the regexp matches, and any other context
  10100. defined in `org-show-context-detail', which see.
  10101. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  10102. done by a previous call to `org-occur' will be kept, to allow stacking of
  10103. calls to this command.
  10104. Optional argument CALLBACK can be a function of no argument. In this case,
  10105. it is called with point at the end of the match, match data being set
  10106. accordingly. Current match is shown only if the return value is non-nil.
  10107. The function must neither move point nor alter narrowing."
  10108. (interactive "sRegexp: \nP")
  10109. (when (equal regexp "")
  10110. (user-error "Regexp cannot be empty"))
  10111. (unless keep-previous
  10112. (org-remove-occur-highlights nil nil t))
  10113. (push (cons regexp callback) org-occur-parameters)
  10114. (let ((cnt 0))
  10115. (save-excursion
  10116. (goto-char (point-min))
  10117. (when (or (not keep-previous) ; do not want to keep
  10118. (not org-occur-highlights)) ; no previous matches
  10119. ;; hide everything
  10120. (org-overview))
  10121. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  10122. (isearch-no-upper-case-p regexp t)
  10123. org-occur-case-fold-search)))
  10124. (while (re-search-forward regexp nil t)
  10125. (when (or (not callback)
  10126. (save-match-data (funcall callback)))
  10127. (setq cnt (1+ cnt))
  10128. (when org-highlight-sparse-tree-matches
  10129. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  10130. (org-show-context 'occur-tree)))))
  10131. (when org-remove-highlights-with-change
  10132. (add-hook 'before-change-functions 'org-remove-occur-highlights
  10133. nil 'local))
  10134. (unless org-sparse-tree-open-archived-trees
  10135. (org-hide-archived-subtrees (point-min) (point-max)))
  10136. (run-hooks 'org-occur-hook)
  10137. (when (called-interactively-p 'interactive)
  10138. (message "%d match(es) for regexp %s" cnt regexp))
  10139. cnt))
  10140. (defun org-occur-next-match (&optional n _reset)
  10141. "Function for `next-error-function' to find sparse tree matches.
  10142. N is the number of matches to move, when negative move backwards.
  10143. This function always goes back to the starting point when no
  10144. match is found."
  10145. (let* ((limit (if (< n 0) (point-min) (point-max)))
  10146. (search-func (if (< n 0)
  10147. 'previous-single-char-property-change
  10148. 'next-single-char-property-change))
  10149. (n (abs n))
  10150. (pos (point))
  10151. p1)
  10152. (catch 'exit
  10153. (while (setq p1 (funcall search-func (point) 'org-type))
  10154. (when (equal p1 limit)
  10155. (goto-char pos)
  10156. (user-error "No more matches"))
  10157. (when (equal (get-char-property p1 'org-type) 'org-occur)
  10158. (setq n (1- n))
  10159. (when (= n 0)
  10160. (goto-char p1)
  10161. (throw 'exit (point))))
  10162. (goto-char p1))
  10163. (goto-char p1)
  10164. (user-error "No more matches"))))
  10165. (defun org-highlight-new-match (beg end)
  10166. "Highlight from BEG to END and mark the highlight is an occur headline."
  10167. (let ((ov (make-overlay beg end)))
  10168. (overlay-put ov 'face 'secondary-selection)
  10169. (overlay-put ov 'org-type 'org-occur)
  10170. (push ov org-occur-highlights)))
  10171. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  10172. "Remove the occur highlights from the buffer.
  10173. BEG and END are ignored. If NOREMOVE is nil, remove this function
  10174. from the `before-change-functions' in the current buffer."
  10175. (interactive)
  10176. (unless org-inhibit-highlight-removal
  10177. (mapc #'delete-overlay org-occur-highlights)
  10178. (setq org-occur-highlights nil)
  10179. (setq org-occur-parameters nil)
  10180. (unless noremove
  10181. (remove-hook 'before-change-functions
  10182. 'org-remove-occur-highlights 'local))))
  10183. ;;;; Priorities
  10184. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]+\\)\\] ?\\)"
  10185. "Regular expression matching the priority indicator.
  10186. A priority indicator can be e.g. [#A] or [#1].
  10187. This regular expression matches these groups:
  10188. 0 : the whole match, e.g. \"TODO [#A] Hack\"
  10189. 1 : the priority cookie, e.g. \"[#A]\"
  10190. 2 : the value of the priority cookie, e.g. \"A\".")
  10191. (defun org-priority-up ()
  10192. "Increase the priority of the current item."
  10193. (interactive)
  10194. (org-priority 'up))
  10195. (defun org-priority-down ()
  10196. "Decrease the priority of the current item."
  10197. (interactive)
  10198. (org-priority 'down))
  10199. (defun org-priority (&optional action show)
  10200. "Change the priority of an item.
  10201. When called interactively with a `\\[universal-argument]' prefix,
  10202. show the priority in the minibuffer instead of changing it.
  10203. When called programmatically, ACTION can be `set', `up', `down',
  10204. or a character."
  10205. (interactive "P")
  10206. (when show
  10207. ;; Deprecation warning inserted for Org 9.2; once enough time has
  10208. ;; passed the SHOW argument should be removed.
  10209. (warn "`org-priority' called with deprecated SHOW argument"))
  10210. (if (equal action '(4))
  10211. (org-priority-show)
  10212. (unless org-priority-enable-commands
  10213. (user-error "Priority commands are disabled"))
  10214. (setq action (or action 'set))
  10215. (let ((nump (< org-priority-lowest 65))
  10216. current new news have remove)
  10217. (save-excursion
  10218. (org-back-to-heading t)
  10219. (when (looking-at org-priority-regexp)
  10220. (let ((ms (match-string 2)))
  10221. (setq current (org-priority-to-value ms)
  10222. have t)))
  10223. (cond
  10224. ((eq action 'remove)
  10225. (setq remove t new ?\ ))
  10226. ((or (eq action 'set)
  10227. (integerp action))
  10228. (if (not (eq action 'set))
  10229. (setq new action)
  10230. (setq
  10231. new
  10232. (if nump
  10233. (let* ((msg (format "Priority %s-%s, SPC to remove: "
  10234. (number-to-string org-priority-highest)
  10235. (number-to-string org-priority-lowest)))
  10236. (s (if (< 9 org-priority-lowest)
  10237. (read-string msg)
  10238. (message msg)
  10239. (char-to-string (read-char-exclusive)))))
  10240. (if (equal s " ") ?\s (string-to-number s)))
  10241. (progn (message "Priority %c-%c, SPC to remove: "
  10242. org-priority-highest org-priority-lowest)
  10243. (save-match-data
  10244. (setq new (read-char-exclusive)))))))
  10245. (when (and (= (upcase org-priority-highest) org-priority-highest)
  10246. (= (upcase org-priority-lowest) org-priority-lowest))
  10247. (setq new (upcase new)))
  10248. (cond ((equal new ?\s) (setq remove t))
  10249. ((or (< (upcase new) org-priority-highest) (> (upcase new) org-priority-lowest))
  10250. (user-error
  10251. (if nump
  10252. "Priority must be between `%s' and `%s'"
  10253. "Priority must be between `%c' and `%c'")
  10254. org-priority-highest org-priority-lowest))))
  10255. ((eq action 'up)
  10256. (setq new (if have
  10257. (1- current) ; normal cycling
  10258. ;; last priority was empty
  10259. (if (eq last-command this-command)
  10260. org-priority-lowest ; wrap around empty to lowest
  10261. ;; default
  10262. (if org-priority-start-cycle-with-default
  10263. org-priority-default
  10264. (1- org-priority-default))))))
  10265. ((eq action 'down)
  10266. (setq new (if have
  10267. (1+ current) ; normal cycling
  10268. ;; last priority was empty
  10269. (if (eq last-command this-command)
  10270. org-priority-highest ; wrap around empty to highest
  10271. ;; default
  10272. (if org-priority-start-cycle-with-default
  10273. org-priority-default
  10274. (1+ org-priority-default))))))
  10275. (t (user-error "Invalid action")))
  10276. (when (or (< (upcase new) org-priority-highest)
  10277. (> (upcase new) org-priority-lowest))
  10278. (if (and (memq action '(up down))
  10279. (not have) (not (eq last-command this-command)))
  10280. ;; `new' is from default priority
  10281. (error
  10282. "The default can not be set, see `org-priority-default' why")
  10283. ;; normal cycling: `new' is beyond highest/lowest priority
  10284. ;; and is wrapped around to the empty priority
  10285. (setq remove t)))
  10286. ;; Numerical priorities are limited to 64, beyond that number,
  10287. ;; assume the priority cookie is a character.
  10288. (setq news (if (> new 64) (format "%c" new) (format "%s" new)))
  10289. (if have
  10290. (if remove
  10291. (replace-match "" t t nil 1)
  10292. (replace-match news t t nil 2))
  10293. (if remove
  10294. (user-error "No priority cookie found in line")
  10295. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  10296. (if (match-end 2)
  10297. (progn
  10298. (goto-char (match-end 2))
  10299. (insert " [#" news "]"))
  10300. (goto-char (match-beginning 3))
  10301. (insert "[#" news "] "))))
  10302. (org-align-tags))
  10303. (if remove
  10304. (message "Priority removed")
  10305. (message "Priority of current item set to %s" news)))))
  10306. (defalias 'org-show-priority 'org-priority-show)
  10307. (defun org-priority-show ()
  10308. "Show the priority of the current item.
  10309. This priority is composed of the main priority given with the [#A] cookies,
  10310. and by additional input from the age of a schedules or deadline entry."
  10311. (interactive)
  10312. (let ((pri (if (eq major-mode 'org-agenda-mode)
  10313. (org-get-at-bol 'priority)
  10314. (save-excursion
  10315. (save-match-data
  10316. (beginning-of-line)
  10317. (and (looking-at org-heading-regexp)
  10318. (org-get-priority (match-string 0))))))))
  10319. (message "Priority is %d" (if pri pri -1000))))
  10320. (defun org-get-priority (s)
  10321. "Find priority cookie and return priority.
  10322. S is a string against which you can match `org-priority-regexp'.
  10323. If `org-priority-get-priority-function' is set to a custom
  10324. function, use it. Otherwise process S and output the priority
  10325. value, an integer."
  10326. (save-match-data
  10327. (if (functionp org-priority-get-priority-function)
  10328. (funcall org-priority-get-priority-function s)
  10329. (if (not (string-match org-priority-regexp s))
  10330. (* 1000 (- org-priority-lowest org-priority-default))
  10331. (* 1000 (- org-priority-lowest
  10332. (org-priority-to-value (match-string 2 s))))))))
  10333. ;;;; Tags
  10334. (defvar org-agenda-archives-mode)
  10335. (defvar org-map-continue-from nil
  10336. "Position from where mapping should continue.
  10337. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  10338. (defvar org-scanner-tags nil
  10339. "The current tag list while the tags scanner is running.")
  10340. (defvar org-trust-scanner-tags nil
  10341. "Should `org-get-tags' use the tags for the scanner.
  10342. This is for internal dynamical scoping only.
  10343. When this is non-nil, the function `org-get-tags' will return the value
  10344. of `org-scanner-tags' instead of building the list by itself. This
  10345. can lead to large speed-ups when the tags scanner is used in a file with
  10346. many entries, and when the list of tags is retrieved, for example to
  10347. obtain a list of properties. Building the tags list for each entry in such
  10348. a file becomes an N^2 operation - but with this variable set, it scales
  10349. as N.")
  10350. (defvar org--matcher-tags-todo-only nil)
  10351. (defun org-scan-tags (action matcher todo-only &optional start-level)
  10352. "Scan headline tags with inheritance and produce output ACTION.
  10353. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  10354. or `agenda' to produce an entry list for an agenda view. It can also be
  10355. a Lisp form or a function that should be called at each matched headline, in
  10356. this case the return value is a list of all return values from these calls.
  10357. MATCHER is a function accepting three arguments, returning
  10358. a non-nil value whenever a given set of tags qualifies a headline
  10359. for inclusion. See `org-make-tags-matcher' for more information.
  10360. As a special case, it can also be set to t (respectively nil) in
  10361. order to match all (respectively none) headline.
  10362. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  10363. included in the output.
  10364. START-LEVEL can be a string with asterisks, reducing the scope to
  10365. headlines matching this string."
  10366. (require 'org-agenda)
  10367. (let* ((re (concat "^"
  10368. (if start-level
  10369. ;; Get the correct level to match
  10370. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  10371. org-outline-regexp)
  10372. " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
  10373. " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
  10374. (props (list 'face 'default
  10375. 'done-face 'org-agenda-done
  10376. 'undone-face 'default
  10377. 'mouse-face 'highlight
  10378. 'org-not-done-regexp org-not-done-regexp
  10379. 'org-todo-regexp org-todo-regexp
  10380. 'org-complex-heading-regexp org-complex-heading-regexp
  10381. 'help-echo
  10382. (format "mouse-2 or RET jump to Org file %S"
  10383. (abbreviate-file-name
  10384. (or (buffer-file-name (buffer-base-buffer))
  10385. (buffer-name (buffer-base-buffer)))))))
  10386. (org-map-continue-from nil)
  10387. lspos tags tags-list
  10388. (tags-alist (list (cons 0 org-file-tags)))
  10389. (llast 0) rtn rtn1 level category i txt
  10390. todo marker entry priority
  10391. ts-date ts-date-type ts-date-pair)
  10392. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  10393. (setq action (list 'lambda nil action)))
  10394. (save-excursion
  10395. (goto-char (point-min))
  10396. (when (eq action 'sparse-tree)
  10397. (org-overview)
  10398. (org-remove-occur-highlights))
  10399. (while (let (case-fold-search)
  10400. (re-search-forward re nil t))
  10401. (setq org-map-continue-from nil)
  10402. (catch :skip
  10403. ;; Ignore closing parts of inline tasks.
  10404. (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
  10405. (throw :skip t))
  10406. (setq todo (and (match-end 1) (match-string-no-properties 1)))
  10407. (setq tags (and (match-end 4) (org-trim (match-string-no-properties 4))))
  10408. (goto-char (setq lspos (match-beginning 0)))
  10409. (setq level (org-reduced-level (org-outline-level))
  10410. category (org-get-category))
  10411. (when (eq action 'agenda)
  10412. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  10413. ts-date (car ts-date-pair)
  10414. ts-date-type (cdr ts-date-pair)))
  10415. (setq i llast llast level)
  10416. ;; remove tag lists from same and sublevels
  10417. (while (>= i level)
  10418. (when (setq entry (assoc i tags-alist))
  10419. (setq tags-alist (delete entry tags-alist)))
  10420. (setq i (1- i)))
  10421. ;; add the next tags
  10422. (when tags
  10423. (setq tags (org-split-string tags ":")
  10424. tags-alist
  10425. (cons (cons level tags) tags-alist)))
  10426. ;; compile tags for current headline
  10427. (setq tags-list
  10428. (if org-use-tag-inheritance
  10429. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  10430. tags)
  10431. org-scanner-tags tags-list)
  10432. (when org-use-tag-inheritance
  10433. (setcdr (car tags-alist)
  10434. (mapcar (lambda (x)
  10435. (setq x (copy-sequence x))
  10436. (org-add-prop-inherited x))
  10437. (cdar tags-alist))))
  10438. (when (and tags org-use-tag-inheritance
  10439. (or (not (eq t org-use-tag-inheritance))
  10440. org-tags-exclude-from-inheritance))
  10441. ;; Selective inheritance, remove uninherited ones.
  10442. (setcdr (car tags-alist)
  10443. (org-remove-uninherited-tags (cdar tags-alist))))
  10444. (when (and
  10445. ;; eval matcher only when the todo condition is OK
  10446. (and (or (not todo-only) (member todo org-todo-keywords-1))
  10447. (if (functionp matcher)
  10448. (let ((case-fold-search t) (org-trust-scanner-tags t))
  10449. (funcall matcher todo tags-list level))
  10450. matcher))
  10451. ;; Call the skipper, but return t if it does not
  10452. ;; skip, so that the `and' form continues evaluating.
  10453. (progn
  10454. (unless (eq action 'sparse-tree) (org-agenda-skip))
  10455. t)
  10456. ;; Check if timestamps are deselecting this entry
  10457. (or (not todo-only)
  10458. (and (member todo org-todo-keywords-1)
  10459. (or (not org-agenda-tags-todo-honor-ignore-options)
  10460. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  10461. ;; select this headline
  10462. (cond
  10463. ((eq action 'sparse-tree)
  10464. (and org-highlight-sparse-tree-matches
  10465. (org-get-heading) (match-end 0)
  10466. (org-highlight-new-match
  10467. (match-beginning 1) (match-end 1)))
  10468. (org-show-context 'tags-tree))
  10469. ((eq action 'agenda)
  10470. (setq txt (org-agenda-format-item
  10471. ""
  10472. (concat
  10473. (if (eq org-tags-match-list-sublevels 'indented)
  10474. (make-string (1- level) ?.) "")
  10475. (org-get-heading))
  10476. (make-string level ?\s)
  10477. category
  10478. tags-list)
  10479. priority (org-get-priority txt))
  10480. (goto-char lspos)
  10481. (setq marker (org-agenda-new-marker))
  10482. (org-add-props txt props
  10483. 'org-marker marker 'org-hd-marker marker 'org-category category
  10484. 'todo-state todo
  10485. 'ts-date ts-date
  10486. 'priority priority
  10487. 'type (concat "tagsmatch" ts-date-type))
  10488. (push txt rtn))
  10489. ((functionp action)
  10490. (setq org-map-continue-from nil)
  10491. (save-excursion
  10492. (setq rtn1 (funcall action))
  10493. (push rtn1 rtn)))
  10494. (t (user-error "Invalid action")))
  10495. ;; if we are to skip sublevels, jump to end of subtree
  10496. (unless org-tags-match-list-sublevels
  10497. (org-end-of-subtree t)
  10498. (backward-char 1))))
  10499. ;; Get the correct position from where to continue
  10500. (if org-map-continue-from
  10501. (goto-char org-map-continue-from)
  10502. (and (= (point) lspos) (end-of-line 1)))))
  10503. (when (and (eq action 'sparse-tree)
  10504. (not org-sparse-tree-open-archived-trees))
  10505. (org-hide-archived-subtrees (point-min) (point-max)))
  10506. (nreverse rtn)))
  10507. (defun org-remove-uninherited-tags (tags)
  10508. "Remove all tags that are not inherited from the list TAGS."
  10509. (cond
  10510. ((eq org-use-tag-inheritance t)
  10511. (if org-tags-exclude-from-inheritance
  10512. (org-delete-all org-tags-exclude-from-inheritance tags)
  10513. tags))
  10514. ((not org-use-tag-inheritance) nil)
  10515. ((stringp org-use-tag-inheritance)
  10516. (delq nil (mapcar
  10517. (lambda (x)
  10518. (if (and (string-match org-use-tag-inheritance x)
  10519. (not (member x org-tags-exclude-from-inheritance)))
  10520. x nil))
  10521. tags)))
  10522. ((listp org-use-tag-inheritance)
  10523. (delq nil (mapcar
  10524. (lambda (x)
  10525. (if (member x org-use-tag-inheritance) x nil))
  10526. tags)))))
  10527. (defun org-match-sparse-tree (&optional todo-only match)
  10528. "Create a sparse tree according to tags string MATCH.
  10529. MATCH is a string with match syntax. It can contain a selection
  10530. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  10531. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  10532. those. See the manual for details.
  10533. If optional argument TODO-ONLY is non-nil, only select lines that
  10534. are also TODO tasks."
  10535. (interactive "P")
  10536. (org-agenda-prepare-buffers (list (current-buffer)))
  10537. (let ((org--matcher-tags-todo-only todo-only))
  10538. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match t))
  10539. org--matcher-tags-todo-only)))
  10540. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  10541. (defvar org-cached-props nil)
  10542. (defun org-cached-entry-get (pom property)
  10543. (if (or (eq t org-use-property-inheritance)
  10544. (and (stringp org-use-property-inheritance)
  10545. (let ((case-fold-search t))
  10546. (string-match-p org-use-property-inheritance property)))
  10547. (and (listp org-use-property-inheritance)
  10548. (member-ignore-case property org-use-property-inheritance)))
  10549. ;; Caching is not possible, check it directly.
  10550. (org-entry-get pom property 'inherit)
  10551. ;; Get all properties, so we can do complicated checks easily.
  10552. (cdr (assoc-string property
  10553. (or org-cached-props
  10554. (setq org-cached-props (org-entry-properties pom)))
  10555. t))))
  10556. (defun org-global-tags-completion-table (&optional files)
  10557. "Return the list of all tags in all agenda buffer/files.
  10558. Optional FILES argument is a list of files which can be used
  10559. instead of the agenda files."
  10560. (save-excursion
  10561. (org-uniquify
  10562. (delq nil
  10563. (apply #'append
  10564. (mapcar
  10565. (lambda (file)
  10566. (set-buffer (find-file-noselect file))
  10567. (org--tag-add-to-alist
  10568. (org-get-buffer-tags)
  10569. (mapcar (lambda (x)
  10570. (and (stringp (car-safe x))
  10571. (list (car-safe x))))
  10572. org-current-tag-alist)))
  10573. (if (car-safe files) files
  10574. (org-agenda-files))))))))
  10575. (defun org-make-tags-matcher (match &optional only-local-tags)
  10576. "Create the TAGS/TODO matcher form for the selection string MATCH.
  10577. Returns a cons of the selection string MATCH and a function
  10578. implementing the matcher.
  10579. The matcher is to be called at an Org entry, with point on the
  10580. headline, and returns non-nil if the entry matches the selection
  10581. string MATCH. It must be called with three arguments: the TODO
  10582. keyword at the entry (or nil if none), the list of all tags at
  10583. the entry including inherited ones and the reduced level of the
  10584. headline. Additionally, the category of the entry, if any, must
  10585. be specified as the text property `org-category' on the headline.
  10586. This function sets the variable `org--matcher-tags-todo-only' to
  10587. a non-nil value if the matcher restricts matching to TODO
  10588. entries, otherwise it is not touched.
  10589. When ONLY-LOCAL-TAGS is non-nil, ignore the global tag completion
  10590. table, only get buffer tags.
  10591. See also `org-scan-tags'."
  10592. (unless match
  10593. ;; Get a new match request, with completion against the global
  10594. ;; tags table and the local tags in current buffer.
  10595. (let ((org-last-tags-completion-table
  10596. (org--tag-add-to-alist
  10597. (org-get-buffer-tags)
  10598. (unless only-local-tags
  10599. (org-global-tags-completion-table)))))
  10600. (setq match
  10601. (completing-read
  10602. "Match: "
  10603. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  10604. (let ((match0 match)
  10605. (re (concat
  10606. "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
  10607. "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
  10608. "\\([<>=]\\{1,2\\}\\)"
  10609. "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
  10610. "\\|" org-tag-re "\\)"))
  10611. (start 0)
  10612. tagsmatch todomatch tagsmatcher todomatcher)
  10613. ;; Expand group tags.
  10614. (setq match (org-tags-expand match))
  10615. ;; Check if there is a TODO part of this match, which would be the
  10616. ;; part after a "/". To make sure that this slash is not part of
  10617. ;; a property value to be matched against, we also check that
  10618. ;; there is no / after that slash. First, find the last slash.
  10619. (let ((s 0))
  10620. (while (string-match "/+" match s)
  10621. (setq start (match-beginning 0))
  10622. (setq s (match-end 0))))
  10623. (if (and (string-match "/+" match start)
  10624. (not (string-match-p "\"" match start)))
  10625. ;; Match contains also a TODO-matching request.
  10626. (progn
  10627. (setq tagsmatch (substring match 0 (match-beginning 0)))
  10628. (setq todomatch (substring match (match-end 0)))
  10629. (when (string-prefix-p "!" todomatch)
  10630. (setq org--matcher-tags-todo-only t)
  10631. (setq todomatch (substring todomatch 1)))
  10632. (when (string-match "\\`\\s-*\\'" todomatch)
  10633. (setq todomatch nil)))
  10634. ;; Only matching tags.
  10635. (setq tagsmatch match)
  10636. (setq todomatch nil))
  10637. ;; Make the tags matcher.
  10638. (when (org-string-nw-p tagsmatch)
  10639. (let ((orlist nil)
  10640. (orterms (org-split-string tagsmatch "|"))
  10641. term)
  10642. (while (setq term (pop orterms))
  10643. (while (and (equal (substring term -1) "\\") orterms)
  10644. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  10645. (while (string-match re term)
  10646. (let* ((rest (substring term (match-end 0)))
  10647. (minus (and (match-end 1)
  10648. (equal (match-string 1 term) "-")))
  10649. (tag (save-match-data
  10650. (replace-regexp-in-string
  10651. "\\\\-" "-" (match-string 2 term))))
  10652. (regexp (eq (string-to-char tag) ?{))
  10653. (levelp (match-end 4))
  10654. (propp (match-end 5))
  10655. (mm
  10656. (cond
  10657. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  10658. (levelp
  10659. `(,(org-op-to-function (match-string 3 term))
  10660. level
  10661. ,(string-to-number (match-string 4 term))))
  10662. (propp
  10663. (let* ((gv (pcase (upcase (match-string 5 term))
  10664. ("CATEGORY"
  10665. '(get-text-property (point) 'org-category))
  10666. ("TODO" 'todo)
  10667. (p `(org-cached-entry-get nil ,p))))
  10668. (pv (match-string 7 term))
  10669. (regexp (eq (string-to-char pv) ?{))
  10670. (strp (eq (string-to-char pv) ?\"))
  10671. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  10672. (po (org-op-to-function (match-string 6 term)
  10673. (if timep 'time strp))))
  10674. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  10675. (when timep (setq pv (org-matcher-time pv)))
  10676. (cond ((and regexp (eq po '/=))
  10677. `(not (string-match ,pv (or ,gv ""))))
  10678. (regexp `(string-match ,pv (or ,gv "")))
  10679. (strp `(,po (or ,gv "") ,pv))
  10680. (t
  10681. `(,po
  10682. (string-to-number (or ,gv ""))
  10683. ,(string-to-number pv))))))
  10684. (t `(member ,tag tags-list)))))
  10685. (push (if minus `(not ,mm) mm) tagsmatcher)
  10686. (setq term rest)))
  10687. (push `(and ,@tagsmatcher) orlist)
  10688. (setq tagsmatcher nil))
  10689. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  10690. ;; Make the TODO matcher.
  10691. (when (org-string-nw-p todomatch)
  10692. (let ((orlist nil))
  10693. (dolist (term (org-split-string todomatch "|"))
  10694. (while (string-match re term)
  10695. (let* ((minus (and (match-end 1)
  10696. (equal (match-string 1 term) "-")))
  10697. (kwd (match-string 2 term))
  10698. (regexp (eq (string-to-char kwd) ?{))
  10699. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  10700. `(equal todo ,kwd))))
  10701. (push (if minus `(not ,mm) mm) todomatcher))
  10702. (setq term (substring term (match-end 0))))
  10703. (push (if (> (length todomatcher) 1)
  10704. (cons 'and todomatcher)
  10705. (car todomatcher))
  10706. orlist)
  10707. (setq todomatcher nil))
  10708. (setq todomatcher (cons 'or orlist))))
  10709. ;; Return the string and function of the matcher. If no
  10710. ;; tags-specific or todo-specific matcher exists, match
  10711. ;; everything.
  10712. (let ((matcher (if (and tagsmatcher todomatcher)
  10713. `(and ,tagsmatcher ,todomatcher)
  10714. (or tagsmatcher todomatcher t))))
  10715. (when org--matcher-tags-todo-only
  10716. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  10717. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  10718. (defun org--tags-expand-group (group tag-groups expanded)
  10719. "Recursively expand all tags in GROUP, according to TAG-GROUPS.
  10720. TAG-GROUPS is the list of groups used for expansion. EXPANDED is
  10721. an accumulator used in recursive calls."
  10722. (dolist (tag group)
  10723. (unless (member tag expanded)
  10724. (let ((group (assoc tag tag-groups)))
  10725. (push tag expanded)
  10726. (when group
  10727. (setq expanded
  10728. (org--tags-expand-group (cdr group) tag-groups expanded))))))
  10729. expanded)
  10730. (defun org-tags-expand (match &optional single-as-list)
  10731. "Expand group tags in MATCH.
  10732. This replaces every group tag in MATCH with a regexp tag search.
  10733. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  10734. will be replaced like this:
  10735. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10736. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10737. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10738. Replacing by a regexp preserves the structure of the match.
  10739. E.g., this expansion
  10740. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  10741. will match anything tagged with \"Lab\" and \"Home\", or tagged
  10742. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"Home\".
  10743. A group tag in MATCH can contain regular expressions of its own.
  10744. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  10745. will be replaced like this:
  10746. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  10747. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  10748. assumed to be a single group tag, and the function will return
  10749. the list of tags in this group."
  10750. (unless (org-string-nw-p match) (error "Invalid match tag: %S" match))
  10751. (let ((tag-groups
  10752. (or org-tag-groups-alist-for-agenda org-tag-groups-alist)))
  10753. (cond
  10754. (single-as-list (org--tags-expand-group (list match) tag-groups nil))
  10755. (org-group-tags
  10756. (let* ((case-fold-search t)
  10757. (tag-syntax org-mode-syntax-table)
  10758. (group-keys (mapcar #'car tag-groups))
  10759. (key-regexp (concat "\\([+-]?\\)" (regexp-opt group-keys 'words)))
  10760. (return-match match))
  10761. ;; Mark regexp-expressions in the match-expression so that we
  10762. ;; do not replace them later on.
  10763. (let ((s 0))
  10764. (while (string-match "{.+?}" return-match s)
  10765. (setq s (match-end 0))
  10766. (add-text-properties
  10767. (match-beginning 0) (match-end 0) '(regexp t) return-match)))
  10768. ;; @ and _ are allowed as word-components in tags.
  10769. (modify-syntax-entry ?@ "w" tag-syntax)
  10770. (modify-syntax-entry ?_ "w" tag-syntax)
  10771. ;; For each tag token found in MATCH, compute a regexp and it
  10772. (with-syntax-table tag-syntax
  10773. (replace-regexp-in-string
  10774. key-regexp
  10775. (lambda (m)
  10776. (if (get-text-property (match-beginning 2) 'regexp m)
  10777. m ;regexp tag: ignore
  10778. (let* ((operator (match-string 1 m))
  10779. (tag-token (let ((tag (match-string 2 m)))
  10780. (list tag)))
  10781. regexp-tags regular-tags)
  10782. ;; Partition tags between regexp and regular tags.
  10783. ;; Remove curly bracket syntax from regexp tags.
  10784. (dolist (tag (org--tags-expand-group tag-token tag-groups nil))
  10785. (save-match-data
  10786. (if (string-match "{\\(.+?\\)}" tag)
  10787. (push (match-string 1 tag) regexp-tags)
  10788. (push tag regular-tags))))
  10789. ;; Replace tag token by the appropriate regexp.
  10790. ;; Regular tags need to be regexp-quoted, whereas
  10791. ;; regexp-tags are inserted as-is.
  10792. (let ((regular (regexp-opt regular-tags))
  10793. (regexp (mapconcat #'identity regexp-tags "\\|")))
  10794. (concat operator
  10795. (cond
  10796. ((null regular-tags) (format "{%s}" regexp))
  10797. ((null regexp-tags) (format "{\\<%s\\>}" regular))
  10798. (t (format "{\\<%s\\>\\|%s}" regular regexp))))))))
  10799. return-match
  10800. t t))))
  10801. (t match))))
  10802. (defun org-op-to-function (op &optional stringp)
  10803. "Turn an operator into the appropriate function."
  10804. (setq op
  10805. (cond
  10806. ((equal op "<" ) '(< org-string< org-time<))
  10807. ((equal op ">" ) '(> org-string> org-time>))
  10808. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  10809. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  10810. ((member op '("=" "==")) '(= string= org-time=))
  10811. ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
  10812. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  10813. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  10814. (defvar org-tags-overlay (make-overlay 1 1))
  10815. (delete-overlay org-tags-overlay)
  10816. (defun org-add-prop-inherited (s)
  10817. (add-text-properties 0 (length s) '(inherited t) s)
  10818. s)
  10819. (defun org-toggle-tag (tag &optional onoff)
  10820. "Toggle the tag TAG for the current line.
  10821. If ONOFF is `on' or `off', don't toggle but set to this state."
  10822. (save-excursion
  10823. (org-back-to-heading t)
  10824. (let ((current
  10825. ;; Reverse the tags list so any new tag is appended to the
  10826. ;; current list of tags.
  10827. (nreverse (org-get-tags nil t)))
  10828. res)
  10829. (pcase onoff
  10830. (`off (setq current (delete tag current)))
  10831. ((or `on (guard (not (member tag current))))
  10832. (setq res t)
  10833. (cl-pushnew tag current :test #'equal))
  10834. (_ (setq current (delete tag current))))
  10835. (org-set-tags (nreverse current))
  10836. res)))
  10837. (defun org--align-tags-here (to-col)
  10838. "Align tags on the current headline to TO-COL.
  10839. Assume point is on a headline. Preserve point when aligning
  10840. tags."
  10841. (when (org-match-line org-tag-line-re)
  10842. (let* ((tags-start (match-beginning 1))
  10843. (blank-start (save-excursion
  10844. (goto-char tags-start)
  10845. (skip-chars-backward " \t")
  10846. (point)))
  10847. (new (max (if (>= to-col 0) to-col
  10848. (- (abs to-col) (string-width (match-string 1))))
  10849. ;; Introduce at least one space after the heading
  10850. ;; or the stars.
  10851. (save-excursion
  10852. (goto-char blank-start)
  10853. (1+ (current-column)))))
  10854. (current
  10855. (save-excursion (goto-char tags-start) (current-column)))
  10856. (origin (point-marker))
  10857. (column (current-column))
  10858. (in-blank? (and (> origin blank-start) (<= origin tags-start))))
  10859. (when (/= new current)
  10860. (delete-region blank-start tags-start)
  10861. (goto-char blank-start)
  10862. (let ((indent-tabs-mode nil)) (indent-to new))
  10863. ;; Try to move back to original position. If point was in the
  10864. ;; blanks before the tags, ORIGIN marker is of no use because
  10865. ;; it now points to BLANK-START. Use COLUMN instead.
  10866. (if in-blank? (org-move-to-column column) (goto-char origin))))))
  10867. (defun org-set-tags-command (&optional arg)
  10868. "Set the tags for the current visible entry.
  10869. When called with `\\[universal-argument]' prefix argument ARG, \
  10870. realign all tags
  10871. in the current buffer.
  10872. When called with `\\[universal-argument] \\[universal-argument]' prefix argument, \
  10873. unconditionally do not
  10874. offer the fast tag selection interface.
  10875. If a region is active, set tags in the region according to the
  10876. setting of `org-loop-over-headlines-in-active-region'.
  10877. This function is for interactive use only;
  10878. in Lisp code use `org-set-tags' instead."
  10879. (interactive "P")
  10880. (let ((org-use-fast-tag-selection
  10881. (unless (equal '(16) arg) org-use-fast-tag-selection)))
  10882. (cond
  10883. ((equal '(4) arg) (org-align-tags t))
  10884. ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
  10885. (let (org-loop-over-headlines-in-active-region) ; hint: infinite recursion.
  10886. (org-map-entries
  10887. #'org-set-tags-command
  10888. nil
  10889. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  10890. 'region-start-level
  10891. 'region)
  10892. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
  10893. (t
  10894. (save-excursion
  10895. (org-back-to-heading)
  10896. (let* ((all-tags (org-get-tags))
  10897. (table (setq org-last-tags-completion-table
  10898. (org--tag-add-to-alist
  10899. (and org-complete-tags-always-offer-all-agenda-tags
  10900. (org-global-tags-completion-table
  10901. (org-agenda-files)))
  10902. (or org-current-tag-alist (org-get-buffer-tags)))))
  10903. (current-tags
  10904. (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
  10905. all-tags))
  10906. (inherited-tags
  10907. (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
  10908. all-tags))
  10909. (tags
  10910. (replace-regexp-in-string
  10911. ;; Ignore all forbidden characters in tags.
  10912. "[^[:alnum:]_@#%]+" ":"
  10913. (if (or (eq t org-use-fast-tag-selection)
  10914. (and org-use-fast-tag-selection
  10915. (delq nil (mapcar #'cdr table))))
  10916. (org-fast-tag-selection
  10917. current-tags
  10918. inherited-tags
  10919. table
  10920. (and org-fast-tag-selection-include-todo org-todo-key-alist))
  10921. (let ((org-add-colon-after-tag-completion (< 1 (length table)))
  10922. (crm-separator "[ \t]*:[ \t]*"))
  10923. (mapconcat #'identity
  10924. (completing-read-multiple
  10925. "Tags: "
  10926. org-last-tags-completion-table
  10927. nil nil (org-make-tag-string current-tags)
  10928. 'org-tags-history)
  10929. ":"))))))
  10930. (org-set-tags tags)))))
  10931. ;; `save-excursion' may not replace the point at the right
  10932. ;; position.
  10933. (when (and (save-excursion (skip-chars-backward "*") (bolp))
  10934. (looking-at-p " "))
  10935. (forward-char))))
  10936. (defun org-align-tags (&optional all)
  10937. "Align tags in current entry.
  10938. When optional argument ALL is non-nil, align all tags in the
  10939. visible part of the buffer."
  10940. (let ((get-indent-column
  10941. (lambda ()
  10942. (let ((offset (if (bound-and-true-p org-indent-mode)
  10943. (* (1- org-indent-indentation-per-level)
  10944. (1- (org-current-level)))
  10945. 0)))
  10946. (+ org-tags-column
  10947. (if (> org-tags-column 0) (- offset) offset))))))
  10948. (if (and (not all) (org-at-heading-p))
  10949. (org--align-tags-here (funcall get-indent-column))
  10950. (save-excursion
  10951. (if all
  10952. (progn
  10953. (goto-char (point-min))
  10954. (while (re-search-forward org-tag-line-re nil t)
  10955. (org--align-tags-here (funcall get-indent-column))))
  10956. (org-back-to-heading t)
  10957. (org--align-tags-here (funcall get-indent-column)))))))
  10958. (defun org-set-tags (tags)
  10959. "Set the tags of the current entry to TAGS, replacing current tags.
  10960. TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
  10961. If TAGS is nil or the empty string, all tags are removed.
  10962. This function assumes point is on a headline."
  10963. (org-with-wide-buffer
  10964. (let ((tags (pcase tags
  10965. ((pred listp) tags)
  10966. ((pred stringp) (split-string (org-trim tags) ":" t))
  10967. (_ (error "Invalid tag specification: %S" tags))))
  10968. (old-tags (org-get-tags nil t))
  10969. (tags-change? nil))
  10970. (when (functionp org-tags-sort-function)
  10971. (setq tags (sort tags org-tags-sort-function)))
  10972. (setq tags-change? (not (equal tags old-tags)))
  10973. (when tags-change?
  10974. ;; Delete previous tags and any trailing white space.
  10975. (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
  10976. (line-end-position)))
  10977. (skip-chars-backward " \t")
  10978. (delete-region (point) (line-end-position))
  10979. ;; Deleting white spaces may break an otherwise empty headline.
  10980. ;; Re-introduce one space in this case.
  10981. (unless (org-at-heading-p) (insert " "))
  10982. (when tags
  10983. (save-excursion (insert " " (org-make-tag-string tags)))
  10984. ;; When text is being inserted on an invisible region
  10985. ;; boundary, it can be inadvertently sucked into
  10986. ;; invisibility.
  10987. (unless (org-invisible-p (line-beginning-position))
  10988. (org-flag-region (point) (line-end-position) nil 'outline))))
  10989. ;; Align tags, if any.
  10990. (when tags (org-align-tags))
  10991. (when tags-change? (run-hooks 'org-after-tags-change-hook)))))
  10992. (defun org-change-tag-in-region (beg end tag off)
  10993. "Add or remove TAG for each entry in the region.
  10994. This works in the agenda, and also in an Org buffer."
  10995. (interactive
  10996. (list (region-beginning) (region-end)
  10997. (let ((org-last-tags-completion-table
  10998. (if (derived-mode-p 'org-mode)
  10999. (org--tag-add-to-alist
  11000. (org-get-buffer-tags)
  11001. (org-global-tags-completion-table))
  11002. (org-global-tags-completion-table))))
  11003. (completing-read
  11004. "Tag: " org-last-tags-completion-table nil nil nil
  11005. 'org-tags-history))
  11006. (progn
  11007. (message "[s]et or [r]emove? ")
  11008. (equal (read-char-exclusive) ?r))))
  11009. (deactivate-mark)
  11010. (let ((agendap (equal major-mode 'org-agenda-mode))
  11011. l1 l2 m buf pos newhead (cnt 0))
  11012. (goto-char end)
  11013. (setq l2 (1- (org-current-line)))
  11014. (goto-char beg)
  11015. (setq l1 (org-current-line))
  11016. (cl-loop for l from l1 to l2 do
  11017. (org-goto-line l)
  11018. (setq m (get-text-property (point) 'org-hd-marker))
  11019. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  11020. (and agendap m))
  11021. (setq buf (if agendap (marker-buffer m) (current-buffer))
  11022. pos (if agendap m (point)))
  11023. (with-current-buffer buf
  11024. (save-excursion
  11025. (save-restriction
  11026. (goto-char pos)
  11027. (setq cnt (1+ cnt))
  11028. (org-toggle-tag tag (if off 'off 'on))
  11029. (setq newhead (org-get-heading)))))
  11030. (and agendap (org-agenda-change-all-lines newhead m))))
  11031. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  11032. (defun org-tags-completion-function (string _predicate &optional flag)
  11033. "Complete tag STRING.
  11034. FLAG specifies the type of completion operation to perform. This
  11035. function is passed as a collection function to `completing-read',
  11036. which see."
  11037. (let ((completion-ignore-case nil) ;tags are case-sensitive
  11038. (confirm (lambda (x) (stringp (car x))))
  11039. (prefix ""))
  11040. (when (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  11041. (setq prefix (match-string 1 string))
  11042. (setq string (match-string 2 string)))
  11043. (pcase flag
  11044. (`t (all-completions string org-last-tags-completion-table confirm))
  11045. (`lambda (assoc string org-last-tags-completion-table)) ;exact match?
  11046. (`nil
  11047. (pcase (try-completion string org-last-tags-completion-table confirm)
  11048. ((and completion (pred stringp))
  11049. (concat prefix
  11050. completion
  11051. (if (and org-add-colon-after-tag-completion
  11052. (assoc completion org-last-tags-completion-table))
  11053. ":"
  11054. "")))
  11055. (completion completion)))
  11056. (_ nil))))
  11057. (defun org-fast-tag-insert (kwd tags face &optional end)
  11058. "Insert KWD, and the TAGS, the latter with face FACE.
  11059. Also insert END."
  11060. (insert (format "%-12s" (concat kwd ":"))
  11061. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  11062. (or end "")))
  11063. (defun org-fast-tag-show-exit (flag)
  11064. (save-excursion
  11065. (org-goto-line 3)
  11066. (when (re-search-forward "[ \t]+Next change exits" (line-end-position) t)
  11067. (replace-match ""))
  11068. (when flag
  11069. (end-of-line 1)
  11070. (org-move-to-column (- (window-width) 19) t)
  11071. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  11072. (defun org-set-current-tags-overlay (current prefix)
  11073. "Add an overlay to CURRENT tag with PREFIX."
  11074. (let ((s (org-make-tag-string current)))
  11075. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  11076. (org-overlay-display org-tags-overlay (concat prefix s))))
  11077. (defvar org-last-tag-selection-key nil)
  11078. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  11079. "Fast tag selection with single keys.
  11080. CURRENT is the current list of tags in the headline, INHERITED is the
  11081. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  11082. possibly with grouping information. TODO-TABLE is a similar table with
  11083. TODO keywords, should these have keys assigned to them.
  11084. If the keys are nil, a-z are automatically assigned.
  11085. Returns the new tags string, or nil to not change the current settings."
  11086. (let* ((fulltable (append table todo-table))
  11087. (maxlen (if (null fulltable) 0
  11088. (apply #'max
  11089. (mapcar (lambda (x)
  11090. (if (stringp (car x)) (string-width (car x))
  11091. 0))
  11092. fulltable))))
  11093. (buf (current-buffer))
  11094. (expert (eq org-fast-tag-selection-single-key 'expert))
  11095. (tab-tags nil)
  11096. (fwidth (+ maxlen 3 1 3))
  11097. (ncol (/ (- (window-width) 4) fwidth))
  11098. (i-face 'org-done)
  11099. (c-face 'org-todo)
  11100. tg cnt e c char c1 c2 ntable tbl rtn
  11101. ov-start ov-end ov-prefix
  11102. (exit-after-next org-fast-tag-selection-single-key)
  11103. (done-keywords org-done-keywords)
  11104. groups ingroup intaggroup)
  11105. (save-excursion
  11106. (beginning-of-line)
  11107. (if (looking-at org-tag-line-re)
  11108. (setq ov-start (match-beginning 1)
  11109. ov-end (match-end 1)
  11110. ov-prefix "")
  11111. (setq ov-start (1- (line-end-position))
  11112. ov-end (1+ ov-start))
  11113. (skip-chars-forward "^\n\r")
  11114. (setq ov-prefix
  11115. (concat
  11116. (buffer-substring (1- (point)) (point))
  11117. (if (> (current-column) org-tags-column)
  11118. " "
  11119. (make-string (- org-tags-column (current-column)) ?\ ))))))
  11120. (move-overlay org-tags-overlay ov-start ov-end)
  11121. (save-excursion
  11122. (save-window-excursion
  11123. (if expert
  11124. (set-buffer (get-buffer-create " *Org tags*"))
  11125. (delete-other-windows)
  11126. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  11127. (org-switch-to-buffer-other-window " *Org tags*"))
  11128. (erase-buffer)
  11129. (setq-local org-done-keywords done-keywords)
  11130. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  11131. (org-fast-tag-insert "Current" current c-face "\n\n")
  11132. (org-fast-tag-show-exit exit-after-next)
  11133. (org-set-current-tags-overlay current ov-prefix)
  11134. (setq tbl fulltable char ?a cnt 0)
  11135. (while (setq e (pop tbl))
  11136. (cond
  11137. ((eq (car e) :startgroup)
  11138. (push '() groups) (setq ingroup t)
  11139. (unless (zerop cnt)
  11140. (setq cnt 0)
  11141. (insert "\n"))
  11142. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  11143. ((eq (car e) :endgroup)
  11144. (setq ingroup nil cnt 0)
  11145. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  11146. ((eq (car e) :startgrouptag)
  11147. (setq intaggroup t)
  11148. (unless (zerop cnt)
  11149. (setq cnt 0)
  11150. (insert "\n"))
  11151. (insert "[ "))
  11152. ((eq (car e) :endgrouptag)
  11153. (setq intaggroup nil cnt 0)
  11154. (insert "]\n"))
  11155. ((equal e '(:newline))
  11156. (unless (zerop cnt)
  11157. (setq cnt 0)
  11158. (insert "\n")
  11159. (setq e (car tbl))
  11160. (while (equal (car tbl) '(:newline))
  11161. (insert "\n")
  11162. (setq tbl (cdr tbl)))))
  11163. ((equal e '(:grouptags)) (insert " : "))
  11164. (t
  11165. (setq tg (copy-sequence (car e)) c2 nil)
  11166. (if (cdr e)
  11167. (setq c (cdr e))
  11168. ;; automatically assign a character.
  11169. (setq c1 (string-to-char
  11170. (downcase (substring
  11171. tg (if (= (string-to-char tg) ?@) 1 0)))))
  11172. (if (or (rassoc c1 ntable) (rassoc c1 table))
  11173. (while (or (rassoc char ntable) (rassoc char table))
  11174. (setq char (1+ char)))
  11175. (setq c2 c1))
  11176. (setq c (or c2 char)))
  11177. (when ingroup (push tg (car groups)))
  11178. (setq tg (org-add-props tg nil 'face
  11179. (cond
  11180. ((not (assoc tg table))
  11181. (org-get-todo-face tg))
  11182. ((member tg current) c-face)
  11183. ((member tg inherited) i-face))))
  11184. (when (equal (caar tbl) :grouptags)
  11185. (org-add-props tg nil 'face 'org-tag-group))
  11186. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  11187. (insert "[" c "] " tg (make-string
  11188. (- fwidth 4 (length tg)) ?\ ))
  11189. (push (cons tg c) ntable)
  11190. (when (= (cl-incf cnt) ncol)
  11191. (unless (memq (caar tbl) '(:endgroup :endgrouptag))
  11192. (insert "\n")
  11193. (when (or ingroup intaggroup) (insert " ")))
  11194. (setq cnt 0)))))
  11195. (setq ntable (nreverse ntable))
  11196. (insert "\n")
  11197. (goto-char (point-min))
  11198. (unless expert (org-fit-window-to-buffer))
  11199. (setq rtn
  11200. (catch 'exit
  11201. (while t
  11202. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  11203. (if (not groups) "no " "")
  11204. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  11205. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11206. (setq org-last-tag-selection-key c)
  11207. (cond
  11208. ((= c ?\r) (throw 'exit t))
  11209. ((= c ?!)
  11210. (setq groups (not groups))
  11211. (goto-char (point-min))
  11212. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  11213. ((= c ?\C-c)
  11214. (if (not expert)
  11215. (org-fast-tag-show-exit
  11216. (setq exit-after-next (not exit-after-next)))
  11217. (setq expert nil)
  11218. (delete-other-windows)
  11219. (set-window-buffer (split-window-vertically) " *Org tags*")
  11220. (org-switch-to-buffer-other-window " *Org tags*")
  11221. (org-fit-window-to-buffer)))
  11222. ((or (= c ?\C-g)
  11223. (and (= c ?q) (not (rassoc c ntable))))
  11224. (delete-overlay org-tags-overlay)
  11225. (setq quit-flag t))
  11226. ((= c ?\ )
  11227. (setq current nil)
  11228. (when exit-after-next (setq exit-after-next 'now)))
  11229. ((= c ?\t)
  11230. (condition-case nil
  11231. (unless tab-tags
  11232. (setq tab-tags
  11233. (delq nil
  11234. (mapcar (lambda (x)
  11235. (let ((item (car-safe x)))
  11236. (and (stringp item)
  11237. (list item))))
  11238. (org--tag-add-to-alist
  11239. (with-current-buffer buf
  11240. (org-get-buffer-tags))
  11241. table))))))
  11242. (setq tg (completing-read "Tag: " tab-tags))
  11243. (when (string-match "\\S-" tg)
  11244. (cl-pushnew (list tg) tab-tags :test #'equal)
  11245. (if (member tg current)
  11246. (setq current (delete tg current))
  11247. (push tg current)))
  11248. (when exit-after-next (setq exit-after-next 'now)))
  11249. ((setq e (rassoc c todo-table) tg (car e))
  11250. (with-current-buffer buf
  11251. (save-excursion (org-todo tg)))
  11252. (when exit-after-next (setq exit-after-next 'now)))
  11253. ((setq e (rassoc c ntable) tg (car e))
  11254. (if (member tg current)
  11255. (setq current (delete tg current))
  11256. (cl-loop for g in groups do
  11257. (when (member tg g)
  11258. (dolist (x g) (setq current (delete x current)))))
  11259. (push tg current))
  11260. (when exit-after-next (setq exit-after-next 'now))))
  11261. ;; Create a sorted list
  11262. (setq current
  11263. (sort current
  11264. (lambda (a b)
  11265. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  11266. (when (eq exit-after-next 'now) (throw 'exit t))
  11267. (goto-char (point-min))
  11268. (beginning-of-line 2)
  11269. (delete-region (point) (line-end-position))
  11270. (org-fast-tag-insert "Current" current c-face)
  11271. (org-set-current-tags-overlay current ov-prefix)
  11272. (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
  11273. (while (re-search-forward tag-re nil t)
  11274. (let ((tag (match-string 1)))
  11275. (add-text-properties
  11276. (match-beginning 1) (match-end 1)
  11277. (list 'face
  11278. (cond
  11279. ((member tag current) c-face)
  11280. ((member tag inherited) i-face)
  11281. (t (get-text-property (match-beginning 1) '
  11282. face))))))))
  11283. (goto-char (point-min)))))
  11284. (delete-overlay org-tags-overlay)
  11285. (if rtn
  11286. (mapconcat 'identity current ":")
  11287. nil)))))
  11288. (defun org-make-tag-string (tags)
  11289. "Return string associated to TAGS.
  11290. TAGS is a list of strings."
  11291. (if (null tags) ""
  11292. (format ":%s:" (mapconcat #'identity tags ":"))))
  11293. (defun org--get-local-tags ()
  11294. "Return list of tags for the current headline.
  11295. Assume point is at the beginning of the headline."
  11296. (and (looking-at org-tag-line-re)
  11297. (split-string (match-string-no-properties 2) ":" t)))
  11298. (defun org-get-tags (&optional pos local)
  11299. "Get the list of tags specified in the current headline.
  11300. When argument POS is non-nil, retrieve tags for headline at POS.
  11301. According to `org-use-tag-inheritance', tags may be inherited
  11302. from parent headlines, and from the whole document, through
  11303. `org-file-tags'. In this case, the returned list of tags
  11304. contains tags in this order: file tags, tags inherited from
  11305. parent headlines, local tags. If a tag appears multiple times,
  11306. only the most local tag is returned.
  11307. However, when optional argument LOCAL is non-nil, only return
  11308. tags specified at the headline.
  11309. Inherited tags have the `inherited' text property."
  11310. (if (and org-trust-scanner-tags
  11311. (or (not pos) (eq pos (point)))
  11312. (not local))
  11313. org-scanner-tags
  11314. (org-with-point-at (or pos (point))
  11315. (unless (org-before-first-heading-p)
  11316. (org-back-to-heading t)
  11317. (let ((ltags (org--get-local-tags)) itags)
  11318. (if (or local (not org-use-tag-inheritance)) ltags
  11319. (while (org-up-heading-safe)
  11320. (setq itags (nconc (mapcar #'org-add-prop-inherited
  11321. (org--get-local-tags))
  11322. itags)))
  11323. (setq itags (append org-file-tags itags))
  11324. (nreverse
  11325. (delete-dups
  11326. (nreverse (nconc (org-remove-uninherited-tags itags) ltags))))))))))
  11327. (defun org-get-buffer-tags ()
  11328. "Get a table of all tags used in the buffer, for completion."
  11329. (org-with-point-at 1
  11330. (let (tags)
  11331. (while (re-search-forward org-tag-line-re nil t)
  11332. (setq tags (nconc (split-string (match-string-no-properties 2) ":")
  11333. tags)))
  11334. (mapcar #'list (delete-dups (append org-file-tags tags))))))
  11335. ;;;; The mapping API
  11336. (defvar org-agenda-skip-comment-trees)
  11337. (defvar org-agenda-skip-function)
  11338. (defun org-map-entries (func &optional match scope &rest skip)
  11339. "Call FUNC at each headline selected by MATCH in SCOPE.
  11340. FUNC is a function or a Lisp form. The function will be called without
  11341. arguments, with the cursor positioned at the beginning of the headline.
  11342. The return values of all calls to the function will be collected and
  11343. returned as a list.
  11344. The call to FUNC will be wrapped into a `save-excursion' form, so FUNC
  11345. does not need to preserve point. After evaluation, the cursor will be
  11346. moved to the end of the line (presumably of the headline of the
  11347. processed entry) and search continues from there. Under some
  11348. circumstances, this may not produce the wanted results. For example,
  11349. if you have removed (e.g. archived) the current (sub)tree it could
  11350. mean that the next entry will be skipped entirely. In such cases, you
  11351. can specify the position from where search should continue by making
  11352. FUNC set the variable `org-map-continue-from' to the desired buffer
  11353. position.
  11354. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  11355. Only headlines that are matched by this query will be considered during
  11356. the iteration. When MATCH is nil or t, all headlines will be
  11357. visited by the iteration.
  11358. SCOPE determines the scope of this command. It can be any of:
  11359. nil The current buffer, respecting the restriction if any
  11360. tree The subtree started with the entry at point
  11361. region The entries within the active region, if any
  11362. region-start-level
  11363. The entries within the active region, but only those at
  11364. the same level than the first one.
  11365. file The current buffer, without restriction
  11366. file-with-archives
  11367. The current buffer, and any archives associated with it
  11368. agenda All agenda files
  11369. agenda-with-archives
  11370. All agenda files with any archive files associated with them
  11371. \(file1 file2 ...)
  11372. If this is a list, all files in the list will be scanned
  11373. The remaining args are treated as settings for the skipping facilities of
  11374. the scanner. The following items can be given here:
  11375. archive skip trees with the archive tag
  11376. comment skip trees with the COMMENT keyword
  11377. function or Emacs Lisp form:
  11378. will be used as value for `org-agenda-skip-function', so
  11379. whenever the function returns a position, FUNC will not be
  11380. called for that entry and search will continue from the
  11381. position returned
  11382. If your function needs to retrieve the tags including inherited tags
  11383. at the *current* entry, you can use the value of the variable
  11384. `org-scanner-tags' which will be much faster than getting the value
  11385. with `org-get-tags'. If your function gets properties with
  11386. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  11387. to t around the call to `org-entry-properties' to get the same speedup.
  11388. Note that if your function moves around to retrieve tags and properties at
  11389. a *different* entry, you cannot use these techniques."
  11390. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  11391. (not (org-region-active-p)))
  11392. (let* ((org-agenda-archives-mode nil) ; just to make sure
  11393. (org-agenda-skip-archived-trees (memq 'archive skip))
  11394. (org-agenda-skip-comment-trees (memq 'comment skip))
  11395. (org-agenda-skip-function
  11396. (car (org-delete-all '(comment archive) skip)))
  11397. (org-tags-match-list-sublevels t)
  11398. (start-level (eq scope 'region-start-level))
  11399. matcher res
  11400. org-todo-keywords-for-agenda
  11401. org-done-keywords-for-agenda
  11402. org-todo-keyword-alist-for-agenda
  11403. org-tag-alist-for-agenda
  11404. org--matcher-tags-todo-only)
  11405. (cond
  11406. ((eq match t) (setq matcher t))
  11407. ((eq match nil) (setq matcher t))
  11408. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  11409. (save-excursion
  11410. (save-restriction
  11411. (cond ((eq scope 'tree)
  11412. (org-back-to-heading t)
  11413. (org-narrow-to-subtree)
  11414. (setq scope nil))
  11415. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  11416. (org-region-active-p))
  11417. ;; If needed, set start-level to a string like "2"
  11418. (when start-level
  11419. (save-excursion
  11420. (goto-char (region-beginning))
  11421. (unless (org-at-heading-p) (outline-next-heading))
  11422. (setq start-level (org-current-level))))
  11423. (narrow-to-region (region-beginning)
  11424. (save-excursion
  11425. (goto-char (region-end))
  11426. (unless (and (bolp) (org-at-heading-p))
  11427. (outline-next-heading))
  11428. (point)))
  11429. (setq scope nil)))
  11430. (if (not scope)
  11431. (progn
  11432. (org-agenda-prepare-buffers
  11433. (and buffer-file-name (list buffer-file-name)))
  11434. (setq res
  11435. (org-scan-tags
  11436. func matcher org--matcher-tags-todo-only start-level)))
  11437. ;; Get the right scope
  11438. (cond
  11439. ((and scope (listp scope) (symbolp (car scope)))
  11440. (setq scope (eval scope)))
  11441. ((eq scope 'agenda)
  11442. (setq scope (org-agenda-files t)))
  11443. ((eq scope 'agenda-with-archives)
  11444. (setq scope (org-agenda-files t))
  11445. (setq scope (org-add-archive-files scope)))
  11446. ((eq scope 'file)
  11447. (setq scope (and buffer-file-name (list buffer-file-name))))
  11448. ((eq scope 'file-with-archives)
  11449. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  11450. (org-agenda-prepare-buffers scope)
  11451. (dolist (file scope)
  11452. (with-current-buffer (org-find-base-buffer-visiting file)
  11453. (org-with-wide-buffer
  11454. (goto-char (point-min))
  11455. (setq res
  11456. (append
  11457. res
  11458. (org-scan-tags
  11459. func matcher org--matcher-tags-todo-only)))))))))
  11460. res)))
  11461. ;;; Properties API
  11462. (defconst org-special-properties
  11463. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  11464. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  11465. "The special properties valid in Org mode.
  11466. These are properties that are not defined in the property drawer,
  11467. but in some other way.")
  11468. (defconst org-default-properties
  11469. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  11470. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  11471. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  11472. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  11473. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  11474. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  11475. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  11476. "Some properties that are used by Org mode for various purposes.
  11477. Being in this list makes sure that they are offered for completion.")
  11478. (defun org--valid-property-p (property)
  11479. "Non-nil when string PROPERTY is a valid property name."
  11480. (not
  11481. (or (equal property "")
  11482. (string-match-p "\\s-" property))))
  11483. (defun org--update-property-plist (key val props)
  11484. "Associate KEY to VAL in alist PROPS.
  11485. Modifications are made by side-effect. Return new alist."
  11486. (let* ((appending (string= (substring key -1) "+"))
  11487. (key (if appending (substring key 0 -1) key))
  11488. (old (assoc-string key props t)))
  11489. (if (not old) (cons (cons key val) props)
  11490. (setcdr old (if appending (concat (cdr old) " " val) val))
  11491. props)))
  11492. (defun org-get-property-block (&optional beg force)
  11493. "Return the (beg . end) range of the body of the property drawer.
  11494. BEG is the beginning of the current subtree or the beginning of
  11495. the document if before the first headline. If it is not given,
  11496. it will be found. If the drawer does not exist, create it if
  11497. FORCE is non-nil, or return nil."
  11498. (org-with-wide-buffer
  11499. (let ((beg (cond (beg (goto-char beg))
  11500. ((or (not (featurep 'org-inlinetask))
  11501. (org-inlinetask-in-task-p))
  11502. (org-back-to-heading-or-point-min t) (point))
  11503. (t (org-with-limited-levels
  11504. (org-back-to-heading-or-point-min t))
  11505. (point)))))
  11506. ;; Move point to its position according to its positional rules.
  11507. (cond ((org-before-first-heading-p)
  11508. (while (and (org-at-comment-p) (bolp)) (forward-line)))
  11509. (t (forward-line)
  11510. (when (looking-at-p org-planning-line-re) (forward-line))))
  11511. (cond ((looking-at org-property-drawer-re)
  11512. (forward-line)
  11513. (cons (point) (progn (goto-char (match-end 0))
  11514. (line-beginning-position))))
  11515. (force
  11516. (goto-char beg)
  11517. (org-insert-property-drawer)
  11518. (let ((pos (save-excursion (re-search-forward org-property-drawer-re)
  11519. (line-beginning-position))))
  11520. (cons pos pos)))))))
  11521. (defun org-at-property-drawer-p ()
  11522. "Non-nil when point is at the first line of a property drawer."
  11523. (org-with-wide-buffer
  11524. (beginning-of-line)
  11525. (and (looking-at org-property-drawer-re)
  11526. (or (bobp)
  11527. (progn
  11528. (forward-line -1)
  11529. (cond ((org-at-heading-p))
  11530. ((looking-at org-planning-line-re)
  11531. (forward-line -1)
  11532. (org-at-heading-p))
  11533. ((looking-at org-comment-regexp)
  11534. (forward-line -1)
  11535. (while (and (not (bobp)) (looking-at org-comment-regexp))
  11536. (forward-line -1))
  11537. (looking-at org-comment-regexp))
  11538. (t nil)))))))
  11539. (defun org-at-property-p ()
  11540. "Non-nil when point is inside a property drawer.
  11541. See `org-property-re' for match data, if applicable."
  11542. (save-excursion
  11543. (beginning-of-line)
  11544. (and (looking-at org-property-re)
  11545. (let ((property-drawer (save-match-data (org-get-property-block))))
  11546. (and property-drawer
  11547. (>= (point) (car property-drawer))
  11548. (< (point) (cdr property-drawer)))))))
  11549. (defun org-property-action ()
  11550. "Do an action on properties."
  11551. (interactive)
  11552. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  11553. (let ((c (read-char-exclusive)))
  11554. (cl-case c
  11555. (?s (call-interactively #'org-set-property))
  11556. (?d (call-interactively #'org-delete-property))
  11557. (?D (call-interactively #'org-delete-property-globally))
  11558. (?c (call-interactively #'org-compute-property-at-point))
  11559. (otherwise (user-error "No such property action %c" c)))))
  11560. (defun org-inc-effort ()
  11561. "Increment the value of the effort property in the current entry."
  11562. (interactive)
  11563. (org-set-effort t))
  11564. (defvar org-clock-effort) ; Defined in org-clock.el.
  11565. (defvar org-clock-current-task) ; Defined in org-clock.el.
  11566. (defun org-set-effort (&optional increment value)
  11567. "Set the effort property of the current entry.
  11568. If INCREMENT is non-nil, set the property to the next allowed
  11569. value. Otherwise, if optional argument VALUE is provided, use
  11570. it. Eventually, prompt for the new value if none of the previous
  11571. variables is set."
  11572. (interactive "P")
  11573. (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
  11574. (current (org-entry-get nil org-effort-property))
  11575. (value
  11576. (cond
  11577. (increment
  11578. (unless allowed (user-error "Allowed effort values are not set"))
  11579. (or (cl-caadr (member (list current) allowed))
  11580. (user-error "Unknown value %S among allowed values" current)))
  11581. (value
  11582. (if (stringp value) value
  11583. (error "Invalid effort value: %S" value)))
  11584. (t
  11585. (let ((must-match
  11586. (and allowed
  11587. (not (get-text-property 0 'org-unrestricted
  11588. (caar allowed))))))
  11589. (completing-read "Effort: " allowed nil must-match))))))
  11590. ;; Test whether the value can be interpreted as a duration before
  11591. ;; inserting it in the buffer:
  11592. (org-duration-to-minutes value)
  11593. ;; Maybe update the effort value:
  11594. (unless (equal current value)
  11595. (org-entry-put nil org-effort-property value))
  11596. (org-refresh-property '((effort . identity)
  11597. (effort-minutes . org-duration-to-minutes))
  11598. value)
  11599. (when (equal (org-get-heading t t t t)
  11600. (bound-and-true-p org-clock-current-task))
  11601. (setq org-clock-effort value)
  11602. (org-clock-update-mode-line))
  11603. (message "%s is now %s" org-effort-property value)))
  11604. (defun org-entry-properties (&optional pom which)
  11605. "Get all properties of the current entry.
  11606. When POM is a buffer position, get all properties from the entry
  11607. there instead.
  11608. This includes the TODO keyword, the tags, time strings for
  11609. deadline, scheduled, and clocking, and any additional properties
  11610. defined in the entry.
  11611. If WHICH is nil or `all', get all properties. If WHICH is
  11612. `special' or `standard', only get that subclass. If WHICH is
  11613. a string, only get that property.
  11614. Return value is an alist. Keys are properties, as upcased
  11615. strings."
  11616. (org-with-point-at pom
  11617. (when (and (derived-mode-p 'org-mode)
  11618. (org-back-to-heading-or-point-min t))
  11619. (catch 'exit
  11620. (let* ((beg (point))
  11621. (specific (and (stringp which) (upcase which)))
  11622. (which (cond ((not specific) which)
  11623. ((member specific org-special-properties) 'special)
  11624. (t 'standard)))
  11625. props)
  11626. ;; Get the special properties, like TODO and TAGS.
  11627. (when (memq which '(nil all special))
  11628. (when (or (not specific) (string= specific "CLOCKSUM"))
  11629. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  11630. (when clocksum
  11631. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  11632. props)))
  11633. (when specific (throw 'exit props)))
  11634. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  11635. (let ((clocksumt (get-text-property (point)
  11636. :org-clock-minutes-today)))
  11637. (when clocksumt
  11638. (push (cons "CLOCKSUM_T"
  11639. (org-duration-from-minutes clocksumt))
  11640. props)))
  11641. (when specific (throw 'exit props)))
  11642. (when (or (not specific) (string= specific "ITEM"))
  11643. (let ((case-fold-search nil))
  11644. (when (looking-at org-complex-heading-regexp)
  11645. (push (cons "ITEM"
  11646. (let ((title (match-string-no-properties 4)))
  11647. (if (org-string-nw-p title)
  11648. (org-remove-tabs title)
  11649. "")))
  11650. props)))
  11651. (when specific (throw 'exit props)))
  11652. (when (or (not specific) (string= specific "TODO"))
  11653. (let ((case-fold-search nil))
  11654. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  11655. (push (cons "TODO" (match-string-no-properties 2)) props)))
  11656. (when specific (throw 'exit props)))
  11657. (when (or (not specific) (string= specific "PRIORITY"))
  11658. (push (cons "PRIORITY"
  11659. (if (looking-at org-priority-regexp)
  11660. (match-string-no-properties 2)
  11661. (char-to-string org-priority-default)))
  11662. props)
  11663. (when specific (throw 'exit props)))
  11664. (when (or (not specific) (string= specific "FILE"))
  11665. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  11666. props)
  11667. (when specific (throw 'exit props)))
  11668. (when (or (not specific) (string= specific "TAGS"))
  11669. (let ((tags (org-get-tags nil t)))
  11670. (when tags
  11671. (push (cons "TAGS" (org-make-tag-string tags))
  11672. props)))
  11673. (when specific (throw 'exit props)))
  11674. (when (or (not specific) (string= specific "ALLTAGS"))
  11675. (let ((tags (org-get-tags)))
  11676. (when tags
  11677. (push (cons "ALLTAGS" (org-make-tag-string tags))
  11678. props)))
  11679. (when specific (throw 'exit props)))
  11680. (when (or (not specific) (string= specific "BLOCKED"))
  11681. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  11682. (when specific (throw 'exit props)))
  11683. (when (or (not specific)
  11684. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  11685. (forward-line)
  11686. (when (looking-at-p org-planning-line-re)
  11687. (end-of-line)
  11688. (let ((bol (line-beginning-position))
  11689. ;; Backward compatibility: time keywords used to
  11690. ;; be configurable (before 8.3). Make sure we
  11691. ;; get the correct keyword.
  11692. (key-assoc `(("CLOSED" . ,org-closed-string)
  11693. ("DEADLINE" . ,org-deadline-string)
  11694. ("SCHEDULED" . ,org-scheduled-string))))
  11695. (dolist (pair (if specific (list (assoc specific key-assoc))
  11696. key-assoc))
  11697. (save-excursion
  11698. (when (search-backward (cdr pair) bol t)
  11699. (goto-char (match-end 0))
  11700. (skip-chars-forward " \t")
  11701. (and (looking-at org-ts-regexp-both)
  11702. (push (cons (car pair)
  11703. (match-string-no-properties 0))
  11704. props)))))))
  11705. (when specific (throw 'exit props)))
  11706. (when (or (not specific)
  11707. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  11708. (let ((find-ts
  11709. (lambda (end ts)
  11710. ;; Fix next time-stamp before END. TS is the
  11711. ;; list of time-stamps found so far.
  11712. (let ((ts ts)
  11713. (regexp (cond
  11714. ((string= specific "TIMESTAMP")
  11715. org-ts-regexp)
  11716. ((string= specific "TIMESTAMP_IA")
  11717. org-ts-regexp-inactive)
  11718. ((assoc "TIMESTAMP_IA" ts)
  11719. org-ts-regexp)
  11720. ((assoc "TIMESTAMP" ts)
  11721. org-ts-regexp-inactive)
  11722. (t org-ts-regexp-both))))
  11723. (catch 'next
  11724. (while (re-search-forward regexp end t)
  11725. (backward-char)
  11726. (let ((object (org-element-context)))
  11727. ;; Accept to match timestamps in node
  11728. ;; properties, too.
  11729. (when (memq (org-element-type object)
  11730. '(node-property timestamp))
  11731. (let ((type
  11732. (org-element-property :type object)))
  11733. (cond
  11734. ((and (memq type '(active active-range))
  11735. (not (equal specific "TIMESTAMP_IA")))
  11736. (unless (assoc "TIMESTAMP" ts)
  11737. (push (cons "TIMESTAMP"
  11738. (org-element-property
  11739. :raw-value object))
  11740. ts)
  11741. (when specific (throw 'exit ts))))
  11742. ((and (memq type '(inactive inactive-range))
  11743. (not (string= specific "TIMESTAMP")))
  11744. (unless (assoc "TIMESTAMP_IA" ts)
  11745. (push (cons "TIMESTAMP_IA"
  11746. (org-element-property
  11747. :raw-value object))
  11748. ts)
  11749. (when specific (throw 'exit ts))))))
  11750. ;; Both timestamp types are found,
  11751. ;; move to next part.
  11752. (when (= (length ts) 2) (throw 'next ts)))))
  11753. ts)))))
  11754. (goto-char beg)
  11755. ;; First look for timestamps within headline.
  11756. (let ((ts (funcall find-ts (line-end-position) nil)))
  11757. (if (= (length ts) 2) (setq props (nconc ts props))
  11758. ;; Then find timestamps in the section, skipping
  11759. ;; planning line.
  11760. (let ((end (save-excursion (outline-next-heading))))
  11761. (forward-line)
  11762. (when (looking-at-p org-planning-line-re) (forward-line))
  11763. (setq props (nconc (funcall find-ts end ts) props))))))))
  11764. ;; Get the standard properties, like :PROP:.
  11765. (when (memq which '(nil all standard))
  11766. ;; If we are looking after a specific property, delegate
  11767. ;; to `org-entry-get', which is faster. However, make an
  11768. ;; exception for "CATEGORY", since it can be also set
  11769. ;; through keywords (i.e. #+CATEGORY).
  11770. (if (and specific (not (equal specific "CATEGORY")))
  11771. (let ((value (org-entry-get beg specific nil t)))
  11772. (throw 'exit (and value (list (cons specific value)))))
  11773. (let ((range (org-get-property-block beg)))
  11774. (when range
  11775. (let ((end (cdr range)) seen-base)
  11776. (goto-char (car range))
  11777. ;; Unlike to `org--update-property-plist', we
  11778. ;; handle the case where base values is found
  11779. ;; after its extension. We also forbid standard
  11780. ;; properties to be named as special properties.
  11781. (while (re-search-forward org-property-re end t)
  11782. (let* ((key (upcase (match-string-no-properties 2)))
  11783. (extendp (string-match-p "\\+\\'" key))
  11784. (key-base (if extendp (substring key 0 -1) key))
  11785. (value (match-string-no-properties 3)))
  11786. (cond
  11787. ((member-ignore-case key-base org-special-properties))
  11788. (extendp
  11789. (setq props
  11790. (org--update-property-plist key value props)))
  11791. ((member key seen-base))
  11792. (t (push key seen-base)
  11793. (let ((p (assoc-string key props t)))
  11794. (if p (setcdr p (concat value " " (cdr p)))
  11795. (push (cons key value) props))))))))))))
  11796. (unless (assoc "CATEGORY" props)
  11797. (push (cons "CATEGORY" (org-get-category beg)) props)
  11798. (when (string= specific "CATEGORY") (throw 'exit props)))
  11799. ;; Return value.
  11800. props)))))
  11801. (defun org--property-local-values (property literal-nil)
  11802. "Return value for PROPERTY in current entry.
  11803. Value is a list whose car is the base value for PROPERTY and cdr
  11804. a list of accumulated values. Return nil if neither is found in
  11805. the entry. Also return nil when PROPERTY is set to \"nil\",
  11806. unless LITERAL-NIL is non-nil."
  11807. (let ((range (org-get-property-block)))
  11808. (when range
  11809. (goto-char (car range))
  11810. (let* ((case-fold-search t)
  11811. (end (cdr range))
  11812. (value
  11813. ;; Base value.
  11814. (save-excursion
  11815. (let ((v (and (re-search-forward
  11816. (org-re-property property nil t) end t)
  11817. (match-string-no-properties 3))))
  11818. (list (if literal-nil v (org-not-nil v)))))))
  11819. ;; Find additional values.
  11820. (let* ((property+ (org-re-property (concat property "+") nil t)))
  11821. (while (re-search-forward property+ end t)
  11822. (push (match-string-no-properties 3) value)))
  11823. ;; Return final values.
  11824. (and (not (equal value '(nil))) (nreverse value))))))
  11825. (defun org--property-global-or-keyword-value (property literal-nil)
  11826. "Return value for PROPERTY as defined by global properties or by keyword.
  11827. Return value is a string. Return nil if property is not set
  11828. globally or by keyword. Also return nil when PROPERTY is set to
  11829. \"nil\", unless LITERAL-NIL is non-nil."
  11830. (let ((global
  11831. (cdr (or (assoc-string property org-keyword-properties t)
  11832. (assoc-string property org-global-properties t)
  11833. (assoc-string property org-global-properties-fixed t)))))
  11834. (if literal-nil global (org-not-nil global))))
  11835. (defun org-entry-get (pom property &optional inherit literal-nil)
  11836. "Get value of PROPERTY for entry or content at point-or-marker POM.
  11837. If INHERIT is non-nil and the entry does not have the property,
  11838. then also check higher levels of the hierarchy. If INHERIT is
  11839. the symbol `selective', use inheritance only if the setting in
  11840. `org-use-property-inheritance' selects PROPERTY for inheritance.
  11841. If the property is present but empty, the return value is the
  11842. empty string. If the property is not present at all, nil is
  11843. returned. In any other case, return the value as a string.
  11844. Search is case-insensitive.
  11845. If LITERAL-NIL is set, return the string value \"nil\" as
  11846. a string, do not interpret it as the list atom nil. This is used
  11847. for inheritance when a \"nil\" value can supersede a non-nil
  11848. value higher up the hierarchy."
  11849. (org-with-point-at pom
  11850. (cond
  11851. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  11852. ;; We need a special property. Use `org-entry-properties' to
  11853. ;; retrieve it, but specify the wanted property.
  11854. (cdr (assoc-string property (org-entry-properties nil property))))
  11855. ((and inherit
  11856. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  11857. (org-entry-get-with-inheritance property literal-nil))
  11858. (t
  11859. (let* ((local (org--property-local-values property literal-nil))
  11860. (value (and local (mapconcat #'identity (delq nil local) " "))))
  11861. (if literal-nil value (org-not-nil value)))))))
  11862. (defun org-property-or-variable-value (var &optional inherit)
  11863. "Check if there is a property fixing the value of VAR.
  11864. If yes, return this value. If not, return the current value of the variable."
  11865. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  11866. (if (and prop (stringp prop) (string-match "\\S-" prop))
  11867. (read prop)
  11868. (symbol-value var))))
  11869. (defun org-entry-delete (pom property)
  11870. "Delete PROPERTY from entry at point-or-marker POM.
  11871. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  11872. non-nil when a property was removed."
  11873. (org-with-point-at pom
  11874. (pcase (org-get-property-block)
  11875. (`(,begin . ,origin)
  11876. (let* ((end (copy-marker origin))
  11877. (re (org-re-property
  11878. (concat (regexp-quote property) "\\+?") t t)))
  11879. (goto-char begin)
  11880. (while (re-search-forward re end t)
  11881. (delete-region (match-beginning 0) (line-beginning-position 2)))
  11882. ;; If drawer is empty, remove it altogether.
  11883. (when (= begin end)
  11884. (delete-region (line-beginning-position 0)
  11885. (line-beginning-position 2)))
  11886. ;; Return non-nil if some property was removed.
  11887. (prog1 (/= end origin) (set-marker end nil))))
  11888. (_ nil))))
  11889. ;; Multi-values properties are properties that contain multiple values
  11890. ;; These values are assumed to be single words, separated by whitespace.
  11891. (defun org-entry-add-to-multivalued-property (pom property value)
  11892. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  11893. (let* ((old (org-entry-get pom property))
  11894. (values (and old (split-string old))))
  11895. (setq value (org-entry-protect-space value))
  11896. (unless (member value values)
  11897. (setq values (append values (list value)))
  11898. (org-entry-put pom property (mapconcat #'identity values " ")))))
  11899. (defun org-entry-remove-from-multivalued-property (pom property value)
  11900. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  11901. (let* ((old (org-entry-get pom property))
  11902. (values (and old (split-string old))))
  11903. (setq value (org-entry-protect-space value))
  11904. (when (member value values)
  11905. (setq values (delete value values))
  11906. (org-entry-put pom property (mapconcat #'identity values " ")))))
  11907. (defun org-entry-member-in-multivalued-property (pom property value)
  11908. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  11909. (let* ((old (org-entry-get pom property))
  11910. (values (and old (split-string old))))
  11911. (setq value (org-entry-protect-space value))
  11912. (member value values)))
  11913. (defun org-entry-get-multivalued-property (pom property)
  11914. "Return a list of values in a multivalued property."
  11915. (let* ((value (org-entry-get pom property))
  11916. (values (and value (split-string value))))
  11917. (mapcar #'org-entry-restore-space values)))
  11918. (defun org-entry-put-multivalued-property (pom property &rest values)
  11919. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  11920. VALUES should be a list of strings. Spaces will be protected."
  11921. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  11922. (let* ((value (org-entry-get pom property))
  11923. (values (and value (split-string value))))
  11924. (mapcar #'org-entry-restore-space values)))
  11925. (defun org-entry-protect-space (s)
  11926. "Protect spaces and newline in string S."
  11927. (while (string-match " " s)
  11928. (setq s (replace-match "%20" t t s)))
  11929. (while (string-match "\n" s)
  11930. (setq s (replace-match "%0A" t t s)))
  11931. s)
  11932. (defun org-entry-restore-space (s)
  11933. "Restore spaces and newline in string S."
  11934. (while (string-match "%20" s)
  11935. (setq s (replace-match " " t t s)))
  11936. (while (string-match "%0A" s)
  11937. (setq s (replace-match "\n" t t s)))
  11938. s)
  11939. (defvar org-entry-property-inherited-from (make-marker)
  11940. "Marker pointing to the entry from where a property was inherited.
  11941. Each call to `org-entry-get-with-inheritance' will set this marker to the
  11942. location of the entry where the inheritance search matched. If there was
  11943. no match, the marker will point nowhere.
  11944. Note that also `org-entry-get' calls this function, if the INHERIT flag
  11945. is set.")
  11946. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  11947. "Get PROPERTY of entry or content at point, search higher levels if needed.
  11948. The search will stop at the first ancestor which has the property defined.
  11949. If the value found is \"nil\", return nil to show that the property
  11950. should be considered as undefined (this is the meaning of nil here).
  11951. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  11952. (move-marker org-entry-property-inherited-from nil)
  11953. (org-with-wide-buffer
  11954. (let (value)
  11955. (catch 'exit
  11956. (while t
  11957. (let ((v (org--property-local-values property literal-nil)))
  11958. (when v
  11959. (setq value
  11960. (concat (mapconcat #'identity (delq nil v) " ")
  11961. (and value " ")
  11962. value)))
  11963. (cond
  11964. ((car v)
  11965. (org-back-to-heading-or-point-min t)
  11966. (move-marker org-entry-property-inherited-from (point))
  11967. (throw 'exit nil))
  11968. ((org-up-heading-or-point-min))
  11969. (t
  11970. (let ((global (org--property-global-or-keyword-value property literal-nil)))
  11971. (cond ((not global))
  11972. (value (setq value (concat global " " value)))
  11973. (t (setq value global))))
  11974. (throw 'exit nil))))))
  11975. (if literal-nil value (org-not-nil value)))))
  11976. (defvar org-property-changed-functions nil
  11977. "Hook called when the value of a property has changed.
  11978. Each hook function should accept two arguments, the name of the property
  11979. and the new value.")
  11980. (defun org-entry-put (pom property value)
  11981. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  11982. If the value is nil, it is converted to the empty string. If it
  11983. is not a string, an error is raised. Also raise an error on
  11984. invalid property names.
  11985. PROPERTY can be any regular property (see
  11986. `org-special-properties'). It can also be \"TODO\",
  11987. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  11988. For the last two properties, VALUE may have any of the special
  11989. values \"earlier\" and \"later\". The function then increases or
  11990. decreases scheduled or deadline date by one day."
  11991. (cond ((null value) (setq value ""))
  11992. ((not (stringp value)) (error "Properties values should be strings"))
  11993. ((not (org--valid-property-p property))
  11994. (user-error "Invalid property name: \"%s\"" property)))
  11995. (org-no-read-only
  11996. (org-with-point-at pom
  11997. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  11998. (org-back-to-heading-or-point-min t)
  11999. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  12000. (let ((beg (point)))
  12001. (cond
  12002. ((equal property "TODO")
  12003. (cond ((not (org-string-nw-p value)) (setq value 'none))
  12004. ((not (member value org-todo-keywords-1))
  12005. (user-error "\"%s\" is not a valid TODO state" value)))
  12006. (org-todo value)
  12007. (org-align-tags))
  12008. ((equal property "PRIORITY")
  12009. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  12010. (org-align-tags))
  12011. ((equal property "SCHEDULED")
  12012. (forward-line)
  12013. (if (and (looking-at-p org-planning-line-re)
  12014. (re-search-forward
  12015. org-scheduled-time-regexp (line-end-position) t))
  12016. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  12017. ((string= value "later") (org-timestamp-change 1 'day))
  12018. ((string= value "") (org-schedule '(4)))
  12019. (t (org-schedule nil value)))
  12020. (if (member value '("earlier" "later" ""))
  12021. (call-interactively #'org-schedule)
  12022. (org-schedule nil value))))
  12023. ((equal property "DEADLINE")
  12024. (forward-line)
  12025. (if (and (looking-at-p org-planning-line-re)
  12026. (re-search-forward
  12027. org-deadline-time-regexp (line-end-position) t))
  12028. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  12029. ((string= value "later") (org-timestamp-change 1 'day))
  12030. ((string= value "") (org-deadline '(4)))
  12031. (t (org-deadline nil value)))
  12032. (if (member value '("earlier" "later" ""))
  12033. (call-interactively #'org-deadline)
  12034. (org-deadline nil value))))
  12035. ((member property org-special-properties)
  12036. (error "The %s property cannot be set with `org-entry-put'" property))
  12037. (t
  12038. (let* ((range (org-get-property-block beg 'force))
  12039. (end (cdr range))
  12040. (case-fold-search t))
  12041. (goto-char (car range))
  12042. (if (re-search-forward (org-re-property property nil t) end t)
  12043. (progn (delete-region (match-beginning 0) (match-end 0))
  12044. (goto-char (match-beginning 0)))
  12045. (goto-char end)
  12046. (insert "\n")
  12047. (backward-char))
  12048. (insert ":" property ":")
  12049. (when value (insert " " value))
  12050. (org-indent-line)))))
  12051. (run-hook-with-args 'org-property-changed-functions property value))))
  12052. (defun org-buffer-property-keys (&optional specials defaults columns)
  12053. "Get all property keys in the current buffer.
  12054. When SPECIALS is non-nil, also list the special properties that
  12055. reflect things like tags and TODO state.
  12056. When DEFAULTS is non-nil, also include properties that has
  12057. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  12058. DESCRIPTION, LOCATION, and LOGGING and others.
  12059. When COLUMNS in non-nil, also include property names given in
  12060. COLUMN formats in the current buffer."
  12061. (let ((case-fold-search t)
  12062. (props (append
  12063. (and specials org-special-properties)
  12064. (and defaults (cons org-effort-property org-default-properties))
  12065. ;; Get property names from #+PROPERTY keywords as well
  12066. (mapcar (lambda (s)
  12067. (nth 0 (split-string s)))
  12068. (cdar (org-collect-keywords '("PROPERTY")))))))
  12069. (org-with-wide-buffer
  12070. (goto-char (point-min))
  12071. (while (re-search-forward org-property-start-re nil t)
  12072. (catch :skip
  12073. (let ((range (org-get-property-block)))
  12074. (unless range (throw :skip nil))
  12075. (goto-char (car range))
  12076. (let ((begin (car range))
  12077. (end (cdr range)))
  12078. ;; Make sure that found property block is not located
  12079. ;; before current point, as it would generate an infloop.
  12080. ;; It can happen, for example, in the following
  12081. ;; situation:
  12082. ;;
  12083. ;; * Headline
  12084. ;; :PROPERTIES:
  12085. ;; ...
  12086. ;; :END:
  12087. ;; *************** Inlinetask
  12088. ;; #+BEGIN_EXAMPLE
  12089. ;; :PROPERTIES:
  12090. ;; #+END_EXAMPLE
  12091. ;;
  12092. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  12093. (while (< (point) end)
  12094. (let ((p (progn (looking-at org-property-re)
  12095. (match-string-no-properties 2))))
  12096. ;; Only add true property name, not extension symbol.
  12097. (push (if (not (string-match-p "\\+\\'" p)) p
  12098. (substring p 0 -1))
  12099. props))
  12100. (forward-line))))
  12101. (outline-next-heading)))
  12102. (when columns
  12103. (goto-char (point-min))
  12104. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  12105. (let ((element (org-element-at-point)))
  12106. (when (memq (org-element-type element) '(keyword node-property))
  12107. (let ((value (org-element-property :value element))
  12108. (start 0))
  12109. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  12110. \\(?:{[^}]+}\\)?"
  12111. value start)
  12112. (setq start (match-end 0))
  12113. (let ((p (match-string-no-properties 1 value)))
  12114. (unless (member-ignore-case p org-special-properties)
  12115. (push p props))))))))))
  12116. (sort (delete-dups
  12117. (append props
  12118. ;; for each xxx_ALL property, make sure the bare
  12119. ;; xxx property is also included
  12120. (delq nil (mapcar (lambda (p)
  12121. (and (string-match-p "._ALL\\'" p)
  12122. (substring p 0 -4)))
  12123. props))))
  12124. (lambda (a b) (string< (upcase a) (upcase b))))))
  12125. (defun org-property-values (key)
  12126. "List all non-nil values of property KEY in current buffer."
  12127. (org-with-wide-buffer
  12128. (goto-char (point-min))
  12129. (let ((case-fold-search t)
  12130. (re (org-re-property key))
  12131. values)
  12132. (while (re-search-forward re nil t)
  12133. (push (org-entry-get (point) key) values))
  12134. (delete-dups values))))
  12135. (defun org-insert-property-drawer ()
  12136. "Insert a property drawer into the current entry.
  12137. Do nothing if the drawer already exists. The newly created
  12138. drawer is immediately hidden."
  12139. (org-with-wide-buffer
  12140. ;; Set point to the position where the drawer should be inserted.
  12141. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  12142. (org-back-to-heading-or-point-min t)
  12143. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  12144. (if (org-before-first-heading-p)
  12145. (while (and (org-at-comment-p) (bolp)) (forward-line))
  12146. (progn
  12147. (forward-line)
  12148. (when (looking-at-p org-planning-line-re) (forward-line))))
  12149. (unless (looking-at-p org-property-drawer-re)
  12150. ;; Make sure we start editing a line from current entry, not from
  12151. ;; next one. It prevents extending text properties or overlays
  12152. ;; belonging to the latter.
  12153. (when (and (bolp) (> (point) (point-min))) (backward-char))
  12154. (let ((begin (if (bobp) (point) (1+ (point))))
  12155. (inhibit-read-only t))
  12156. (unless (bobp) (insert "\n"))
  12157. (insert ":PROPERTIES:\n:END:")
  12158. (org-flag-region (line-end-position 0) (point) t 'outline)
  12159. (when (or (eobp) (= begin (point-min))) (insert "\n"))
  12160. (org-indent-region begin (point))))))
  12161. (defun org-insert-drawer (&optional arg drawer)
  12162. "Insert a drawer at point.
  12163. When optional argument ARG is non-nil, insert a property drawer.
  12164. Optional argument DRAWER, when non-nil, is a string representing
  12165. drawer's name. Otherwise, the user is prompted for a name.
  12166. If a region is active, insert the drawer around that region
  12167. instead.
  12168. Point is left between drawer's boundaries."
  12169. (interactive "P")
  12170. (let* ((drawer (if arg "PROPERTIES"
  12171. (or drawer (read-from-minibuffer "Drawer: ")))))
  12172. (cond
  12173. ;; With C-u, fall back on `org-insert-property-drawer'
  12174. (arg (org-insert-property-drawer))
  12175. ;; Check validity of suggested drawer's name.
  12176. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  12177. (user-error "Invalid drawer name"))
  12178. ;; With an active region, insert a drawer at point.
  12179. ((not (org-region-active-p))
  12180. (progn
  12181. (unless (bolp) (insert "\n"))
  12182. (insert (format ":%s:\n\n:END:\n" drawer))
  12183. (forward-line -2)))
  12184. ;; Otherwise, insert the drawer at point
  12185. (t
  12186. (let ((rbeg (region-beginning))
  12187. (rend (copy-marker (region-end))))
  12188. (unwind-protect
  12189. (progn
  12190. (goto-char rbeg)
  12191. (beginning-of-line)
  12192. (when (save-excursion
  12193. (re-search-forward org-outline-regexp-bol rend t))
  12194. (user-error "Drawers cannot contain headlines"))
  12195. ;; Position point at the beginning of the first
  12196. ;; non-blank line in region. Insert drawer's opening
  12197. ;; there, then indent it.
  12198. (org-skip-whitespace)
  12199. (beginning-of-line)
  12200. (insert ":" drawer ":\n")
  12201. (forward-line -1)
  12202. (indent-for-tab-command)
  12203. ;; Move point to the beginning of the first blank line
  12204. ;; after the last non-blank line in region. Insert
  12205. ;; drawer's closing, then indent it.
  12206. (goto-char rend)
  12207. (skip-chars-backward " \r\t\n")
  12208. (insert "\n:END:")
  12209. (deactivate-mark t)
  12210. (indent-for-tab-command)
  12211. (unless (eolp) (insert "\n")))
  12212. ;; Clear marker, whatever the outcome of insertion is.
  12213. (set-marker rend nil)))))))
  12214. (defvar org-property-set-functions-alist nil
  12215. "Property set function alist.
  12216. Each entry should have the following format:
  12217. (PROPERTY . READ-FUNCTION)
  12218. The read function will be called with the same argument as
  12219. `org-completing-read'.")
  12220. (defun org-set-property-function (property)
  12221. "Get the function that should be used to set PROPERTY.
  12222. This is computed according to `org-property-set-functions-alist'."
  12223. (or (cdr (assoc property org-property-set-functions-alist))
  12224. 'org-completing-read))
  12225. (defun org-read-property-value (property &optional pom default)
  12226. "Read value for PROPERTY, as a string.
  12227. When optional argument POM is non-nil, completion uses additional
  12228. information, i.e., allowed or existing values at point or marker
  12229. POM.
  12230. Optional argument DEFAULT provides a default value for PROPERTY."
  12231. (let* ((completion-ignore-case t)
  12232. (allowed
  12233. (or (org-property-get-allowed-values nil property 'table)
  12234. (and pom (org-property-get-allowed-values pom property 'table))))
  12235. (current (org-entry-get nil property))
  12236. (prompt (format "%s value%s: "
  12237. property
  12238. (if (org-string-nw-p current)
  12239. (format " [%s]" current)
  12240. "")))
  12241. (set-function (org-set-property-function property)))
  12242. (org-trim
  12243. (if allowed
  12244. (funcall set-function
  12245. prompt allowed nil
  12246. (not (get-text-property 0 'org-unrestricted (caar allowed)))
  12247. default nil default)
  12248. (let ((all (mapcar #'list
  12249. (append (org-property-values property)
  12250. (and pom
  12251. (org-with-point-at pom
  12252. (org-property-values property)))))))
  12253. (funcall set-function prompt all nil nil "" nil current))))))
  12254. (defvar org-last-set-property nil)
  12255. (defvar org-last-set-property-value nil)
  12256. (defun org-read-property-name ()
  12257. "Read a property name."
  12258. (let ((completion-ignore-case t)
  12259. (default-prop (or (and (org-at-property-p)
  12260. (match-string-no-properties 2))
  12261. org-last-set-property)))
  12262. (org-completing-read
  12263. (concat "Property"
  12264. (if default-prop (concat " [" default-prop "]") "")
  12265. ": ")
  12266. (mapcar #'list (org-buffer-property-keys nil t t))
  12267. nil nil nil nil default-prop)))
  12268. (defun org-set-property-and-value (use-last)
  12269. "Allow to set [PROPERTY]: [value] direction from prompt.
  12270. When use-default, don't even ask, just use the last
  12271. \"[PROPERTY]: [value]\" string from the history."
  12272. (interactive "P")
  12273. (let* ((completion-ignore-case t)
  12274. (pv (or (and use-last org-last-set-property-value)
  12275. (org-completing-read
  12276. "Enter a \"[Property]: [value]\" pair: "
  12277. nil nil nil nil nil
  12278. org-last-set-property-value)))
  12279. prop val)
  12280. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  12281. (setq prop (match-string 1 pv)
  12282. val (match-string 2 pv))
  12283. (org-set-property prop val))))
  12284. (defun org-set-property (property value)
  12285. "In the current entry, set PROPERTY to VALUE.
  12286. When called interactively, this will prompt for a property name, offering
  12287. completion on existing and default properties. And then it will prompt
  12288. for a value, offering completion either on allowed values (via an inherited
  12289. xxx_ALL property) or on existing values in other instances of this property
  12290. in the current file.
  12291. Throw an error when trying to set a property with an invalid name."
  12292. (interactive (list nil nil))
  12293. (let ((property (or property (org-read-property-name))))
  12294. ;; `org-entry-put' also makes the following check, but this one
  12295. ;; avoids polluting `org-last-set-property' and
  12296. ;; `org-last-set-property-value' needlessly.
  12297. (unless (org--valid-property-p property)
  12298. (user-error "Invalid property name: \"%s\"" property))
  12299. (let ((value (or value (org-read-property-value property)))
  12300. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  12301. (setq org-last-set-property property)
  12302. (setq org-last-set-property-value (concat property ": " value))
  12303. ;; Possibly postprocess the inserted value:
  12304. (when fn (setq value (funcall fn value)))
  12305. (unless (equal (org-entry-get nil property) value)
  12306. (org-entry-put nil property value)))))
  12307. (defun org-find-property (property &optional value)
  12308. "Find first entry in buffer that sets PROPERTY.
  12309. When optional argument VALUE is non-nil, only consider an entry
  12310. if it contains PROPERTY set to this value. If PROPERTY should be
  12311. explicitly set to nil, use string \"nil\" for VALUE.
  12312. Return position where the entry begins, or nil if there is no
  12313. such entry. If narrowing is in effect, only search the visible
  12314. part of the buffer."
  12315. (save-excursion
  12316. (goto-char (point-min))
  12317. (let ((case-fold-search t)
  12318. (re (org-re-property property nil (not value) value)))
  12319. (catch 'exit
  12320. (while (re-search-forward re nil t)
  12321. (when (if value (org-at-property-p)
  12322. (org-entry-get (point) property nil t))
  12323. (throw 'exit (progn (org-back-to-heading-or-point-min t)
  12324. (point)))))))))
  12325. (defun org-delete-property (property)
  12326. "In the current entry, delete PROPERTY."
  12327. (interactive
  12328. (let* ((completion-ignore-case t)
  12329. (cat (org-entry-get (point) "CATEGORY"))
  12330. (props0 (org-entry-properties nil 'standard))
  12331. (props (if cat props0
  12332. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  12333. (prop (if (< 1 (length props))
  12334. (completing-read "Property: " props nil t)
  12335. (caar props))))
  12336. (list prop)))
  12337. (if (not property)
  12338. (message "No property to delete in this entry")
  12339. (org-entry-delete nil property)
  12340. (message "Property \"%s\" deleted" property)))
  12341. (defun org-delete-property-globally (property)
  12342. "Remove PROPERTY globally, from all entries.
  12343. This function ignores narrowing, if any."
  12344. (interactive
  12345. (let* ((completion-ignore-case t)
  12346. (prop (completing-read
  12347. "Globally remove property: "
  12348. (mapcar #'list (org-buffer-property-keys)))))
  12349. (list prop)))
  12350. (org-with-wide-buffer
  12351. (goto-char (point-min))
  12352. (let ((count 0)
  12353. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  12354. (while (re-search-forward re nil t)
  12355. (when (org-entry-delete (point) property) (cl-incf count)))
  12356. (message "Property \"%s\" removed from %d entries" property count))))
  12357. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  12358. (defun org-compute-property-at-point ()
  12359. "Compute the property at point.
  12360. This looks for an enclosing column format, extracts the operator and
  12361. then applies it to the property in the column format's scope."
  12362. (interactive)
  12363. (unless (org-at-property-p)
  12364. (user-error "Not at a property"))
  12365. (let ((prop (match-string-no-properties 2)))
  12366. (org-columns-get-format-and-top-level)
  12367. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  12368. (user-error "No operator defined for property %s" prop))
  12369. (org-columns-compute prop)))
  12370. (defvar org-property-allowed-value-functions nil
  12371. "Hook for functions supplying allowed values for a specific property.
  12372. The functions must take a single argument, the name of the property, and
  12373. return a flat list of allowed values. If \":ETC\" is one of
  12374. the values, this means that these values are intended as defaults for
  12375. completion, but that other values should be allowed too.
  12376. The functions must return nil if they are not responsible for this
  12377. property.")
  12378. (defun org-property-get-allowed-values (pom property &optional table)
  12379. "Get allowed values for the property PROPERTY.
  12380. When TABLE is non-nil, return an alist that can directly be used for
  12381. completion."
  12382. (let (vals)
  12383. (cond
  12384. ((equal property "TODO")
  12385. (setq vals (org-with-point-at pom
  12386. (append org-todo-keywords-1 '("")))))
  12387. ((equal property "PRIORITY")
  12388. (let ((n org-priority-lowest))
  12389. (while (>= n org-priority-highest)
  12390. (push (char-to-string n) vals)
  12391. (setq n (1- n)))))
  12392. ((equal property "CATEGORY"))
  12393. ((member property org-special-properties))
  12394. ((setq vals (run-hook-with-args-until-success
  12395. 'org-property-allowed-value-functions property)))
  12396. (t
  12397. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  12398. (when (and vals (string-match "\\S-" vals))
  12399. (setq vals (car (read-from-string (concat "(" vals ")"))))
  12400. (setq vals (mapcar (lambda (x)
  12401. (cond ((stringp x) x)
  12402. ((numberp x) (number-to-string x))
  12403. ((symbolp x) (symbol-name x))
  12404. (t "???")))
  12405. vals)))))
  12406. (when (member ":ETC" vals)
  12407. (setq vals (remove ":ETC" vals))
  12408. (org-add-props (car vals) '(org-unrestricted t)))
  12409. (if table (mapcar 'list vals) vals)))
  12410. (defun org-property-previous-allowed-value (&optional _previous)
  12411. "Switch to the next allowed value for this property."
  12412. (interactive)
  12413. (org-property-next-allowed-value t))
  12414. (defun org-property-next-allowed-value (&optional previous)
  12415. "Switch to the next allowed value for this property."
  12416. (interactive)
  12417. (unless (org-at-property-p)
  12418. (user-error "Not at a property"))
  12419. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  12420. (key (match-string 2))
  12421. (value (match-string 3))
  12422. (allowed (or (org-property-get-allowed-values (point) key)
  12423. (and (member value '("[ ]" "[-]" "[X]"))
  12424. '("[ ]" "[X]"))))
  12425. (heading (save-match-data (nth 4 (org-heading-components))))
  12426. nval)
  12427. (unless allowed
  12428. (user-error "Allowed values for this property have not been defined"))
  12429. (when previous (setq allowed (reverse allowed)))
  12430. (when (member value allowed)
  12431. (setq nval (car (cdr (member value allowed)))))
  12432. (setq nval (or nval (car allowed)))
  12433. (when (equal nval value)
  12434. (user-error "Only one allowed value for this property"))
  12435. (org-at-property-p)
  12436. (replace-match (concat " :" key ": " nval) t t)
  12437. (org-indent-line)
  12438. (beginning-of-line 1)
  12439. (skip-chars-forward " \t")
  12440. (when (equal prop org-effort-property)
  12441. (org-refresh-property
  12442. '((effort . identity)
  12443. (effort-minutes . org-duration-to-minutes))
  12444. nval)
  12445. (when (string= org-clock-current-task heading)
  12446. (setq org-clock-effort nval)
  12447. (org-clock-update-mode-line)))
  12448. (run-hook-with-args 'org-property-changed-functions key nval)))
  12449. (defun org-find-olp (path &optional this-buffer)
  12450. "Return a marker pointing to the entry at outline path OLP.
  12451. If anything goes wrong, throw an error, and if you need to do
  12452. something based on this error, you can catch it with
  12453. `condition-case'.
  12454. If THIS-BUFFER is set, the outline path does not contain a file,
  12455. only headings."
  12456. (let* ((file (if this-buffer buffer-file-name (pop path)))
  12457. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  12458. (level 1)
  12459. (lmin 1)
  12460. (lmax 1)
  12461. end found flevel)
  12462. (unless buffer (error "File not found :%s" file))
  12463. (with-current-buffer buffer
  12464. (unless (derived-mode-p 'org-mode)
  12465. (error "Buffer %s needs to be in Org mode" buffer))
  12466. (org-with-wide-buffer
  12467. (goto-char (point-min))
  12468. (dolist (heading path)
  12469. (let ((re (format org-complex-heading-regexp-format
  12470. (regexp-quote heading)))
  12471. (cnt 0))
  12472. (while (re-search-forward re end t)
  12473. (setq level (- (match-end 1) (match-beginning 1)))
  12474. (when (and (>= level lmin) (<= level lmax))
  12475. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  12476. (when (= cnt 0)
  12477. (error "Heading not found on level %d: %s" lmax heading))
  12478. (when (> cnt 1)
  12479. (error "Heading not unique on level %d: %s" lmax heading))
  12480. (goto-char found)
  12481. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  12482. (setq end (save-excursion (org-end-of-subtree t t)))))
  12483. (when (org-at-heading-p)
  12484. (point-marker))))))
  12485. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  12486. "Find node HEADING in BUFFER.
  12487. Return a marker to the heading if it was found, or nil if not.
  12488. If POS-ONLY is set, return just the position instead of a marker.
  12489. The heading text must match exact, but it may have a TODO keyword,
  12490. a priority cookie and tags in the standard locations."
  12491. (with-current-buffer (or buffer (current-buffer))
  12492. (org-with-wide-buffer
  12493. (goto-char (point-min))
  12494. (let (case-fold-search)
  12495. (when (re-search-forward
  12496. (format org-complex-heading-regexp-format
  12497. (regexp-quote heading)) nil t)
  12498. (if pos-only
  12499. (match-beginning 0)
  12500. (move-marker (make-marker) (match-beginning 0))))))))
  12501. (defun org-find-exact-heading-in-directory (heading &optional dir)
  12502. "Find Org node headline HEADING in all \".org\" files in directory DIR.
  12503. When the target headline is found, return a marker to this location."
  12504. (let ((files (directory-files (or dir default-directory)
  12505. t "\\`[^.#].*\\.org\\'"))
  12506. visiting m buffer)
  12507. (catch 'found
  12508. (dolist (file files)
  12509. (message "trying %s" file)
  12510. (setq visiting (org-find-base-buffer-visiting file))
  12511. (setq buffer (or visiting (find-file-noselect file)))
  12512. (setq m (org-find-exact-headline-in-buffer
  12513. heading buffer))
  12514. (when (and (not m) (not visiting)) (kill-buffer buffer))
  12515. (and m (throw 'found m))))))
  12516. (defun org-find-entry-with-id (ident)
  12517. "Locate the entry that contains the ID property with exact value IDENT.
  12518. IDENT can be a string, a symbol or a number, this function will search for
  12519. the string representation of it.
  12520. Return the position where this entry starts, or nil if there is no such entry."
  12521. (interactive "sID: ")
  12522. (let ((id (cond
  12523. ((stringp ident) ident)
  12524. ((symbolp ident) (symbol-name ident))
  12525. ((numberp ident) (number-to-string ident))
  12526. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  12527. (org-with-wide-buffer (org-find-property "ID" id))))
  12528. ;;;; Timestamps
  12529. (defvar org-last-changed-timestamp nil)
  12530. (defvar org-last-inserted-timestamp nil
  12531. "The last time stamp inserted with `org-insert-time-stamp'.")
  12532. (defun org-time-stamp (arg &optional inactive)
  12533. "Prompt for a date/time and insert a time stamp.
  12534. If the user specifies a time like HH:MM or if this command is
  12535. called with at least one prefix argument, the time stamp contains
  12536. the date and the time. Otherwise, only the date is included.
  12537. All parts of a date not specified by the user are filled in from
  12538. the timestamp at point, if any, or the current date/time
  12539. otherwise.
  12540. If there is already a timestamp at the cursor, it is replaced.
  12541. With two universal prefix arguments, insert an active timestamp
  12542. with the current time without prompting the user.
  12543. When called from Lisp, the timestamp is inactive if INACTIVE is
  12544. non-nil."
  12545. (interactive "P")
  12546. (let* ((ts (cond
  12547. ((org-at-date-range-p t)
  12548. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  12549. ((org-at-timestamp-p 'lax) (match-string 0))))
  12550. ;; Default time is either the timestamp at point or today.
  12551. ;; When entering a range, only the range start is considered.
  12552. (default-time (and ts (org-time-string-to-time ts)))
  12553. (default-input (and ts (org-get-compact-tod ts)))
  12554. (repeater (and ts
  12555. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  12556. (match-string 0 ts)))
  12557. org-time-was-given
  12558. org-end-time-was-given
  12559. (time
  12560. (if (equal arg '(16)) (current-time)
  12561. ;; Preserve `this-command' and `last-command'.
  12562. (let ((this-command this-command)
  12563. (last-command last-command))
  12564. (org-read-date
  12565. arg 'totime nil nil default-time default-input
  12566. inactive)))))
  12567. (cond
  12568. ((and ts
  12569. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  12570. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  12571. (insert "--")
  12572. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  12573. (ts
  12574. ;; Make sure we're on a timestamp. When in the middle of a date
  12575. ;; range, move arbitrarily to range end.
  12576. (unless (org-at-timestamp-p 'lax)
  12577. (skip-chars-forward "-")
  12578. (org-at-timestamp-p 'lax))
  12579. (replace-match "")
  12580. (setq org-last-changed-timestamp
  12581. (org-insert-time-stamp
  12582. time (or org-time-was-given arg)
  12583. inactive nil nil (list org-end-time-was-given)))
  12584. (when repeater
  12585. (backward-char)
  12586. (insert " " repeater)
  12587. (setq org-last-changed-timestamp
  12588. (concat (substring org-last-inserted-timestamp 0 -1)
  12589. " " repeater ">")))
  12590. (message "Timestamp updated"))
  12591. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  12592. (t (org-insert-time-stamp
  12593. time (or org-time-was-given arg) inactive nil nil
  12594. (list org-end-time-was-given))))))
  12595. ;; FIXME: can we use this for something else, like computing time differences?
  12596. (defun org-get-compact-tod (s)
  12597. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  12598. (let* ((t1 (match-string 1 s))
  12599. (h1 (string-to-number (match-string 2 s)))
  12600. (m1 (string-to-number (match-string 3 s)))
  12601. (t2 (and (match-end 4) (match-string 5 s)))
  12602. (h2 (and t2 (string-to-number (match-string 6 s))))
  12603. (m2 (and t2 (string-to-number (match-string 7 s))))
  12604. dh dm)
  12605. (if (not t2)
  12606. t1
  12607. (setq dh (- h2 h1) dm (- m2 m1))
  12608. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  12609. (concat t1 "+" (number-to-string dh)
  12610. (and (/= 0 dm) (format ":%02d" dm)))))))
  12611. (defun org-time-stamp-inactive (&optional arg)
  12612. "Insert an inactive time stamp.
  12613. An inactive time stamp is enclosed in square brackets instead of
  12614. angle brackets. It is inactive in the sense that it does not
  12615. trigger agenda entries. So these are more for recording a
  12616. certain time/date.
  12617. If the user specifies a time like HH:MM or if this command is called with
  12618. at least one prefix argument, the time stamp contains the date and the time.
  12619. Otherwise, only the date is included.
  12620. When called with two universal prefix arguments, insert an inactive time stamp
  12621. with the current time without prompting the user."
  12622. (interactive "P")
  12623. (org-time-stamp arg 'inactive))
  12624. (defvar org-date-ovl (make-overlay 1 1))
  12625. (overlay-put org-date-ovl 'face 'org-date-selected)
  12626. (delete-overlay org-date-ovl)
  12627. (defvar org-ans1) ; dynamically scoped parameter
  12628. (defvar org-ans2) ; dynamically scoped parameter
  12629. (defvar org-plain-time-of-day-regexp) ; defined below
  12630. (defvar org-overriding-default-time nil) ; dynamically scoped
  12631. (defvar org-read-date-overlay nil)
  12632. (defvar org-read-date-history nil)
  12633. (defvar org-read-date-final-answer nil)
  12634. (defvar org-read-date-analyze-futurep nil)
  12635. (defvar org-read-date-analyze-forced-year nil)
  12636. (defvar org-read-date-inactive)
  12637. (defvar org-def)
  12638. (defvar org-defdecode)
  12639. (defvar org-with-time)
  12640. (defvar calendar-setup) ; Dynamically scoped.
  12641. (defun org-read-date (&optional with-time to-time from-string prompt
  12642. default-time default-input inactive)
  12643. "Read a date, possibly a time, and make things smooth for the user.
  12644. The prompt will suggest to enter an ISO date, but you can also enter anything
  12645. which will at least partially be understood by `parse-time-string'.
  12646. Unrecognized parts of the date will default to the current day, month, year,
  12647. hour and minute. If this command is called to replace a timestamp at point,
  12648. or to enter the second timestamp of a range, the default time is taken
  12649. from the existing stamp. Furthermore, the command prefers the future,
  12650. so if you are giving a date where the year is not given, and the day-month
  12651. combination is already past in the current year, it will assume you
  12652. mean next year. For details, see the manual. A few examples:
  12653. 3-2-5 --> 2003-02-05
  12654. feb 15 --> currentyear-02-15
  12655. 2/15 --> currentyear-02-15
  12656. sep 12 9 --> 2009-09-12
  12657. 12:45 --> today 12:45
  12658. 22 sept 0:34 --> currentyear-09-22 0:34
  12659. 12 --> currentyear-currentmonth-12
  12660. Fri --> nearest Friday after today
  12661. -Tue --> last Tuesday
  12662. etc.
  12663. Furthermore you can specify a relative date by giving, as the *first* thing
  12664. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  12665. change in days weeks, months, years.
  12666. With a single plus or minus, the date is relative to today. With a double
  12667. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  12668. +4d --> four days from today
  12669. +4 --> same as above
  12670. +2w --> two weeks from today
  12671. ++5 --> five days from default date
  12672. The function understands only English month and weekday abbreviations.
  12673. While prompting, a calendar is popped up - you can also select the
  12674. date with the mouse (button 1). The calendar shows a period of three
  12675. months. To scroll it to other months, use the keys `>' and `<'.
  12676. If you don't like the calendar, turn it off with
  12677. (setq org-read-date-popup-calendar nil)
  12678. With optional argument TO-TIME, the date will immediately be converted
  12679. to an internal time.
  12680. With an optional argument WITH-TIME, the prompt will suggest to
  12681. also insert a time. Note that when WITH-TIME is not set, you can
  12682. still enter a time, and this function will inform the calling routine
  12683. about this change. The calling routine may then choose to change the
  12684. format used to insert the time stamp into the buffer to include the time.
  12685. With optional argument FROM-STRING, read from this string instead from
  12686. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  12687. the time/date that is used for everything that is not specified by the
  12688. user."
  12689. (require 'parse-time)
  12690. (let* ((org-with-time with-time)
  12691. (org-time-stamp-rounding-minutes
  12692. (if (equal org-with-time '(16))
  12693. '(0 0)
  12694. org-time-stamp-rounding-minutes))
  12695. (ct (org-current-time))
  12696. (org-def (or org-overriding-default-time default-time ct))
  12697. (org-defdecode (decode-time org-def))
  12698. (cur-frame (selected-frame))
  12699. (mouse-autoselect-window nil) ; Don't let the mouse jump
  12700. (calendar-setup
  12701. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  12702. (calendar-move-hook nil)
  12703. (calendar-view-diary-initially-flag nil)
  12704. (calendar-view-holidays-initially-flag nil)
  12705. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  12706. ;; Rationalize `org-def' and `org-defdecode', if required.
  12707. (when (< (nth 2 org-defdecode) org-extend-today-until)
  12708. (setf (nth 2 org-defdecode) -1)
  12709. (setf (nth 1 org-defdecode) 59)
  12710. (setq org-def (apply #'encode-time org-defdecode))
  12711. (setq org-defdecode (decode-time org-def)))
  12712. (let* ((timestr (format-time-string
  12713. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  12714. org-def))
  12715. (prompt (concat (if prompt (concat prompt " ") "")
  12716. (format "Date+time [%s]: " timestr))))
  12717. (cond
  12718. (from-string (setq ans from-string))
  12719. (org-read-date-popup-calendar
  12720. (save-excursion
  12721. (save-window-excursion
  12722. (calendar)
  12723. (when (eq calendar-setup 'calendar-only)
  12724. (setq cal-frame
  12725. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  12726. (select-frame cal-frame))
  12727. (org-eval-in-calendar '(setq cursor-type nil) t)
  12728. (unwind-protect
  12729. (progn
  12730. (calendar-forward-day (- (time-to-days org-def)
  12731. (calendar-absolute-from-gregorian
  12732. (calendar-current-date))))
  12733. (org-eval-in-calendar nil t)
  12734. (let* ((old-map (current-local-map))
  12735. (map (copy-keymap calendar-mode-map))
  12736. (minibuffer-local-map
  12737. (copy-keymap org-read-date-minibuffer-local-map)))
  12738. (org-defkey map (kbd "RET") 'org-calendar-select)
  12739. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  12740. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  12741. (unwind-protect
  12742. (progn
  12743. (use-local-map map)
  12744. (setq org-read-date-inactive inactive)
  12745. (add-hook 'post-command-hook 'org-read-date-display)
  12746. (setq org-ans0
  12747. (read-string prompt
  12748. default-input
  12749. 'org-read-date-history
  12750. nil))
  12751. ;; org-ans0: from prompt
  12752. ;; org-ans1: from mouse click
  12753. ;; org-ans2: from calendar motion
  12754. (setq ans
  12755. (concat org-ans0 " " (or org-ans1 org-ans2))))
  12756. (remove-hook 'post-command-hook 'org-read-date-display)
  12757. (use-local-map old-map)
  12758. (when org-read-date-overlay
  12759. (delete-overlay org-read-date-overlay)
  12760. (setq org-read-date-overlay nil)))))
  12761. (bury-buffer "*Calendar*")
  12762. (when cal-frame
  12763. (delete-frame cal-frame)
  12764. (select-frame-set-input-focus cur-frame))))))
  12765. (t ; Naked prompt only
  12766. (unwind-protect
  12767. (setq ans (read-string prompt default-input
  12768. 'org-read-date-history timestr))
  12769. (when org-read-date-overlay
  12770. (delete-overlay org-read-date-overlay)
  12771. (setq org-read-date-overlay nil))))))
  12772. (setq final (org-read-date-analyze ans org-def org-defdecode))
  12773. (when org-read-date-analyze-forced-year
  12774. (message "Year was forced into %s"
  12775. (if org-read-date-force-compatible-dates
  12776. "compatible range (1970-2037)"
  12777. "range representable on this machine"))
  12778. (ding))
  12779. (setq final (apply #'encode-time final))
  12780. (setq org-read-date-final-answer ans)
  12781. (if to-time
  12782. final
  12783. ;; This round-trip gets rid of 34th of August and stuff like that....
  12784. (setq final (decode-time final))
  12785. (if (and (boundp 'org-time-was-given) org-time-was-given)
  12786. (format "%04d-%02d-%02d %02d:%02d"
  12787. (nth 5 final) (nth 4 final) (nth 3 final)
  12788. (nth 2 final) (nth 1 final))
  12789. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  12790. (defun org-read-date-display ()
  12791. "Display the current date prompt interpretation in the minibuffer."
  12792. (when org-read-date-display-live
  12793. (when org-read-date-overlay
  12794. (delete-overlay org-read-date-overlay))
  12795. (when (minibufferp (current-buffer))
  12796. (save-excursion
  12797. (end-of-line 1)
  12798. (while (not (equal (buffer-substring
  12799. (max (point-min) (- (point) 4)) (point))
  12800. " "))
  12801. (insert " ")))
  12802. (let* ((ans (concat (buffer-substring (line-beginning-position)
  12803. (point-max))
  12804. " " (or org-ans1 org-ans2)))
  12805. (org-end-time-was-given nil)
  12806. (f (org-read-date-analyze ans org-def org-defdecode))
  12807. (fmts (if org-display-custom-times
  12808. org-time-stamp-custom-formats
  12809. org-time-stamp-formats))
  12810. (fmt (if (or org-with-time
  12811. (and (boundp 'org-time-was-given) org-time-was-given))
  12812. (cdr fmts)
  12813. (car fmts)))
  12814. (txt (format-time-string fmt (apply #'encode-time f)))
  12815. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  12816. (txt (concat "=> " txt)))
  12817. (when (and org-end-time-was-given
  12818. (string-match org-plain-time-of-day-regexp txt))
  12819. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  12820. org-end-time-was-given
  12821. (substring txt (match-end 0)))))
  12822. (when org-read-date-analyze-futurep
  12823. (setq txt (concat txt " (=>F)")))
  12824. (setq org-read-date-overlay
  12825. (make-overlay (1- (line-end-position)) (line-end-position)))
  12826. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  12827. (defun org-read-date-analyze (ans def defdecode)
  12828. "Analyze the combined answer of the date prompt."
  12829. ;; FIXME: cleanup and comment
  12830. (let ((org-def def)
  12831. (org-defdecode defdecode)
  12832. (nowdecode (decode-time))
  12833. delta deltan deltaw deltadef year month day
  12834. hour minute second wday pm h2 m2 tl wday1
  12835. iso-year iso-weekday iso-week iso-date futurep kill-year)
  12836. (setq org-read-date-analyze-futurep nil
  12837. org-read-date-analyze-forced-year nil)
  12838. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  12839. (setq ans "+0"))
  12840. (when (setq delta (org-read-date-get-relative ans nil org-def))
  12841. (setq ans (replace-match "" t t ans)
  12842. deltan (car delta)
  12843. deltaw (nth 1 delta)
  12844. deltadef (nth 2 delta)))
  12845. ;; Check if there is an iso week date in there. If yes, store the
  12846. ;; info and postpone interpreting it until the rest of the parsing
  12847. ;; is done.
  12848. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  12849. (setq iso-year (when (match-end 1)
  12850. (org-small-year-to-year
  12851. (string-to-number (match-string 1 ans))))
  12852. iso-weekday (when (match-end 3)
  12853. (string-to-number (match-string 3 ans)))
  12854. iso-week (string-to-number (match-string 2 ans)))
  12855. (setq ans (replace-match "" t t ans)))
  12856. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  12857. (when (string-match
  12858. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  12859. (setq year (if (match-end 2)
  12860. (string-to-number (match-string 2 ans))
  12861. (progn (setq kill-year t)
  12862. (string-to-number (format-time-string "%Y"))))
  12863. month (string-to-number (match-string 3 ans))
  12864. day (string-to-number (match-string 4 ans)))
  12865. (setq year (org-small-year-to-year year))
  12866. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  12867. t nil ans)))
  12868. ;; Help matching dotted european dates
  12869. (when (string-match
  12870. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  12871. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  12872. (setq kill-year t)
  12873. (string-to-number (format-time-string "%Y")))
  12874. day (string-to-number (match-string 1 ans))
  12875. month (string-to-number (match-string 2 ans))
  12876. ans (replace-match (format "%04d-%02d-%02d" year month day)
  12877. t nil ans)))
  12878. ;; Help matching american dates, like 5/30 or 5/30/7
  12879. (when (string-match
  12880. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  12881. (setq year (if (match-end 4)
  12882. (string-to-number (match-string 4 ans))
  12883. (progn (setq kill-year t)
  12884. (string-to-number (format-time-string "%Y"))))
  12885. month (string-to-number (match-string 1 ans))
  12886. day (string-to-number (match-string 2 ans)))
  12887. (setq year (org-small-year-to-year year))
  12888. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  12889. t nil ans)))
  12890. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  12891. ;; If there is a time with am/pm, and *no* time without it, we convert
  12892. ;; so that matching will be successful.
  12893. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  12894. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  12895. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  12896. (setq hour (string-to-number (match-string 1 ans))
  12897. minute (if (match-end 3)
  12898. (string-to-number (match-string 3 ans))
  12899. 0)
  12900. pm (equal ?p
  12901. (string-to-char (downcase (match-string 4 ans)))))
  12902. (if (and (= hour 12) (not pm))
  12903. (setq hour 0)
  12904. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  12905. (setq ans (replace-match (format "%02d:%02d" hour minute)
  12906. t t ans))))
  12907. ;; Help matching HHhMM times, similarly as for am/pm times.
  12908. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  12909. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  12910. (string-match "\\(?:\\(?1:[012]?[0-9]\\)?h\\(?2:[0-5][0-9]\\)\\)\\|\\(?:\\(?1:[012]?[0-9]\\)h\\(?2:[0-5][0-9]\\)?\\)\\>" ans))
  12911. (setq hour (if (match-end 1)
  12912. (string-to-number (match-string 1 ans))
  12913. 0)
  12914. minute (if (match-end 2)
  12915. (string-to-number (match-string 2 ans))
  12916. 0))
  12917. (setq ans (replace-match (format "%02d:%02d" hour minute)
  12918. t t ans))))
  12919. ;; Check if a time range is given as a duration
  12920. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  12921. (setq hour (string-to-number (match-string 1 ans))
  12922. h2 (+ hour (string-to-number (match-string 3 ans)))
  12923. minute (string-to-number (match-string 2 ans))
  12924. m2 (+ minute (if (match-end 5) (string-to-number
  12925. (match-string 5 ans))0)))
  12926. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  12927. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  12928. t t ans)))
  12929. ;; Check if there is a time range
  12930. (when (boundp 'org-end-time-was-given)
  12931. (setq org-time-was-given nil)
  12932. (when (and (string-match org-plain-time-of-day-regexp ans)
  12933. (match-end 8))
  12934. (setq org-end-time-was-given (match-string 8 ans))
  12935. (setq ans (concat (substring ans 0 (match-beginning 7))
  12936. (substring ans (match-end 7))))))
  12937. (setq tl (parse-time-string ans)
  12938. day (or (nth 3 tl) (nth 3 org-defdecode))
  12939. month
  12940. (cond ((nth 4 tl))
  12941. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  12942. ;; Day was specified. Make sure DAY+MONTH
  12943. ;; combination happens in the future.
  12944. ((nth 3 tl)
  12945. (setq futurep t)
  12946. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  12947. (nth 4 nowdecode)))
  12948. (t (nth 4 org-defdecode)))
  12949. year
  12950. (cond ((and (not kill-year) (nth 5 tl)))
  12951. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  12952. ;; Month was guessed in the future and is at least
  12953. ;; equal to NOWDECODE's. Fix year accordingly.
  12954. (futurep
  12955. (if (or (> month (nth 4 nowdecode))
  12956. (>= day (nth 3 nowdecode)))
  12957. (nth 5 nowdecode)
  12958. (1+ (nth 5 nowdecode))))
  12959. ;; Month was specified. Make sure MONTH+YEAR
  12960. ;; combination happens in the future.
  12961. ((nth 4 tl)
  12962. (setq futurep t)
  12963. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  12964. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  12965. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  12966. (t (nth 5 nowdecode))))
  12967. (t (nth 5 org-defdecode)))
  12968. hour (or (nth 2 tl) (nth 2 org-defdecode))
  12969. minute (or (nth 1 tl) (nth 1 org-defdecode))
  12970. second (or (nth 0 tl) 0)
  12971. wday (nth 6 tl))
  12972. (when (and (eq org-read-date-prefer-future 'time)
  12973. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  12974. (equal day (nth 3 nowdecode))
  12975. (equal month (nth 4 nowdecode))
  12976. (equal year (nth 5 nowdecode))
  12977. (nth 2 tl)
  12978. (or (< (nth 2 tl) (nth 2 nowdecode))
  12979. (and (= (nth 2 tl) (nth 2 nowdecode))
  12980. (nth 1 tl)
  12981. (< (nth 1 tl) (nth 1 nowdecode)))))
  12982. (setq day (1+ day)
  12983. futurep t))
  12984. ;; Special date definitions below
  12985. (cond
  12986. (iso-week
  12987. ;; There was an iso week
  12988. (require 'cal-iso)
  12989. (setq futurep nil)
  12990. (setq year (or iso-year year)
  12991. day (or iso-weekday wday 1)
  12992. wday nil ; to make sure that the trigger below does not match
  12993. iso-date (calendar-gregorian-from-absolute
  12994. (calendar-iso-to-absolute
  12995. (list iso-week day year))))
  12996. ; FIXME: Should we also push ISO weeks into the future?
  12997. ; (when (and org-read-date-prefer-future
  12998. ; (not iso-year)
  12999. ; (< (calendar-absolute-from-gregorian iso-date)
  13000. ; (time-to-days nil)))
  13001. ; (setq year (1+ year)
  13002. ; iso-date (calendar-gregorian-from-absolute
  13003. ; (calendar-iso-to-absolute
  13004. ; (list iso-week day year)))))
  13005. (setq month (car iso-date)
  13006. year (nth 2 iso-date)
  13007. day (nth 1 iso-date)))
  13008. (deltan
  13009. (setq futurep nil)
  13010. (unless deltadef
  13011. (let ((now (decode-time)))
  13012. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  13013. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  13014. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  13015. ((equal deltaw "m") (setq month (+ month deltan)))
  13016. ((equal deltaw "y") (setq year (+ year deltan)))))
  13017. ((and wday (not (nth 3 tl)))
  13018. ;; Weekday was given, but no day, so pick that day in the week
  13019. ;; on or after the derived date.
  13020. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  13021. (unless (equal wday wday1)
  13022. (setq day (+ day (% (- wday wday1 -7) 7))))))
  13023. (when (and (boundp 'org-time-was-given)
  13024. (nth 2 tl))
  13025. (setq org-time-was-given t))
  13026. (when (< year 100) (setq year (+ 2000 year)))
  13027. ;; Check of the date is representable
  13028. (if org-read-date-force-compatible-dates
  13029. (progn
  13030. (when (< year 1970)
  13031. (setq year 1970 org-read-date-analyze-forced-year t))
  13032. (when (> year 2037)
  13033. (setq year 2037 org-read-date-analyze-forced-year t)))
  13034. (condition-case nil
  13035. (ignore (encode-time second minute hour day month year))
  13036. (error
  13037. (setq year (nth 5 org-defdecode))
  13038. (setq org-read-date-analyze-forced-year t))))
  13039. (setq org-read-date-analyze-futurep futurep)
  13040. (list second minute hour day month year)))
  13041. (defvar parse-time-weekdays)
  13042. (defun org-read-date-get-relative (s today default)
  13043. "Check string S for special relative date string.
  13044. TODAY and DEFAULT are internal times, for today and for a default.
  13045. Return shift list (N what def-flag)
  13046. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  13047. N is the number of WHATs to shift.
  13048. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  13049. the DEFAULT date rather than TODAY."
  13050. (require 'parse-time)
  13051. (when (and
  13052. (string-match
  13053. (concat
  13054. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  13055. "\\([0-9]+\\)?"
  13056. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  13057. "\\([ \t]\\|$\\)") s)
  13058. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  13059. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  13060. (string-to-char (substring (match-string 1 s) -1))
  13061. ?+))
  13062. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  13063. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  13064. (what (if (match-end 3) (match-string 3 s) "d"))
  13065. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  13066. (date (if rel default today))
  13067. (wday (nth 6 (decode-time date)))
  13068. delta)
  13069. (if wday1
  13070. (progn
  13071. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  13072. (when (= delta 0) (setq delta 7))
  13073. (when (= dir ?-)
  13074. (setq delta (- delta 7))
  13075. (when (= delta 0) (setq delta -7)))
  13076. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  13077. (list delta "d" rel))
  13078. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  13079. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  13080. "Turn a user-specified date into the internal representation.
  13081. The internal representation needed by the calendar is (month day year).
  13082. This is a wrapper to handle the brain-dead convention in calendar that
  13083. user function argument order change dependent on argument order."
  13084. (pcase calendar-date-style
  13085. (`american (list arg1 arg2 arg3))
  13086. (`european (list arg2 arg1 arg3))
  13087. (`iso (list arg2 arg3 arg1))))
  13088. (defun org-eval-in-calendar (form &optional keepdate)
  13089. "Eval FORM in the calendar window and return to current window.
  13090. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  13091. (let ((sf (selected-frame))
  13092. (sw (selected-window)))
  13093. (select-window (get-buffer-window "*Calendar*" t))
  13094. (eval form)
  13095. (when (and (not keepdate) (calendar-cursor-to-date))
  13096. (let* ((date (calendar-cursor-to-date))
  13097. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  13098. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  13099. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  13100. (select-window sw)
  13101. (select-frame-set-input-focus sf)))
  13102. (defun org-calendar-select ()
  13103. "Return to `org-read-date' with the date currently selected.
  13104. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  13105. (interactive)
  13106. (when (calendar-cursor-to-date)
  13107. (let* ((date (calendar-cursor-to-date))
  13108. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  13109. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  13110. (when (active-minibuffer-window) (exit-minibuffer))))
  13111. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  13112. "Insert a date stamp for the date given by the internal TIME.
  13113. See `format-time-string' for the format of TIME.
  13114. WITH-HM means use the stamp format that includes the time of the day.
  13115. INACTIVE means use square brackets instead of angular ones, so that the
  13116. stamp will not contribute to the agenda.
  13117. PRE and POST are optional strings to be inserted before and after the
  13118. stamp.
  13119. The command returns the inserted time stamp."
  13120. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  13121. stamp)
  13122. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  13123. (insert-before-markers (or pre ""))
  13124. (when (listp extra)
  13125. (setq extra (car extra))
  13126. (if (and (stringp extra)
  13127. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  13128. (setq extra (format "-%02d:%02d"
  13129. (string-to-number (match-string 1 extra))
  13130. (string-to-number (match-string 2 extra))))
  13131. (setq extra nil)))
  13132. (when extra
  13133. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  13134. (insert-before-markers (setq stamp (format-time-string fmt time)))
  13135. (insert-before-markers (or post ""))
  13136. (setq org-last-inserted-timestamp stamp)))
  13137. (defun org-toggle-time-stamp-overlays ()
  13138. "Toggle the use of custom time stamp formats."
  13139. (interactive)
  13140. (setq org-display-custom-times (not org-display-custom-times))
  13141. (unless org-display-custom-times
  13142. (let ((p (point-min)) (bmp (buffer-modified-p)))
  13143. (while (setq p (next-single-property-change p 'display))
  13144. (when (and (get-text-property p 'display)
  13145. (eq (get-text-property p 'face) 'org-date))
  13146. (remove-text-properties
  13147. p (setq p (next-single-property-change p 'display))
  13148. '(display t))))
  13149. (set-buffer-modified-p bmp)))
  13150. (org-restart-font-lock)
  13151. (setq org-table-may-need-update t)
  13152. (if org-display-custom-times
  13153. (message "Time stamps are overlaid with custom format")
  13154. (message "Time stamp overlays removed")))
  13155. (defun org-display-custom-time (beg end)
  13156. "Overlay modified time stamp format over timestamp between BEG and END."
  13157. (let* ((ts (buffer-substring beg end))
  13158. t1 with-hm tf time str (off 0))
  13159. (save-match-data
  13160. (setq t1 (org-parse-time-string ts t))
  13161. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  13162. (setq off (- (match-end 0) (match-beginning 0)))))
  13163. (setq end (- end off))
  13164. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  13165. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  13166. time (org-fix-decoded-time t1)
  13167. str (org-add-props
  13168. (format-time-string
  13169. (substring tf 1 -1) (apply 'encode-time time))
  13170. nil 'mouse-face 'highlight))
  13171. (put-text-property beg end 'display str)))
  13172. (defun org-fix-decoded-time (time)
  13173. "Set 0 instead of nil for the first 6 elements of time.
  13174. Don't touch the rest."
  13175. (let ((n 0))
  13176. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  13177. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  13178. "Difference between TIMESTAMP-STRING and now in days.
  13179. If SECONDS is non-nil, return the difference in seconds."
  13180. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  13181. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  13182. (funcall fdiff nil))))
  13183. (defun org-deadline-close-p (timestamp-string &optional ndays)
  13184. "Is the time in TIMESTAMP-STRING close to the current date?"
  13185. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  13186. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  13187. (not (org-entry-is-done-p))))
  13188. (defun org-get-wdays (ts &optional delay zero-delay)
  13189. "Get the deadline lead time appropriate for timestring TS.
  13190. When DELAY is non-nil, get the delay time for scheduled items
  13191. instead of the deadline lead time. When ZERO-DELAY is non-nil
  13192. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  13193. don't try to find the delay cookie in the scheduled timestamp."
  13194. (let ((tv (if delay org-scheduled-delay-days
  13195. org-deadline-warning-days)))
  13196. (cond
  13197. ((or (and delay (< tv 0))
  13198. (and delay zero-delay (<= tv 0))
  13199. (and (not delay) (<= tv 0)))
  13200. ;; Enforce this value no matter what
  13201. (- tv))
  13202. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  13203. ;; lead time is specified.
  13204. (floor (* (string-to-number (match-string 1 ts))
  13205. (cdr (assoc (match-string 2 ts)
  13206. '(("d" . 1) ("w" . 7)
  13207. ("m" . 30.4) ("y" . 365.25)
  13208. ("h" . 0.041667)))))))
  13209. ;; go for the default.
  13210. (t tv))))
  13211. (defun org-calendar-select-mouse (ev)
  13212. "Return to `org-read-date' with the date currently selected.
  13213. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  13214. (interactive "e")
  13215. (mouse-set-point ev)
  13216. (when (calendar-cursor-to-date)
  13217. (let* ((date (calendar-cursor-to-date))
  13218. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  13219. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  13220. (when (active-minibuffer-window) (exit-minibuffer))))
  13221. (defun org-check-deadlines (ndays)
  13222. "Check if there are any deadlines due or past due.
  13223. A deadline is considered due if it happens within `org-deadline-warning-days'
  13224. days from today's date. If the deadline appears in an entry marked DONE,
  13225. it is not shown. A numeric prefix argument NDAYS can be used to test that
  13226. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  13227. are shown."
  13228. (interactive "P")
  13229. (let* ((org-warn-days
  13230. (cond
  13231. ((equal ndays '(4)) 100000)
  13232. (ndays (prefix-numeric-value ndays))
  13233. (t (abs org-deadline-warning-days))))
  13234. (case-fold-search nil)
  13235. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  13236. (callback
  13237. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  13238. (message "%d deadlines past-due or due within %d days"
  13239. (org-occur regexp nil callback)
  13240. org-warn-days)))
  13241. (defsubst org-re-timestamp (type)
  13242. "Return a regexp for timestamp TYPE.
  13243. Allowed values for TYPE are:
  13244. all: all timestamps
  13245. active: only active timestamps (<...>)
  13246. inactive: only inactive timestamps ([...])
  13247. scheduled: only scheduled timestamps
  13248. deadline: only deadline timestamps
  13249. closed: only closed time-stamps
  13250. When TYPE is nil, fall back on returning a regexp that matches
  13251. both scheduled and deadline timestamps."
  13252. (cl-case type
  13253. (all org-ts-regexp-both)
  13254. (active org-ts-regexp)
  13255. (inactive org-ts-regexp-inactive)
  13256. (scheduled org-scheduled-time-regexp)
  13257. (deadline org-deadline-time-regexp)
  13258. (closed org-closed-time-regexp)
  13259. (otherwise
  13260. (concat "\\<"
  13261. (regexp-opt (list org-deadline-string org-scheduled-string))
  13262. " *<\\([^>]+\\)>"))))
  13263. (defun org-check-before-date (d)
  13264. "Check if there are deadlines or scheduled entries before date D."
  13265. (interactive (list (org-read-date)))
  13266. (let* ((case-fold-search nil)
  13267. (regexp (org-re-timestamp org-ts-type))
  13268. (ts-type org-ts-type)
  13269. (callback
  13270. (lambda ()
  13271. (let ((match (match-string 1)))
  13272. (and (if (memq ts-type '(active inactive all))
  13273. (eq (org-element-type (save-excursion
  13274. (backward-char)
  13275. (org-element-context)))
  13276. 'timestamp)
  13277. (org-at-planning-p))
  13278. (time-less-p
  13279. (org-time-string-to-time match)
  13280. (org-time-string-to-time d)))))))
  13281. (message "%d entries before %s"
  13282. (org-occur regexp nil callback)
  13283. d)))
  13284. (defun org-check-after-date (d)
  13285. "Check if there are deadlines or scheduled entries after date D."
  13286. (interactive (list (org-read-date)))
  13287. (let* ((case-fold-search nil)
  13288. (regexp (org-re-timestamp org-ts-type))
  13289. (ts-type org-ts-type)
  13290. (callback
  13291. (lambda ()
  13292. (let ((match (match-string 1)))
  13293. (and (if (memq ts-type '(active inactive all))
  13294. (eq (org-element-type (save-excursion
  13295. (backward-char)
  13296. (org-element-context)))
  13297. 'timestamp)
  13298. (org-at-planning-p))
  13299. (not (time-less-p
  13300. (org-time-string-to-time match)
  13301. (org-time-string-to-time d))))))))
  13302. (message "%d entries after %s"
  13303. (org-occur regexp nil callback)
  13304. d)))
  13305. (defun org-check-dates-range (start-date end-date)
  13306. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  13307. (interactive (list (org-read-date nil nil nil "Range starts")
  13308. (org-read-date nil nil nil "Range end")))
  13309. (let ((case-fold-search nil)
  13310. (regexp (org-re-timestamp org-ts-type))
  13311. (callback
  13312. (let ((type org-ts-type))
  13313. (lambda ()
  13314. (let ((match (match-string 1)))
  13315. (and
  13316. (if (memq type '(active inactive all))
  13317. (eq (org-element-type (save-excursion
  13318. (backward-char)
  13319. (org-element-context)))
  13320. 'timestamp)
  13321. (org-at-planning-p))
  13322. (not (time-less-p
  13323. (org-time-string-to-time match)
  13324. (org-time-string-to-time start-date)))
  13325. (time-less-p
  13326. (org-time-string-to-time match)
  13327. (org-time-string-to-time end-date))))))))
  13328. (message "%d entries between %s and %s"
  13329. (org-occur regexp nil callback) start-date end-date)))
  13330. (defun org-evaluate-time-range (&optional to-buffer)
  13331. "Evaluate a time range by computing the difference between start and end.
  13332. Normally the result is just printed in the echo area, but with prefix arg
  13333. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  13334. If the time range is actually in a table, the result is inserted into the
  13335. next column.
  13336. For time difference computation, a year is assumed to be exactly 365
  13337. days in order to avoid rounding problems."
  13338. (interactive "P")
  13339. (or
  13340. (org-clock-update-time-maybe)
  13341. (save-excursion
  13342. (unless (org-at-date-range-p t)
  13343. (goto-char (line-beginning-position))
  13344. (re-search-forward org-tr-regexp-both (line-end-position) t))
  13345. (unless (org-at-date-range-p t)
  13346. (user-error "Not at a time-stamp range, and none found in current line")))
  13347. (let* ((ts1 (match-string 1))
  13348. (ts2 (match-string 2))
  13349. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  13350. (match-end (match-end 0))
  13351. (time1 (org-time-string-to-time ts1))
  13352. (time2 (org-time-string-to-time ts2))
  13353. (diff (abs (float-time (time-subtract time2 time1))))
  13354. (negative (time-less-p time2 time1))
  13355. ;; (ys (floor (* 365 24 60 60)))
  13356. (ds (* 24 60 60))
  13357. (hs (* 60 60))
  13358. (fy "%dy %dd %02d:%02d")
  13359. (fy1 "%dy %dd")
  13360. (fd "%dd %02d:%02d")
  13361. (fd1 "%dd")
  13362. (fh "%02d:%02d")
  13363. y d h m align)
  13364. (if havetime
  13365. (setq ; y (floor diff ys) diff (mod diff ys)
  13366. y 0
  13367. d (floor diff ds) diff (mod diff ds)
  13368. h (floor diff hs) diff (mod diff hs)
  13369. m (floor diff 60))
  13370. (setq ; y (floor diff ys) diff (mod diff ys)
  13371. y 0
  13372. d (round diff ds)
  13373. h 0 m 0))
  13374. (if (not to-buffer)
  13375. (message "%s" (org-make-tdiff-string y d h m))
  13376. (if (org-at-table-p)
  13377. (progn
  13378. (goto-char match-end)
  13379. (setq align t)
  13380. (and (looking-at " *|") (goto-char (match-end 0))))
  13381. (goto-char match-end))
  13382. (when (looking-at
  13383. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  13384. (replace-match ""))
  13385. (when negative (insert " -"))
  13386. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  13387. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  13388. (insert " " (format fh h m))))
  13389. (when align (org-table-align))
  13390. (message "Time difference inserted")))))
  13391. (defun org-make-tdiff-string (y d h m)
  13392. (let ((fmt "")
  13393. (l nil))
  13394. (when (> y 0)
  13395. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  13396. (push y l))
  13397. (when (> d 0)
  13398. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  13399. (push d l))
  13400. (when (> h 0)
  13401. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  13402. (push h l))
  13403. (when (> m 0)
  13404. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  13405. (push m l))
  13406. (apply 'format fmt (nreverse l))))
  13407. (defun org-time-string-to-time (s)
  13408. "Convert timestamp string S into internal time."
  13409. (apply #'encode-time (org-parse-time-string s)))
  13410. (defun org-time-string-to-seconds (s)
  13411. "Convert a timestamp string S into a number of seconds."
  13412. (float-time (org-time-string-to-time s)))
  13413. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  13414. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  13415. "Convert time stamp S to an absolute day number.
  13416. If DAYNR in non-nil, and there is a specifier for a cyclic time
  13417. stamp, get the closest date to DAYNR. If PREFER is
  13418. `past' (respectively `future') return a date past (respectively
  13419. after) or equal to DAYNR.
  13420. POS is the location of time stamp S, as a buffer position in
  13421. BUFFER.
  13422. Diary sexp timestamps are matched against DAYNR, when non-nil.
  13423. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  13424. signaled."
  13425. (cond
  13426. ((string-match "\\`%%\\((.*)\\)" s)
  13427. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  13428. ;; only able to match individual dates. If it fails, raise an
  13429. ;; error.
  13430. (if (and daynr
  13431. (org-diary-sexp-entry
  13432. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  13433. daynr
  13434. (signal 'org-diary-sexp-no-match (list s))))
  13435. (daynr (org-closest-date s daynr prefer))
  13436. (t (time-to-days
  13437. (condition-case errdata
  13438. (org-time-string-to-time s)
  13439. (error (error "Bad timestamp `%s'%s\nError was: %s"
  13440. s
  13441. (if (not (and buffer pos)) ""
  13442. (format-message " at %d in buffer `%s'" pos buffer))
  13443. (cdr errdata))))))))
  13444. (defun org-days-to-iso-week (days)
  13445. "Return the ISO week number."
  13446. (require 'cal-iso)
  13447. (car (calendar-iso-from-absolute days)))
  13448. (defun org-small-year-to-year (year)
  13449. "Convert 2-digit years into 4-digit years.
  13450. YEAR is expanded into one of the 30 next years, if possible, or
  13451. into a past one. Any year larger than 99 is returned unchanged."
  13452. (if (>= year 100) year
  13453. (let* ((current (string-to-number (format-time-string "%Y")))
  13454. (century (/ current 100))
  13455. (offset (- year (% current 100))))
  13456. (cond ((> offset 30) (+ (* (1- century) 100) year))
  13457. ((> offset -70) (+ (* century 100) year))
  13458. (t (+ (* (1+ century) 100) year))))))
  13459. (defun org-time-from-absolute (d)
  13460. "Return the time corresponding to date D.
  13461. D may be an absolute day number, or a calendar-type list (month day year)."
  13462. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  13463. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  13464. (defvar org-agenda-current-date)
  13465. (defun org-calendar-holiday ()
  13466. "List of holidays, for Diary display in Org mode."
  13467. (require 'holidays)
  13468. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  13469. (and hl (mapconcat #'identity hl "; "))))
  13470. (defun org-diary-sexp-entry (sexp entry d)
  13471. "Process a SEXP diary ENTRY for date D."
  13472. (require 'diary-lib)
  13473. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  13474. ;; dynamically.
  13475. (let* ((sexp `(let ((entry ,entry)
  13476. (date ',d))
  13477. ,(car (read-from-string sexp))))
  13478. (result (if calendar-debug-sexp (eval sexp)
  13479. (condition-case nil
  13480. (eval sexp)
  13481. (error
  13482. (beep)
  13483. (message "Bad sexp at line %d in %s: %s"
  13484. (org-current-line)
  13485. (buffer-file-name) sexp)
  13486. (sleep-for 2))))))
  13487. (cond ((stringp result) (split-string result "; "))
  13488. ((and (consp result)
  13489. (not (consp (cdr result)))
  13490. (stringp (cdr result))) (cdr result))
  13491. ((and (consp result)
  13492. (stringp (car result))) result)
  13493. (result entry))))
  13494. (defun org-diary-to-ical-string (frombuf)
  13495. "Get iCalendar entries from diary entries in buffer FROMBUF.
  13496. This uses the icalendar.el library."
  13497. (let* ((tmpdir temporary-file-directory)
  13498. (tmpfile (make-temp-name
  13499. (expand-file-name "orgics" tmpdir)))
  13500. buf rtn b e)
  13501. (with-current-buffer frombuf
  13502. (icalendar-export-region (point-min) (point-max) tmpfile)
  13503. (setq buf (find-buffer-visiting tmpfile))
  13504. (set-buffer buf)
  13505. (goto-char (point-min))
  13506. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  13507. (setq b (match-beginning 0)))
  13508. (goto-char (point-max))
  13509. (when (re-search-backward "^END:VEVENT" nil t)
  13510. (setq e (match-end 0)))
  13511. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  13512. (kill-buffer buf)
  13513. (delete-file tmpfile)
  13514. rtn))
  13515. (defun org-closest-date (start current prefer)
  13516. "Return closest date to CURRENT starting from START.
  13517. CURRENT and START are both time stamps.
  13518. When PREFER is `past', return a date that is either CURRENT or
  13519. past. When PREFER is `future', return a date that is either
  13520. CURRENT or future.
  13521. Only time stamps with a repeater are modified. Any other time
  13522. stamp stay unchanged. In any case, return value is an absolute
  13523. day number."
  13524. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  13525. ;; No repeater. Do not shift time stamp.
  13526. (time-to-days (org-time-string-to-time start))
  13527. (let ((value (string-to-number (match-string 1 start)))
  13528. (type (match-string 2 start)))
  13529. (if (= 0 value)
  13530. ;; Repeater with a 0-value is considered as void.
  13531. (time-to-days (org-time-string-to-time start))
  13532. (let* ((base (org-date-to-gregorian start))
  13533. (target (org-date-to-gregorian current))
  13534. (sday (calendar-absolute-from-gregorian base))
  13535. (cday (calendar-absolute-from-gregorian target))
  13536. n1 n2)
  13537. ;; If START is already past CURRENT, just return START.
  13538. (if (<= cday sday) sday
  13539. ;; Compute closest date before (N1) and closest date past
  13540. ;; (N2) CURRENT.
  13541. (pcase type
  13542. ("h"
  13543. (let ((missing-hours
  13544. (mod (+ (- (* 24 (- cday sday))
  13545. (nth 2 (org-parse-time-string start)))
  13546. org-extend-today-until)
  13547. value)))
  13548. (setf n1 (if (= missing-hours 0) cday
  13549. (- cday (1+ (/ missing-hours 24)))))
  13550. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  13551. ((or "d" "w")
  13552. (let ((value (if (equal type "w") (* 7 value) value)))
  13553. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  13554. (setf n2 (+ n1 value))))
  13555. ("m"
  13556. (let* ((add-months
  13557. (lambda (d n)
  13558. ;; Add N months to gregorian date D, i.e.,
  13559. ;; a list (MONTH DAY YEAR). Return a valid
  13560. ;; gregorian date.
  13561. (let ((m (+ (nth 0 d) n)))
  13562. (list (mod m 12)
  13563. (nth 1 d)
  13564. (+ (/ m 12) (nth 2 d))))))
  13565. (months ; Complete months to TARGET.
  13566. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  13567. (- (nth 0 target) (nth 0 base))
  13568. ;; If START's day is greater than
  13569. ;; TARGET's, remove incomplete month.
  13570. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  13571. value)
  13572. value))
  13573. (before (funcall add-months base months)))
  13574. (setf n1 (calendar-absolute-from-gregorian before))
  13575. (setf n2
  13576. (calendar-absolute-from-gregorian
  13577. (funcall add-months before value)))))
  13578. (_
  13579. (let* ((d (nth 1 base))
  13580. (m (nth 0 base))
  13581. (y (nth 2 base))
  13582. (years ; Complete years to TARGET.
  13583. (* (/ (- (nth 2 target)
  13584. y
  13585. ;; If START's month and day are
  13586. ;; greater than TARGET's, remove
  13587. ;; incomplete year.
  13588. (if (or (> (nth 0 target) m)
  13589. (and (= (nth 0 target) m)
  13590. (> (nth 1 target) d)))
  13591. 0
  13592. 1))
  13593. value)
  13594. value))
  13595. (before (list m d (+ y years))))
  13596. (setf n1 (calendar-absolute-from-gregorian before))
  13597. (setf n2 (calendar-absolute-from-gregorian
  13598. (list m d (+ (nth 2 before) value)))))))
  13599. ;; Handle PREFER parameter, if any.
  13600. (cond
  13601. ((eq prefer 'past) (if (= cday n2) n2 n1))
  13602. ((eq prefer 'future) (if (= cday n1) n1 n2))
  13603. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  13604. (defun org-date-to-gregorian (d)
  13605. "Turn any specification of date D into a Gregorian date for the calendar."
  13606. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  13607. ((and (listp d) (= (length d) 3)) d)
  13608. ((stringp d)
  13609. (let ((d (org-parse-time-string d)))
  13610. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  13611. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  13612. (defun org-timestamp-up (&optional arg)
  13613. "Increase the date item at the cursor by one.
  13614. If the cursor is on the year, change the year. If it is on the month,
  13615. the day or the time, change that. If the cursor is on the enclosing
  13616. bracket, change the timestamp type.
  13617. With prefix ARG, change by that many units."
  13618. (interactive "p")
  13619. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  13620. (defun org-timestamp-down (&optional arg)
  13621. "Decrease the date item at the cursor by one.
  13622. If the cursor is on the year, change the year. If it is on the month,
  13623. the day or the time, change that. If the cursor is on the enclosing
  13624. bracket, change the timestamp type.
  13625. With prefix ARG, change by that many units."
  13626. (interactive "p")
  13627. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  13628. (defun org-timestamp-up-day (&optional arg)
  13629. "Increase the date in the time stamp by one day.
  13630. With prefix ARG, change that many days."
  13631. (interactive "p")
  13632. (if (and (not (org-at-timestamp-p 'lax))
  13633. (org-at-heading-p))
  13634. (org-todo 'up)
  13635. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  13636. (defun org-timestamp-down-day (&optional arg)
  13637. "Decrease the date in the time stamp by one day.
  13638. With prefix ARG, change that many days."
  13639. (interactive "p")
  13640. (if (and (not (org-at-timestamp-p 'lax))
  13641. (org-at-heading-p))
  13642. (org-todo 'down)
  13643. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  13644. (defun org-at-timestamp-p (&optional extended)
  13645. "Non-nil if point is inside a timestamp.
  13646. By default, the function only consider syntactically valid active
  13647. timestamps. However, the caller may have a broader definition
  13648. for timestamps. As a consequence, optional argument EXTENDED can
  13649. be set to the following values
  13650. `inactive'
  13651. Include also syntactically valid inactive timestamps.
  13652. `agenda'
  13653. Include timestamps allowed in Agenda, i.e., those in
  13654. properties drawers, planning lines and clock lines.
  13655. `lax'
  13656. Ignore context. The function matches any part of the
  13657. document looking like a timestamp. This includes comments,
  13658. example blocks...
  13659. For backward-compatibility with Org 9.0, every other non-nil
  13660. value is equivalent to `inactive'.
  13661. When at a timestamp, return the position of the point as a symbol
  13662. among `bracket', `after', `year', `month', `hour', `minute',
  13663. `day' or a number of character from the last know part of the
  13664. time stamp. If diary sexp timestamps, any point inside the timestamp
  13665. is considered `day' (i.e. only `bracket', `day', and `after' return
  13666. values are possible).
  13667. When matching, the match groups are the following:
  13668. group 1: year, if any
  13669. group 2: month, if any
  13670. group 3: day number, if any
  13671. group 4: day name, if any
  13672. group 5: hours, if any
  13673. group 6: minutes, if any"
  13674. (let* ((regexp
  13675. (if extended
  13676. (if (eq extended 'agenda)
  13677. (rx-to-string
  13678. `(or (regexp ,org-ts-regexp3)
  13679. (regexp ,org-element--timestamp-regexp)))
  13680. org-ts-regexp3)
  13681. org-ts-regexp2))
  13682. (pos (point))
  13683. (match?
  13684. (let ((boundaries (org-in-regexp regexp)))
  13685. (save-match-data
  13686. (cond ((null boundaries) nil)
  13687. ((eq extended 'lax) t)
  13688. (t
  13689. (or (and (eq extended 'agenda)
  13690. (or (org-at-planning-p)
  13691. (org-at-property-p)
  13692. (and (bound-and-true-p
  13693. org-agenda-include-inactive-timestamps)
  13694. (org-at-clock-log-p))))
  13695. (eq 'timestamp
  13696. (save-excursion
  13697. (when (= pos (cdr boundaries)) (forward-char -1))
  13698. (org-element-type (org-element-context)))))))))))
  13699. (cond
  13700. ((not match?) nil)
  13701. ((= pos (match-beginning 0)) 'bracket)
  13702. ;; Distinguish location right before the closing bracket from
  13703. ;; right after it.
  13704. ((= pos (1- (match-end 0))) 'bracket)
  13705. ((= pos (match-end 0)) 'after)
  13706. ((org-pos-in-match-range pos 2) 'year)
  13707. ((org-pos-in-match-range pos 3) 'month)
  13708. ((org-pos-in-match-range pos 7) 'hour)
  13709. ((org-pos-in-match-range pos 8) 'minute)
  13710. ((or (org-pos-in-match-range pos 4)
  13711. (org-pos-in-match-range pos 5)) 'day)
  13712. ((and (or (match-end 8) (match-end 5))
  13713. (> pos (or (match-end 8) (match-end 5)))
  13714. (< pos (match-end 0)))
  13715. (- pos (or (match-end 8) (match-end 5))))
  13716. (t 'day))))
  13717. (defun org-toggle-timestamp-type ()
  13718. "Toggle the type (<active> or [inactive]) of a time stamp."
  13719. (interactive)
  13720. (when (org-at-timestamp-p 'lax)
  13721. (let ((beg (match-beginning 0)) (end (match-end 0))
  13722. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  13723. (save-excursion
  13724. (goto-char beg)
  13725. (while (re-search-forward "[][<>]" end t)
  13726. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  13727. t t)))
  13728. (message "Timestamp is now %sactive"
  13729. (if (equal (char-after beg) ?<) "" "in")))))
  13730. (defun org-at-clock-log-p ()
  13731. "Non-nil if point is on a clock log line."
  13732. (and (org-match-line org-clock-line-re)
  13733. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  13734. (defvar org-clock-history) ; defined in org-clock.el
  13735. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  13736. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  13737. "Change the date in the time stamp at point.
  13738. The date is changed by N times WHAT. WHAT can be `day', `month',
  13739. `year', `hour', or `minute'. If WHAT is not given, the cursor
  13740. position in the timestamp determines what is changed.
  13741. When optional argument UPDOWN is non-nil, minutes are rounded
  13742. according to `org-time-stamp-rounding-minutes'.
  13743. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like
  13744. \"--2d\"."
  13745. (let ((origin (point))
  13746. (timestamp? (org-at-timestamp-p 'lax))
  13747. origin-cat
  13748. with-hm inactive
  13749. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  13750. extra rem
  13751. ts time time0 fixnext clrgx)
  13752. (unless timestamp? (user-error "Not at a timestamp"))
  13753. (if (and (not what) (eq timestamp? 'bracket))
  13754. (org-toggle-timestamp-type)
  13755. ;; Point isn't on brackets. Remember the part of the time-stamp
  13756. ;; the point was in. Indeed, size of time-stamps may change,
  13757. ;; but point must be kept in the same category nonetheless.
  13758. (setq origin-cat timestamp?)
  13759. (when (and (not what) (not (eq timestamp? 'day))
  13760. org-display-custom-times
  13761. (get-text-property (point) 'display)
  13762. (not (get-text-property (1- (point)) 'display)))
  13763. (setq timestamp? 'day))
  13764. (setq timestamp? (or what timestamp?)
  13765. inactive (= (char-after (match-beginning 0)) ?\[)
  13766. ts (match-string 0))
  13767. (replace-match "")
  13768. (when (string-match
  13769. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  13770. ts)
  13771. (setq extra (match-string 1 ts))
  13772. (when suppress-tmp-delay
  13773. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  13774. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  13775. (setq with-hm t))
  13776. (setq time0 (org-parse-time-string ts))
  13777. (when (and updown
  13778. (eq timestamp? 'minute)
  13779. (not current-prefix-arg))
  13780. ;; This looks like s-up and s-down. Change by one rounding step.
  13781. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  13782. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  13783. (setcar (cdr time0) (+ (nth 1 time0)
  13784. (if (> n 0) (- rem) (- dm rem))))))
  13785. (setq time
  13786. (apply #'encode-time
  13787. (or (car time0) 0)
  13788. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  13789. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  13790. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  13791. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  13792. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  13793. (nthcdr 6 time0)))
  13794. (when (and (memq timestamp? '(hour minute))
  13795. extra
  13796. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  13797. (setq extra (org-modify-ts-extra
  13798. extra
  13799. (if (eq timestamp? 'hour) 2 5)
  13800. n dm)))
  13801. (when (integerp timestamp?)
  13802. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  13803. (when (eq what 'calendar)
  13804. (let ((cal-date (org-get-date-from-calendar)))
  13805. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  13806. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  13807. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  13808. (setcar time0 (or (car time0) 0))
  13809. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  13810. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  13811. (setq time (apply 'encode-time time0))))
  13812. ;; Insert the new time-stamp, and ensure point stays in the same
  13813. ;; category as before (i.e. not after the last position in that
  13814. ;; category).
  13815. (let ((pos (point)))
  13816. ;; Stay before inserted string. `save-excursion' is of no use.
  13817. (setq org-last-changed-timestamp
  13818. (org-insert-time-stamp time with-hm inactive nil nil extra))
  13819. (goto-char pos))
  13820. (save-match-data
  13821. (looking-at org-ts-regexp3)
  13822. (goto-char
  13823. (pcase origin-cat
  13824. ;; `day' category ends before `hour' if any, or at the end
  13825. ;; of the day name.
  13826. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  13827. (`hour (min (match-end 7) origin))
  13828. (`minute (min (1- (match-end 8)) origin))
  13829. ((pred integerp) (min (1- (match-end 0)) origin))
  13830. ;; Point was right after the time-stamp. However, the
  13831. ;; time-stamp length might have changed, so refer to
  13832. ;; (match-end 0) instead.
  13833. (`after (match-end 0))
  13834. ;; `year' and `month' have both fixed size: point couldn't
  13835. ;; have moved into another part.
  13836. (_ origin))))
  13837. ;; Update clock if on a CLOCK line.
  13838. (org-clock-update-time-maybe)
  13839. ;; Maybe adjust the closest clock in `org-clock-history'
  13840. (when org-clock-adjust-closest
  13841. (if (not (and (org-at-clock-log-p)
  13842. (< 1 (length (delq nil (mapcar 'marker-position
  13843. org-clock-history))))))
  13844. (message "No clock to adjust")
  13845. (cond ((save-excursion ; fix previous clock?
  13846. (re-search-backward org-ts-regexp0 nil t)
  13847. (looking-back (concat org-clock-string " \\[")
  13848. (line-beginning-position)))
  13849. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  13850. ((save-excursion ; fix next clock?
  13851. (re-search-backward org-ts-regexp0 nil t)
  13852. (looking-at (concat org-ts-regexp0 "\\] =>")))
  13853. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  13854. (save-window-excursion
  13855. ;; Find closest clock to point, adjust the previous/next one in history
  13856. (let* ((p (save-excursion (org-back-to-heading t)))
  13857. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  13858. (clfixnth
  13859. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  13860. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  13861. (if (not clfixpos)
  13862. (message "No clock to adjust")
  13863. (save-excursion
  13864. (org-goto-marker-or-bmk clfixpos)
  13865. (org-show-subtree)
  13866. (when (re-search-forward clrgx nil t)
  13867. (goto-char (match-beginning 1))
  13868. (let (org-clock-adjust-closest)
  13869. (org-timestamp-change n timestamp? updown))
  13870. (message "Clock adjusted in %s for heading: %s"
  13871. (file-name-nondirectory (buffer-file-name))
  13872. (org-get-heading t t)))))))))
  13873. ;; Try to recenter the calendar window, if any.
  13874. (when (and org-calendar-follow-timestamp-change
  13875. (get-buffer-window "*Calendar*" t)
  13876. (memq timestamp? '(day month year)))
  13877. (org-recenter-calendar (time-to-days time))))))
  13878. (defun org-modify-ts-extra (s pos n dm)
  13879. "Change the different parts of the lead-time and repeat fields in timestamp."
  13880. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  13881. ng h m new rem)
  13882. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  13883. (cond
  13884. ((or (org-pos-in-match-range pos 2)
  13885. (org-pos-in-match-range pos 3))
  13886. (setq m (string-to-number (match-string 3 s))
  13887. h (string-to-number (match-string 2 s)))
  13888. (if (org-pos-in-match-range pos 2)
  13889. (setq h (+ h n))
  13890. (setq n (* dm (with-no-warnings (cl-signum n))))
  13891. (unless (= 0 (setq rem (% m dm)))
  13892. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  13893. (setq m (+ m n)))
  13894. (when (< m 0) (setq m (+ m 60) h (1- h)))
  13895. (when (> m 59) (setq m (- m 60) h (1+ h)))
  13896. (setq h (mod h 24))
  13897. (setq ng 1 new (format "-%02d:%02d" h m)))
  13898. ((org-pos-in-match-range pos 6)
  13899. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  13900. ((org-pos-in-match-range pos 5)
  13901. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  13902. ((org-pos-in-match-range pos 9)
  13903. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  13904. ((org-pos-in-match-range pos 8)
  13905. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  13906. (when ng
  13907. (setq s (concat
  13908. (substring s 0 (match-beginning ng))
  13909. new
  13910. (substring s (match-end ng))))))
  13911. s))
  13912. (defun org-recenter-calendar (d)
  13913. "If the calendar is visible, recenter it to date D."
  13914. (let ((cwin (get-buffer-window "*Calendar*" t)))
  13915. (when cwin
  13916. (let ((calendar-move-hook nil))
  13917. (with-selected-window cwin
  13918. (calendar-goto-date
  13919. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  13920. (defun org-goto-calendar (&optional arg)
  13921. "Go to the Emacs calendar at the current date.
  13922. If there is a time stamp in the current line, go to that date.
  13923. A prefix ARG can be used to force the current date."
  13924. (interactive "P")
  13925. (let ((calendar-move-hook nil)
  13926. (calendar-view-holidays-initially-flag nil)
  13927. (calendar-view-diary-initially-flag nil)
  13928. diff)
  13929. (when (or (org-at-timestamp-p 'lax)
  13930. (org-match-line (concat ".*" org-ts-regexp)))
  13931. (let ((d1 (time-to-days nil))
  13932. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  13933. (setq diff (- d2 d1))))
  13934. (calendar)
  13935. (calendar-goto-today)
  13936. (when (and diff (not arg)) (calendar-forward-day diff))))
  13937. (defun org-get-date-from-calendar ()
  13938. "Return a list (month day year) of date at point in calendar."
  13939. (with-current-buffer "*Calendar*"
  13940. (save-match-data
  13941. (calendar-cursor-to-date))))
  13942. (defun org-date-from-calendar ()
  13943. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  13944. If there is already a time stamp at the cursor position, update it."
  13945. (interactive)
  13946. (if (org-at-timestamp-p 'lax)
  13947. (org-timestamp-change 0 'calendar)
  13948. (let ((cal-date (org-get-date-from-calendar)))
  13949. (org-insert-time-stamp
  13950. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  13951. (defcustom org-image-actual-width t
  13952. "When non-nil, use the actual width of images when inlining them.
  13953. When set to a number, use imagemagick (when available) to set the
  13954. image's width to this value.
  13955. When set to a number in a list, try to get the width from any
  13956. #+ATTR.* keyword if it matches a width specification like
  13957. #+ATTR_HTML: :width 300px
  13958. and fall back on that number if none is found.
  13959. When set to nil, try to get the width from an #+ATTR.* keyword
  13960. and fall back on the original width if none is found.
  13961. When set to any other non-nil value, always use the image width.
  13962. This requires Emacs >= 24.1, built with imagemagick support."
  13963. :group 'org-appearance
  13964. :version "24.4"
  13965. :package-version '(Org . "8.0")
  13966. :type '(choice
  13967. (const :tag "Use the image width" t)
  13968. (integer :tag "Use a number of pixels")
  13969. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  13970. (const :tag "Use #+ATTR* or don't resize" nil)))
  13971. (defcustom org-agenda-inhibit-startup nil
  13972. "Inhibit startup when preparing agenda buffers.
  13973. When this variable is t, the initialization of the Org agenda
  13974. buffers is inhibited: e.g. the visibility state is not set, the
  13975. tables are not re-aligned, etc."
  13976. :type 'boolean
  13977. :version "24.3"
  13978. :group 'org-agenda)
  13979. (defcustom org-agenda-ignore-properties nil
  13980. "Avoid updating text properties when building the agenda.
  13981. Properties are used to prepare buffers for effort estimates,
  13982. appointments, statistics and subtree-local categories.
  13983. If you don't use these in the agenda, you can add them to this
  13984. list and agenda building will be a bit faster.
  13985. The value is a list, with zero or more of the symbols `effort', `appt',
  13986. `stats' or `category'."
  13987. :type '(set :greedy t
  13988. (const effort)
  13989. (const appt)
  13990. (const stats)
  13991. (const category))
  13992. :version "26.1"
  13993. :package-version '(Org . "8.3")
  13994. :group 'org-agenda)
  13995. ;;;; Files
  13996. (defun org-save-all-org-buffers ()
  13997. "Save all Org buffers without user confirmation."
  13998. (interactive)
  13999. (message "Saving all Org buffers...")
  14000. (save-some-buffers t (lambda () (and (derived-mode-p 'org-mode) t)))
  14001. (when (featurep 'org-id) (org-id-locations-save))
  14002. (message "Saving all Org buffers... done"))
  14003. (defun org-revert-all-org-buffers ()
  14004. "Revert all Org buffers.
  14005. Prompt for confirmation when there are unsaved changes.
  14006. Be sure you know what you are doing before letting this function
  14007. overwrite your changes.
  14008. This function is useful in a setup where one tracks Org files
  14009. with a version control system, to revert on one machine after pulling
  14010. changes from another. I believe the procedure must be like this:
  14011. 1. \\[org-save-all-org-buffers]
  14012. 2. Pull changes from the other machine, resolve conflicts
  14013. 3. \\[org-revert-all-org-buffers]"
  14014. (interactive)
  14015. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  14016. (user-error "Abort"))
  14017. (save-excursion
  14018. (save-window-excursion
  14019. (dolist (b (buffer-list))
  14020. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  14021. (with-current-buffer b buffer-file-name))
  14022. (pop-to-buffer-same-window b)
  14023. (revert-buffer t 'no-confirm)))
  14024. (when (and (featurep 'org-id) org-id-track-globally)
  14025. (org-id-locations-load)))))
  14026. ;;;; Agenda files
  14027. ;;;###autoload
  14028. (defun org-switchb (&optional arg)
  14029. "Switch between Org buffers.
  14030. With `\\[universal-argument]' prefix, restrict available buffers to files.
  14031. With `\\[universal-argument] \\[universal-argument]' \
  14032. prefix, restrict available buffers to agenda files."
  14033. (interactive "P")
  14034. (let ((blist (org-buffer-list
  14035. (cond ((equal arg '(4)) 'files)
  14036. ((equal arg '(16)) 'agenda)))))
  14037. (pop-to-buffer-same-window
  14038. (completing-read "Org buffer: "
  14039. (mapcar #'list (mapcar #'buffer-name blist))
  14040. nil t))))
  14041. (defun org-buffer-list (&optional predicate exclude-tmp)
  14042. "Return a list of Org buffers.
  14043. PREDICATE can be `export', `files' or `agenda'.
  14044. export restrict the list to Export buffers.
  14045. files restrict the list to buffers visiting Org files.
  14046. agenda restrict the list to buffers visiting agenda files.
  14047. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  14048. (let* ((bfn nil)
  14049. (agenda-files (and (eq predicate 'agenda)
  14050. (mapcar 'file-truename (org-agenda-files t))))
  14051. (filter
  14052. (cond
  14053. ((eq predicate 'files)
  14054. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  14055. ((eq predicate 'export)
  14056. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  14057. ((eq predicate 'agenda)
  14058. (lambda (b)
  14059. (with-current-buffer b
  14060. (and (derived-mode-p 'org-mode)
  14061. (setq bfn (buffer-file-name b))
  14062. (member (file-truename bfn) agenda-files)))))
  14063. (t (lambda (b) (with-current-buffer b
  14064. (or (derived-mode-p 'org-mode)
  14065. (string-match "\\*Org .*Export"
  14066. (buffer-name b)))))))))
  14067. (delq nil
  14068. (mapcar
  14069. (lambda(b)
  14070. (if (and (funcall filter b)
  14071. (or (not exclude-tmp)
  14072. (not (string-match "tmp" (buffer-name b)))))
  14073. b
  14074. nil))
  14075. (buffer-list)))))
  14076. (defun org-agenda-files (&optional unrestricted archives)
  14077. "Get the list of agenda files.
  14078. Optional UNRESTRICTED means return the full list even if a restriction
  14079. is currently in place.
  14080. When ARCHIVES is t, include all archive files that are really being
  14081. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  14082. `org-agenda-archives-mode' is t."
  14083. (let ((files
  14084. (cond
  14085. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  14086. ((stringp org-agenda-files) (org-read-agenda-file-list))
  14087. ((listp org-agenda-files) org-agenda-files)
  14088. (t (error "Invalid value of `org-agenda-files'")))))
  14089. (setq files (apply 'append
  14090. (mapcar (lambda (f)
  14091. (if (file-directory-p f)
  14092. (directory-files
  14093. f t org-agenda-file-regexp)
  14094. (list (expand-file-name f org-directory))))
  14095. files)))
  14096. (when org-agenda-skip-unavailable-files
  14097. (setq files (delq nil
  14098. (mapcar (lambda (file)
  14099. (and (file-readable-p file) file))
  14100. files))))
  14101. (when (or (eq archives t)
  14102. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  14103. (setq files (org-add-archive-files files)))
  14104. files))
  14105. (defun org-agenda-file-p (&optional file)
  14106. "Return non-nil, if FILE is an agenda file.
  14107. If FILE is omitted, use the file associated with the current
  14108. buffer."
  14109. (let ((fname (or file (buffer-file-name))))
  14110. (and fname
  14111. (member (file-truename fname)
  14112. (mapcar #'file-truename (org-agenda-files t))))))
  14113. (defun org-edit-agenda-file-list ()
  14114. "Edit the list of agenda files.
  14115. Depending on setup, this either uses customize to edit the variable
  14116. `org-agenda-files', or it visits the file that is holding the list. In the
  14117. latter case, the buffer is set up in a way that saving it automatically kills
  14118. the buffer and restores the previous window configuration."
  14119. (interactive)
  14120. (if (stringp org-agenda-files)
  14121. (let ((cw (current-window-configuration)))
  14122. (find-file org-agenda-files)
  14123. (setq-local org-window-configuration cw)
  14124. (add-hook 'after-save-hook
  14125. (lambda ()
  14126. (set-window-configuration
  14127. (prog1 org-window-configuration
  14128. (kill-buffer (current-buffer))))
  14129. (org-install-agenda-files-menu)
  14130. (message "New agenda file list installed"))
  14131. nil 'local)
  14132. (message "%s" (substitute-command-keys
  14133. "Edit list and finish with \\[save-buffer]")))
  14134. (customize-variable 'org-agenda-files)))
  14135. (defun org-store-new-agenda-file-list (list)
  14136. "Set new value for the agenda file list and save it correctly."
  14137. (if (stringp org-agenda-files)
  14138. (let ((fe (org-read-agenda-file-list t)) b u)
  14139. (while (setq b (find-buffer-visiting org-agenda-files))
  14140. (kill-buffer b))
  14141. (with-temp-file org-agenda-files
  14142. (insert
  14143. (mapconcat
  14144. (lambda (f) ;; Keep un-expanded entries.
  14145. (if (setq u (assoc f fe))
  14146. (cdr u)
  14147. f))
  14148. list "\n")
  14149. "\n")))
  14150. (let ((org-mode-hook nil) (org-inhibit-startup t)
  14151. (org-insert-mode-line-in-empty-file nil))
  14152. (setq org-agenda-files list)
  14153. (customize-save-variable 'org-agenda-files org-agenda-files))))
  14154. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  14155. "Read the list of agenda files from a file.
  14156. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  14157. filenames, used by `org-store-new-agenda-file-list' to write back
  14158. un-expanded file names."
  14159. (when (file-directory-p org-agenda-files)
  14160. (error "`org-agenda-files' cannot be a single directory"))
  14161. (when (stringp org-agenda-files)
  14162. (with-temp-buffer
  14163. (insert-file-contents org-agenda-files)
  14164. (mapcar
  14165. (lambda (f)
  14166. (let ((e (expand-file-name (substitute-in-file-name f)
  14167. org-directory)))
  14168. (if pair-with-expansion
  14169. (cons e f)
  14170. e)))
  14171. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  14172. ;;;###autoload
  14173. (defun org-cycle-agenda-files ()
  14174. "Cycle through the files in `org-agenda-files'.
  14175. If the current buffer visits an agenda file, find the next one in the list.
  14176. If the current buffer does not, find the first agenda file."
  14177. (interactive)
  14178. (let* ((fs (or (org-agenda-files t)
  14179. (user-error "No agenda files")))
  14180. (files (copy-sequence fs))
  14181. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  14182. file)
  14183. (when tcf
  14184. (while (and (setq file (pop files))
  14185. (not (equal (file-truename file) tcf)))))
  14186. (find-file (car (or files fs)))
  14187. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  14188. (defun org-agenda-file-to-front (&optional to-end)
  14189. "Move/add the current file to the top of the agenda file list.
  14190. If the file is not present in the list, it is added to the front. If it is
  14191. present, it is moved there. With optional argument TO-END, add/move to the
  14192. end of the list."
  14193. (interactive "P")
  14194. (let ((org-agenda-skip-unavailable-files nil)
  14195. (file-alist (mapcar (lambda (x)
  14196. (cons (file-truename x) x))
  14197. (org-agenda-files t)))
  14198. (ctf (file-truename
  14199. (or buffer-file-name
  14200. (user-error "Please save the current buffer to a file"))))
  14201. x had)
  14202. (setq x (assoc ctf file-alist) had x)
  14203. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  14204. (if to-end
  14205. (setq file-alist (append (delq x file-alist) (list x)))
  14206. (setq file-alist (cons x (delq x file-alist))))
  14207. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  14208. (org-install-agenda-files-menu)
  14209. (message "File %s to %s of agenda file list"
  14210. (if had "moved" "added") (if to-end "end" "front"))))
  14211. (defun org-remove-file (&optional file)
  14212. "Remove current file from the list of files in variable `org-agenda-files'.
  14213. These are the files which are being checked for agenda entries.
  14214. Optional argument FILE means use this file instead of the current."
  14215. (interactive)
  14216. (let* ((org-agenda-skip-unavailable-files nil)
  14217. (file (or file buffer-file-name
  14218. (user-error "Current buffer does not visit a file")))
  14219. (true-file (file-truename file))
  14220. (afile (abbreviate-file-name file))
  14221. (files (delq nil (mapcar
  14222. (lambda (x)
  14223. (unless (equal true-file
  14224. (file-truename x))
  14225. x))
  14226. (org-agenda-files t)))))
  14227. (if (not (= (length files) (length (org-agenda-files t))))
  14228. (progn
  14229. (org-store-new-agenda-file-list files)
  14230. (org-install-agenda-files-menu)
  14231. (message "Removed from Org Agenda list: %s" afile))
  14232. (message "File was not in list: %s (not removed)" afile))))
  14233. (defun org-file-menu-entry (file)
  14234. (vector file (list 'find-file file) t))
  14235. (defun org-check-agenda-file (file)
  14236. "Make sure FILE exists. If not, ask user what to do."
  14237. (unless (file-exists-p file)
  14238. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  14239. (abbreviate-file-name file))
  14240. (let ((r (downcase (read-char-exclusive))))
  14241. (cond
  14242. ((equal r ?r)
  14243. (org-remove-file file)
  14244. (throw 'nextfile t))
  14245. (t (user-error "Abort"))))))
  14246. (defun org-get-agenda-file-buffer (file)
  14247. "Get an agenda buffer visiting FILE.
  14248. If the buffer needs to be created, add it to the list of buffers
  14249. which might be released later."
  14250. (let ((buf (org-find-base-buffer-visiting file)))
  14251. (if buf
  14252. buf ; just return it
  14253. ;; Make a new buffer and remember it
  14254. (setq buf (find-file-noselect file))
  14255. (when buf (push buf org-agenda-new-buffers))
  14256. buf)))
  14257. (defun org-release-buffers (blist)
  14258. "Release all buffers in list, asking the user for confirmation when needed.
  14259. When a buffer is unmodified, it is just killed. When modified, it is saved
  14260. \(if the user agrees) and then killed."
  14261. (let (file)
  14262. (dolist (buf blist)
  14263. (setq file (buffer-file-name buf))
  14264. (when (and (buffer-modified-p buf)
  14265. file
  14266. (y-or-n-p (format "Save file %s? " file)))
  14267. (with-current-buffer buf (save-buffer)))
  14268. (kill-buffer buf))))
  14269. (defun org-agenda-prepare-buffers (files)
  14270. "Create buffers for all agenda files, protect archived trees and comments."
  14271. (interactive)
  14272. (let ((pa '(:org-archived t))
  14273. (pc '(:org-comment t))
  14274. (pall '(:org-archived t :org-comment t))
  14275. (inhibit-read-only t)
  14276. (org-inhibit-startup org-agenda-inhibit-startup)
  14277. (rea (org-make-tag-string (list org-archive-tag)))
  14278. re pos)
  14279. (setq org-tag-alist-for-agenda nil
  14280. org-tag-groups-alist-for-agenda nil)
  14281. (save-excursion
  14282. (save-restriction
  14283. (dolist (file files)
  14284. (catch 'nextfile
  14285. (if (bufferp file)
  14286. (set-buffer file)
  14287. (org-check-agenda-file file)
  14288. (set-buffer (org-get-agenda-file-buffer file)))
  14289. (widen)
  14290. (org-set-regexps-and-options 'tags-only)
  14291. (setq pos (point))
  14292. (or (memq 'category org-agenda-ignore-properties)
  14293. (org-refresh-category-properties))
  14294. (or (memq 'stats org-agenda-ignore-properties)
  14295. (org-refresh-stats-properties))
  14296. (or (memq 'effort org-agenda-ignore-properties)
  14297. (org-refresh-effort-properties))
  14298. (or (memq 'appt org-agenda-ignore-properties)
  14299. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  14300. (setq org-todo-keywords-for-agenda
  14301. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  14302. (setq org-done-keywords-for-agenda
  14303. (append org-done-keywords-for-agenda org-done-keywords))
  14304. (setq org-todo-keyword-alist-for-agenda
  14305. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  14306. (setq org-tag-alist-for-agenda
  14307. (org--tag-add-to-alist
  14308. org-tag-alist-for-agenda
  14309. org-current-tag-alist))
  14310. ;; Merge current file's tag groups into global
  14311. ;; `org-tag-groups-alist-for-agenda'.
  14312. (when org-group-tags
  14313. (dolist (alist org-tag-groups-alist)
  14314. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  14315. (if old
  14316. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  14317. (push alist org-tag-groups-alist-for-agenda)))))
  14318. (with-silent-modifications
  14319. (save-excursion
  14320. (remove-text-properties (point-min) (point-max) pall)
  14321. (when org-agenda-skip-archived-trees
  14322. (goto-char (point-min))
  14323. (while (re-search-forward rea nil t)
  14324. (when (org-at-heading-p t)
  14325. (add-text-properties (line-beginning-position)
  14326. (org-end-of-subtree t) pa))))
  14327. (goto-char (point-min))
  14328. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  14329. (while (re-search-forward re nil t)
  14330. (when (save-match-data (org-in-commented-heading-p t))
  14331. (add-text-properties
  14332. (match-beginning 0) (org-end-of-subtree t) pc)))))
  14333. (goto-char pos)))))
  14334. (setq org-todo-keywords-for-agenda
  14335. (org-uniquify org-todo-keywords-for-agenda))
  14336. (setq org-todo-keyword-alist-for-agenda
  14337. (org-uniquify org-todo-keyword-alist-for-agenda))))
  14338. ;;;; CDLaTeX minor mode
  14339. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  14340. "Keymap for the minor `org-cdlatex-mode'.")
  14341. (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
  14342. (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
  14343. (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
  14344. (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
  14345. (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
  14346. (defvar org-cdlatex-texmathp-advice-is-done nil
  14347. "Flag remembering if we have applied the advice to texmathp already.")
  14348. (define-minor-mode org-cdlatex-mode
  14349. "Toggle the minor `org-cdlatex-mode'.
  14350. This mode supports entering LaTeX environment and math in LaTeX fragments
  14351. in Org mode.
  14352. \\{org-cdlatex-mode-map}"
  14353. :lighter " OCDL"
  14354. (when org-cdlatex-mode
  14355. (require 'cdlatex)
  14356. (run-hooks 'cdlatex-mode-hook)
  14357. (cdlatex-compute-tables))
  14358. (unless org-cdlatex-texmathp-advice-is-done
  14359. (setq org-cdlatex-texmathp-advice-is-done t)
  14360. (defadvice texmathp (around org-math-always-on activate)
  14361. "Always return t in Org buffers.
  14362. This is because we want to insert math symbols without dollars even outside
  14363. the LaTeX math segments. If Org mode thinks that point is actually inside
  14364. an embedded LaTeX fragment, let `texmathp' do its job.
  14365. `\\[org-cdlatex-mode-map]'"
  14366. (interactive)
  14367. (let (p)
  14368. (cond
  14369. ((not (derived-mode-p 'org-mode)) ad-do-it)
  14370. ((eq this-command 'cdlatex-math-symbol)
  14371. (setq ad-return-value t
  14372. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  14373. (t
  14374. (let ((p (org-inside-LaTeX-fragment-p)))
  14375. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  14376. (setq ad-return-value t
  14377. texmathp-why '("Org mode embedded math" . 0))
  14378. (when p ad-do-it)))))))))
  14379. (defun turn-on-org-cdlatex ()
  14380. "Unconditionally turn on `org-cdlatex-mode'."
  14381. (org-cdlatex-mode 1))
  14382. (defun org-try-cdlatex-tab ()
  14383. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  14384. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  14385. - inside a LaTeX fragment, or
  14386. - after the first word in a line, where an abbreviation expansion could
  14387. insert a LaTeX environment."
  14388. (when org-cdlatex-mode
  14389. (cond
  14390. ;; Before any word on the line: No expansion possible.
  14391. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  14392. ;; Just after first word on the line: Expand it. Make sure it
  14393. ;; cannot happen on headlines, though.
  14394. ((save-excursion
  14395. (skip-chars-backward "a-zA-Z0-9*")
  14396. (skip-chars-backward " \t")
  14397. (and (bolp) (not (org-at-heading-p))))
  14398. (cdlatex-tab) t)
  14399. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  14400. (defun org-cdlatex-underscore-caret (&optional _arg)
  14401. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  14402. Revert to the normal definition outside of these fragments."
  14403. (interactive "P")
  14404. (if (org-inside-LaTeX-fragment-p)
  14405. (call-interactively 'cdlatex-sub-superscript)
  14406. (let (org-cdlatex-mode)
  14407. (call-interactively (key-binding (vector last-input-event))))))
  14408. (defun org-cdlatex-math-modify (&optional _arg)
  14409. "Execute `cdlatex-math-modify' in LaTeX fragments.
  14410. Revert to the normal definition outside of these fragments."
  14411. (interactive "P")
  14412. (if (org-inside-LaTeX-fragment-p)
  14413. (call-interactively 'cdlatex-math-modify)
  14414. (let (org-cdlatex-mode)
  14415. (call-interactively (key-binding (vector last-input-event))))))
  14416. (defun org-cdlatex-environment-indent (&optional environment item)
  14417. "Execute `cdlatex-environment' and indent the inserted environment.
  14418. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  14419. The inserted environment is indented to current indentation
  14420. unless point is at the beginning of the line, in which the
  14421. environment remains unintended."
  14422. (interactive)
  14423. ;; cdlatex-environment always return nil. Therefore, capture output
  14424. ;; first and determine if an environment was selected.
  14425. (let* ((beg (point-marker))
  14426. (end (copy-marker (point) t))
  14427. (inserted (progn
  14428. (ignore-errors (cdlatex-environment environment item))
  14429. (< beg end)))
  14430. ;; Figure out how many lines to move forward after the
  14431. ;; environment has been inserted.
  14432. (lines (when inserted
  14433. (save-excursion
  14434. (- (cl-loop while (< beg (point))
  14435. with x = 0
  14436. do (forward-line -1)
  14437. (cl-incf x)
  14438. finally return x)
  14439. (if (progn (goto-char beg)
  14440. (and (progn (skip-chars-forward " \t") (eolp))
  14441. (progn (skip-chars-backward " \t") (bolp))))
  14442. 1 0)))))
  14443. (env (org-trim (delete-and-extract-region beg end))))
  14444. (when inserted
  14445. ;; Get indentation of next line unless at column 0.
  14446. (let ((ind (if (bolp) 0
  14447. (save-excursion
  14448. (org-return t)
  14449. (prog1 (current-indentation)
  14450. (when (progn (skip-chars-forward " \t") (eolp))
  14451. (delete-region beg (point)))))))
  14452. (bol (progn (skip-chars-backward " \t") (bolp))))
  14453. ;; Insert a newline before environment unless at column zero
  14454. ;; to "escape" the current line. Insert a newline if
  14455. ;; something is one the same line as \end{ENVIRONMENT}.
  14456. (insert
  14457. (concat (unless bol "\n") env
  14458. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  14459. (unless (zerop ind)
  14460. (save-excursion
  14461. (goto-char beg)
  14462. (while (< (point) end)
  14463. (unless (eolp) (indent-line-to ind))
  14464. (forward-line))))
  14465. (goto-char beg)
  14466. (forward-line lines)
  14467. (indent-line-to ind)))
  14468. (set-marker beg nil)
  14469. (set-marker end nil)))
  14470. ;;;; LaTeX fragments
  14471. (defun org-inside-LaTeX-fragment-p ()
  14472. "Test if point is inside a LaTeX fragment.
  14473. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  14474. sequence appearing also before point.
  14475. Even though the matchers for math are configurable, this function assumes
  14476. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  14477. delimiters are skipped when they have been removed by customization.
  14478. The return value is nil, or a cons cell with the delimiter and the
  14479. position of this delimiter.
  14480. This function does a reasonably good job, but can locally be fooled by
  14481. for example currency specifications. For example it will assume being in
  14482. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  14483. fragments that are properly closed, but during editing, we have to live
  14484. with the uncertainty caused by missing closing delimiters. This function
  14485. looks only before point, not after."
  14486. (catch 'exit
  14487. (let ((pos (point))
  14488. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  14489. (lim (progn
  14490. (re-search-backward (concat "^\\(" paragraph-start "\\)") nil
  14491. 'move)
  14492. (point)))
  14493. dd-on str (start 0) m re)
  14494. (goto-char pos)
  14495. (when dodollar
  14496. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  14497. re (nth 1 (assoc "$" org-latex-regexps)))
  14498. (while (string-match re str start)
  14499. (cond
  14500. ((= (match-end 0) (length str))
  14501. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  14502. ((= (match-end 0) (- (length str) 5))
  14503. (throw 'exit nil))
  14504. (t (setq start (match-end 0))))))
  14505. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  14506. (goto-char pos)
  14507. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  14508. (and (match-beginning 2) (throw 'exit nil))
  14509. ;; count $$
  14510. (while (re-search-backward "\\$\\$" lim t)
  14511. (setq dd-on (not dd-on)))
  14512. (goto-char pos)
  14513. (when dd-on (cons "$$" m))))))
  14514. (defun org-inside-latex-macro-p ()
  14515. "Is point inside a LaTeX macro or its arguments?"
  14516. (save-match-data
  14517. (org-in-regexp
  14518. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  14519. (defun org--make-preview-overlay (beg end image &optional imagetype)
  14520. "Build an overlay between BEG and END using IMAGE file.
  14521. Argument IMAGETYPE is the extension of the displayed image,
  14522. as a string. It defaults to \"png\"."
  14523. (let ((ov (make-overlay beg end))
  14524. (imagetype (or (intern imagetype) 'png)))
  14525. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  14526. (overlay-put ov 'evaporate t)
  14527. (overlay-put ov
  14528. 'modification-hooks
  14529. (list (lambda (o _flag _beg _end &optional _l)
  14530. (delete-overlay o))))
  14531. (overlay-put ov
  14532. 'display
  14533. (list 'image :type imagetype :file image :ascent 'center))))
  14534. (defun org-clear-latex-preview (&optional beg end)
  14535. "Remove all overlays with LaTeX fragment images in current buffer.
  14536. When optional arguments BEG and END are non-nil, remove all
  14537. overlays between them instead. Return a non-nil value when some
  14538. overlays were removed, nil otherwise."
  14539. (let ((overlays
  14540. (cl-remove-if-not
  14541. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  14542. (overlays-in (or beg (point-min)) (or end (point-max))))))
  14543. (mapc #'delete-overlay overlays)
  14544. overlays))
  14545. (defun org--latex-preview-region (beg end)
  14546. "Preview LaTeX fragments between BEG and END.
  14547. BEG and END are buffer positions."
  14548. (let ((file (buffer-file-name (buffer-base-buffer))))
  14549. (save-excursion
  14550. (org-format-latex
  14551. (concat org-preview-latex-image-directory "org-ltximg")
  14552. beg end
  14553. ;; Emacs cannot overlay images from remote hosts. Create it in
  14554. ;; `temporary-file-directory' instead.
  14555. (if (or (not file) (file-remote-p file))
  14556. temporary-file-directory
  14557. default-directory)
  14558. 'overlays nil 'forbuffer org-preview-latex-default-process))))
  14559. (defun org-latex-preview (&optional arg)
  14560. "Toggle preview of the LaTeX fragment at point.
  14561. If the cursor is on a LaTeX fragment, create the image and
  14562. overlay it over the source code, if there is none. Remove it
  14563. otherwise. If there is no fragment at point, display images for
  14564. all fragments in the current section.
  14565. With a `\\[universal-argument]' prefix argument ARG, clear images \
  14566. for all fragments
  14567. in the current section.
  14568. With a `\\[universal-argument] \\[universal-argument]' prefix \
  14569. argument ARG, display image for all
  14570. fragments in the buffer.
  14571. With a `\\[universal-argument] \\[universal-argument] \
  14572. \\[universal-argument]' prefix argument ARG, clear image for all
  14573. fragments in the buffer."
  14574. (interactive "P")
  14575. (cond
  14576. ((not (display-graphic-p)) nil)
  14577. ;; Clear whole buffer.
  14578. ((equal arg '(64))
  14579. (org-clear-latex-preview (point-min) (point-max))
  14580. (message "LaTeX previews removed from buffer"))
  14581. ;; Preview whole buffer.
  14582. ((equal arg '(16))
  14583. (message "Creating LaTeX previews in buffer...")
  14584. (org--latex-preview-region (point-min) (point-max))
  14585. (message "Creating LaTeX previews in buffer... done."))
  14586. ;; Clear current section.
  14587. ((equal arg '(4))
  14588. (org-clear-latex-preview
  14589. (if (org-before-first-heading-p) (point-min)
  14590. (save-excursion
  14591. (org-with-limited-levels (org-back-to-heading t) (point))))
  14592. (org-with-limited-levels (org-entry-end-position))))
  14593. ;; Toggle preview on LaTeX code at point.
  14594. ((let ((datum (org-element-context)))
  14595. (and (memq (org-element-type datum) '(latex-environment latex-fragment))
  14596. (let ((beg (org-element-property :begin datum))
  14597. (end (org-element-property :end datum)))
  14598. (if (org-clear-latex-preview beg end)
  14599. (message "LaTeX preview removed")
  14600. (message "Creating LaTeX preview...")
  14601. (org--latex-preview-region beg end)
  14602. (message "Creating LaTeX preview... done."))
  14603. t))))
  14604. ;; Preview current section.
  14605. (t
  14606. (let ((beg (if (org-before-first-heading-p) (point-min)
  14607. (save-excursion
  14608. (org-with-limited-levels (org-back-to-heading t) (point)))))
  14609. (end (org-with-limited-levels (org-entry-end-position))))
  14610. (message "Creating LaTeX previews in section...")
  14611. (org--latex-preview-region beg end)
  14612. (message "Creating LaTeX previews in section... done.")))))
  14613. (defun org-format-latex
  14614. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  14615. "Replace LaTeX fragments with links to an image.
  14616. The function takes care of creating the replacement image.
  14617. Only consider fragments between BEG and END when those are
  14618. provided.
  14619. When optional argument OVERLAYS is non-nil, display the image on
  14620. top of the fragment instead of replacing it.
  14621. PROCESSING-TYPE is the conversion method to use, as a symbol.
  14622. Some of the options can be changed using the variable
  14623. `org-format-latex-options', which see."
  14624. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  14625. (unless (eq processing-type 'verbatim)
  14626. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  14627. (cnt 0)
  14628. checkdir-flag)
  14629. (goto-char (or beg (point-min)))
  14630. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  14631. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  14632. (overlay-recenter (or end (point-max))))
  14633. (while (re-search-forward math-regexp end t)
  14634. (unless (and overlays
  14635. (eq (get-char-property (point) 'org-overlay-type)
  14636. 'org-latex-overlay))
  14637. (let* ((context (org-element-context))
  14638. (type (org-element-type context)))
  14639. (when (memq type '(latex-environment latex-fragment))
  14640. (let ((block-type (eq type 'latex-environment))
  14641. (value (org-element-property :value context))
  14642. (beg (org-element-property :begin context))
  14643. (end (save-excursion
  14644. (goto-char (org-element-property :end context))
  14645. (skip-chars-backward " \r\t\n")
  14646. (point))))
  14647. (cond
  14648. ((eq processing-type 'mathjax)
  14649. ;; Prepare for MathJax processing.
  14650. (if (not (string-match "\\`\\$\\$?" value))
  14651. (goto-char end)
  14652. (delete-region beg end)
  14653. (if (string= (match-string 0 value) "$$")
  14654. (insert "\\[" (substring value 2 -2) "\\]")
  14655. (insert "\\(" (substring value 1 -1) "\\)"))))
  14656. ((eq processing-type 'html)
  14657. (goto-char beg)
  14658. (delete-region beg end)
  14659. (insert (org-format-latex-as-html value)))
  14660. ((assq processing-type org-preview-latex-process-alist)
  14661. ;; Process to an image.
  14662. (cl-incf cnt)
  14663. (goto-char beg)
  14664. (let* ((processing-info
  14665. (cdr (assq processing-type org-preview-latex-process-alist)))
  14666. (face (face-at-point))
  14667. ;; Get the colors from the face at point.
  14668. (fg
  14669. (let ((color (plist-get org-format-latex-options
  14670. :foreground)))
  14671. (if forbuffer
  14672. (cond
  14673. ((eq color 'auto)
  14674. (face-attribute face :foreground nil 'default))
  14675. ((eq color 'default)
  14676. (face-attribute 'default :foreground nil))
  14677. (t color))
  14678. color)))
  14679. (bg
  14680. (let ((color (plist-get org-format-latex-options
  14681. :background)))
  14682. (if forbuffer
  14683. (cond
  14684. ((eq color 'auto)
  14685. (face-attribute face :background nil 'default))
  14686. ((eq color 'default)
  14687. (face-attribute 'default :background nil))
  14688. (t color))
  14689. color)))
  14690. (hash (sha1 (prin1-to-string
  14691. (list org-format-latex-header
  14692. org-latex-default-packages-alist
  14693. org-latex-packages-alist
  14694. org-format-latex-options
  14695. forbuffer value fg bg))))
  14696. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  14697. (absprefix (expand-file-name prefix dir))
  14698. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  14699. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  14700. (sep (and block-type "\n\n"))
  14701. (link (concat sep "[[file:" linkfile "]]" sep))
  14702. (options
  14703. (org-combine-plists
  14704. org-format-latex-options
  14705. `(:foreground ,fg :background ,bg))))
  14706. (when msg (message msg cnt))
  14707. (unless checkdir-flag ; Ensure the directory exists.
  14708. (setq checkdir-flag t)
  14709. (let ((todir (file-name-directory absprefix)))
  14710. (unless (file-directory-p todir)
  14711. (make-directory todir t))))
  14712. (unless (file-exists-p movefile)
  14713. (org-create-formula-image
  14714. value movefile options forbuffer processing-type))
  14715. (if overlays
  14716. (progn
  14717. (dolist (o (overlays-in beg end))
  14718. (when (eq (overlay-get o 'org-overlay-type)
  14719. 'org-latex-overlay)
  14720. (delete-overlay o)))
  14721. (org--make-preview-overlay beg end movefile imagetype)
  14722. (goto-char end))
  14723. (delete-region beg end)
  14724. (insert
  14725. (org-add-props link
  14726. (list 'org-latex-src
  14727. (replace-regexp-in-string "\"" "" value)
  14728. 'org-latex-src-embed-type
  14729. (if block-type 'paragraph 'character)))))))
  14730. ((eq processing-type 'mathml)
  14731. ;; Process to MathML.
  14732. (unless (org-format-latex-mathml-available-p)
  14733. (user-error "LaTeX to MathML converter not configured"))
  14734. (cl-incf cnt)
  14735. (when msg (message msg cnt))
  14736. (goto-char beg)
  14737. (delete-region beg end)
  14738. (insert (org-format-latex-as-mathml
  14739. value block-type prefix dir)))
  14740. (t
  14741. (error "Unknown conversion process %s for LaTeX fragments"
  14742. processing-type)))))))))))
  14743. (defun org-create-math-formula (latex-frag &optional mathml-file)
  14744. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  14745. Use `org-latex-to-mathml-convert-command'. If the conversion is
  14746. successful, return the portion between \"<math...> </math>\"
  14747. elements otherwise return nil. When MATHML-FILE is specified,
  14748. write the results in to that file. When invoked as an
  14749. interactive command, prompt for LATEX-FRAG, with initial value
  14750. set to the current active region and echo the results for user
  14751. inspection."
  14752. (interactive (list (let ((frag (when (org-region-active-p)
  14753. (buffer-substring-no-properties
  14754. (region-beginning) (region-end)))))
  14755. (read-string "LaTeX Fragment: " frag nil frag))))
  14756. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  14757. (let* ((tmp-in-file
  14758. (let ((file (file-relative-name
  14759. (make-temp-name (expand-file-name "ltxmathml-in")))))
  14760. (write-region latex-frag nil file)
  14761. file))
  14762. (tmp-out-file (file-relative-name
  14763. (make-temp-name (expand-file-name "ltxmathml-out"))))
  14764. (cmd (format-spec
  14765. org-latex-to-mathml-convert-command
  14766. `((?j . ,(and org-latex-to-mathml-jar-file
  14767. (shell-quote-argument
  14768. (expand-file-name
  14769. org-latex-to-mathml-jar-file))))
  14770. (?I . ,(shell-quote-argument tmp-in-file))
  14771. (?i . ,latex-frag)
  14772. (?o . ,(shell-quote-argument tmp-out-file)))))
  14773. mathml shell-command-output)
  14774. (when (called-interactively-p 'any)
  14775. (unless (org-format-latex-mathml-available-p)
  14776. (user-error "LaTeX to MathML converter not configured")))
  14777. (message "Running %s" cmd)
  14778. (setq shell-command-output (shell-command-to-string cmd))
  14779. (setq mathml
  14780. (when (file-readable-p tmp-out-file)
  14781. (with-current-buffer (find-file-noselect tmp-out-file t)
  14782. (goto-char (point-min))
  14783. (when (re-search-forward
  14784. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  14785. (regexp-quote
  14786. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  14787. nil t)
  14788. (prog1 (match-string 0) (kill-buffer))))))
  14789. (cond
  14790. (mathml
  14791. (setq mathml
  14792. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  14793. (when mathml-file
  14794. (write-region mathml nil mathml-file))
  14795. (when (called-interactively-p 'any)
  14796. (message mathml)))
  14797. ((warn "LaTeX to MathML conversion failed")
  14798. (message shell-command-output)))
  14799. (delete-file tmp-in-file)
  14800. (when (file-exists-p tmp-out-file)
  14801. (delete-file tmp-out-file))
  14802. mathml))
  14803. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  14804. prefix &optional dir)
  14805. "Use `org-create-math-formula' but check local cache first."
  14806. (let* ((absprefix (expand-file-name prefix dir))
  14807. (print-length nil) (print-level nil)
  14808. (formula-id (concat
  14809. "formula-"
  14810. (sha1
  14811. (prin1-to-string
  14812. (list latex-frag
  14813. org-latex-to-mathml-convert-command)))))
  14814. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  14815. (formula-cache-dir (file-name-directory formula-cache)))
  14816. (unless (file-directory-p formula-cache-dir)
  14817. (make-directory formula-cache-dir t))
  14818. (unless (file-exists-p formula-cache)
  14819. (org-create-math-formula latex-frag formula-cache))
  14820. (if (file-exists-p formula-cache)
  14821. ;; Successful conversion. Return the link to MathML file.
  14822. (org-add-props
  14823. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  14824. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  14825. 'org-latex-src-embed-type (if latex-frag-type
  14826. 'paragraph 'character)))
  14827. ;; Failed conversion. Return the LaTeX fragment verbatim
  14828. latex-frag)))
  14829. (defun org-format-latex-as-html (latex-fragment)
  14830. "Convert LATEX-FRAGMENT to HTML.
  14831. This uses `org-latex-to-html-convert-command', which see."
  14832. (let ((cmd (format-spec org-latex-to-html-convert-command
  14833. `((?i . ,latex-fragment)))))
  14834. (message "Running %s" cmd)
  14835. (shell-command-to-string cmd)))
  14836. (defun org--get-display-dpi ()
  14837. "Get the DPI of the display.
  14838. The function assumes that the display has the same pixel width in
  14839. the horizontal and vertical directions."
  14840. (if (display-graphic-p)
  14841. (round (/ (display-pixel-height)
  14842. (/ (display-mm-height) 25.4)))
  14843. (error "Attempt to calculate the dpi of a non-graphic display")))
  14844. (defun org-create-formula-image
  14845. (string tofile options buffer &optional processing-type)
  14846. "Create an image from LaTeX source using external processes.
  14847. The LaTeX STRING is saved to a temporary LaTeX file, then
  14848. converted to an image file by process PROCESSING-TYPE defined in
  14849. `org-preview-latex-process-alist'. A nil value defaults to
  14850. `org-preview-latex-default-process'.
  14851. The generated image file is eventually moved to TOFILE.
  14852. The OPTIONS argument controls the size, foreground color and
  14853. background color of the generated image.
  14854. When BUFFER non-nil, this function is used for LaTeX previewing.
  14855. Otherwise, it is used to deal with LaTeX snippets showed in
  14856. a HTML file."
  14857. (let* ((processing-type (or processing-type
  14858. org-preview-latex-default-process))
  14859. (processing-info
  14860. (cdr (assq processing-type org-preview-latex-process-alist)))
  14861. (programs (plist-get processing-info :programs))
  14862. (error-message (or (plist-get processing-info :message) ""))
  14863. (image-input-type (plist-get processing-info :image-input-type))
  14864. (image-output-type (plist-get processing-info :image-output-type))
  14865. (post-clean (or (plist-get processing-info :post-clean)
  14866. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  14867. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  14868. (latex-header
  14869. (or (plist-get processing-info :latex-header)
  14870. (org-latex-make-preamble
  14871. (org-export-get-environment (org-export-get-backend 'latex))
  14872. org-format-latex-header
  14873. 'snippet)))
  14874. (latex-compiler (plist-get processing-info :latex-compiler))
  14875. (image-converter (plist-get processing-info :image-converter))
  14876. (tmpdir temporary-file-directory)
  14877. (texfilebase (make-temp-name
  14878. (expand-file-name "orgtex" tmpdir)))
  14879. (texfile (concat texfilebase ".tex"))
  14880. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  14881. '(1.0 . 1.0)))
  14882. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  14883. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  14884. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  14885. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  14886. "Black"))
  14887. (bg (or (plist-get options (if buffer :background :html-background))
  14888. "Transparent"))
  14889. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  14890. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  14891. (dolist (program programs)
  14892. (org-check-external-command program error-message))
  14893. (if (eq fg 'default)
  14894. (setq fg (org-latex-color :foreground))
  14895. (setq fg (org-latex-color-format fg)))
  14896. (setq bg (cond
  14897. ((eq bg 'default) (org-latex-color :background))
  14898. ((string= bg "Transparent") nil)
  14899. (t (org-latex-color-format bg))))
  14900. ;; Remove TeX \par at end of snippet to avoid trailing space.
  14901. (if (string-suffix-p string "\n")
  14902. (aset string (1- (length string)) ?%)
  14903. (setq string (concat string "%")))
  14904. (with-temp-file texfile
  14905. (insert latex-header)
  14906. (insert "\n\\begin{document}\n"
  14907. "\\definecolor{fg}{rgb}{" fg "}%\n"
  14908. (if bg
  14909. (concat "\\definecolor{bg}{rgb}{" bg "}%\n"
  14910. "\n\\pagecolor{bg}%\n")
  14911. "")
  14912. "\n{\\color{fg}\n"
  14913. string
  14914. "\n}\n"
  14915. "\n\\end{document}\n"))
  14916. (let* ((err-msg (format "Please adjust `%s' part of \
  14917. `org-preview-latex-process-alist'."
  14918. processing-type))
  14919. (image-input-file
  14920. (org-compile-file
  14921. texfile latex-compiler image-input-type err-msg log-buf))
  14922. (image-output-file
  14923. (org-compile-file
  14924. image-input-file image-converter image-output-type err-msg log-buf
  14925. `((?D . ,(shell-quote-argument (format "%s" dpi)))
  14926. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  14927. (copy-file image-output-file tofile 'replace)
  14928. (dolist (e post-clean)
  14929. (when (file-exists-p (concat texfilebase e))
  14930. (delete-file (concat texfilebase e))))
  14931. image-output-file)))
  14932. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  14933. "Fill a LaTeX header template TPL.
  14934. In the template, the following place holders will be recognized:
  14935. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  14936. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  14937. [PACKAGES] \\usepackage statements for PKG
  14938. [NO-PACKAGES] do not include PKG
  14939. [EXTRA] the string EXTRA
  14940. [NO-EXTRA] do not include EXTRA
  14941. For backward compatibility, if both the positive and the negative place
  14942. holder is missing, the positive one (without the \"NO-\") will be
  14943. assumed to be present at the end of the template.
  14944. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  14945. EXTRA is a string.
  14946. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  14947. (let (rpl (end ""))
  14948. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  14949. (setq rpl (if (or (match-end 1) (not def-pkg))
  14950. "" (org-latex-packages-to-string def-pkg snippets-p t))
  14951. tpl (replace-match rpl t t tpl))
  14952. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  14953. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  14954. (setq rpl (if (or (match-end 1) (not pkg))
  14955. "" (org-latex-packages-to-string pkg snippets-p t))
  14956. tpl (replace-match rpl t t tpl))
  14957. (when pkg (setq end
  14958. (concat end "\n"
  14959. (org-latex-packages-to-string pkg snippets-p)))))
  14960. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  14961. (setq rpl (if (or (match-end 1) (not extra))
  14962. "" (concat extra "\n"))
  14963. tpl (replace-match rpl t t tpl))
  14964. (when (and extra (string-match "\\S-" extra))
  14965. (setq end (concat end "\n" extra))))
  14966. (if (string-match "\\S-" end)
  14967. (concat tpl "\n" end)
  14968. tpl)))
  14969. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  14970. "Turn an alist of packages into a string with the \\usepackage macros."
  14971. (setq pkg (mapconcat (lambda(p)
  14972. (cond
  14973. ((stringp p) p)
  14974. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  14975. (format "%% Package %s omitted" (cadr p)))
  14976. ((equal "" (car p))
  14977. (format "\\usepackage{%s}" (cadr p)))
  14978. (t
  14979. (format "\\usepackage[%s]{%s}"
  14980. (car p) (cadr p)))))
  14981. pkg
  14982. "\n"))
  14983. (if newline (concat pkg "\n") pkg))
  14984. (defun org-dvipng-color (attr)
  14985. "Return a RGB color specification for dvipng."
  14986. (org-dvipng-color-format (face-attribute 'default attr nil)))
  14987. (defun org-dvipng-color-format (color-name)
  14988. "Convert COLOR-NAME to a RGB color value for dvipng."
  14989. (apply #'format "rgb %s %s %s"
  14990. (mapcar 'org-normalize-color
  14991. (color-values color-name))))
  14992. (defun org-latex-color (attr)
  14993. "Return a RGB color for the LaTeX color package."
  14994. (org-latex-color-format (face-attribute 'default attr nil)))
  14995. (defun org-latex-color-format (color-name)
  14996. "Convert COLOR-NAME to a RGB color value."
  14997. (apply #'format "%s,%s,%s"
  14998. (mapcar 'org-normalize-color
  14999. (color-values color-name))))
  15000. (defun org-normalize-color (value)
  15001. "Return string to be used as color value for an RGB component."
  15002. (format "%g" (/ value 65535.0)))
  15003. ;; Image display
  15004. (defvar-local org-inline-image-overlays nil)
  15005. (defun org-toggle-inline-images (&optional include-linked)
  15006. "Toggle the display of inline images.
  15007. INCLUDE-LINKED is passed to `org-display-inline-images'."
  15008. (interactive "P")
  15009. (if org-inline-image-overlays
  15010. (progn
  15011. (org-remove-inline-images)
  15012. (when (called-interactively-p 'interactive)
  15013. (message "Inline image display turned off")))
  15014. (org-display-inline-images include-linked)
  15015. (when (called-interactively-p 'interactive)
  15016. (message (if org-inline-image-overlays
  15017. (format "%d images displayed inline"
  15018. (length org-inline-image-overlays))
  15019. "No images to display inline")))))
  15020. (defun org-redisplay-inline-images ()
  15021. "Assure display of inline images and refresh them."
  15022. (interactive)
  15023. (org-toggle-inline-images)
  15024. (unless org-inline-image-overlays
  15025. (org-toggle-inline-images)))
  15026. ;; For without-x builds.
  15027. (declare-function image-flush "image" (spec &optional frame))
  15028. (defcustom org-display-remote-inline-images 'skip
  15029. "How to display remote inline images.
  15030. Possible values of this option are:
  15031. skip Don't display remote images.
  15032. download Always download and display remote images.
  15033. cache Display remote images, and open them in separate buffers
  15034. for caching. Silently update the image buffer when a file
  15035. change is detected."
  15036. :group 'org-appearance
  15037. :package-version '(Org . "9.4")
  15038. :type '(choice
  15039. (const :tag "Ignore remote images" skip)
  15040. (const :tag "Always display remote images" download)
  15041. (const :tag "Display and silently update remote images" cache))
  15042. :safe #'symbolp)
  15043. (defun org--create-inline-image (file width)
  15044. "Create image located at FILE, or return nil.
  15045. WIDTH is the width of the image. The image may not be created
  15046. according to the value of `org-display-remote-inline-images'."
  15047. (let* ((remote? (file-remote-p file))
  15048. (file-or-data
  15049. (pcase org-display-remote-inline-images
  15050. ((guard (not remote?)) file)
  15051. (`download (with-temp-buffer
  15052. (set-buffer-multibyte nil)
  15053. (insert-file-contents-literally file)
  15054. (buffer-string)))
  15055. (`cache (let ((revert-without-query '(".")))
  15056. (with-current-buffer (find-file-noselect file)
  15057. (buffer-string))))
  15058. (`skip nil)
  15059. (other
  15060. (message "Invalid value of `org-display-remote-inline-images': %S"
  15061. other)
  15062. nil))))
  15063. (when file-or-data
  15064. (create-image file-or-data
  15065. (and (image-type-available-p 'imagemagick)
  15066. width
  15067. 'imagemagick)
  15068. remote?
  15069. :width width))))
  15070. (defun org-display-inline-images (&optional include-linked refresh beg end)
  15071. "Display inline images.
  15072. An inline image is a link which follows either of these
  15073. conventions:
  15074. 1. Its path is a file with an extension matching return value
  15075. from `image-file-name-regexp' and it has no contents.
  15076. 2. Its description consists in a single link of the previous
  15077. type. In this case, that link must be a well-formed plain
  15078. or angle link, i.e., it must have an explicit \"file\" type.
  15079. Equip each image with the key-map `image-map'.
  15080. When optional argument INCLUDE-LINKED is non-nil, also links with
  15081. a text description part will be inlined. This can be nice for
  15082. a quick look at those images, but it does not reflect what
  15083. exported files will look like.
  15084. When optional argument REFRESH is non-nil, refresh existing
  15085. images between BEG and END. This will create new image displays
  15086. only if necessary.
  15087. BEG and END define the considered part. They default to the
  15088. buffer boundaries with possible narrowing."
  15089. (interactive "P")
  15090. (when (display-graphic-p)
  15091. (unless refresh
  15092. (org-remove-inline-images)
  15093. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  15094. (let ((end (or end (point-max))))
  15095. (org-with-point-at (or beg (point-min))
  15096. (let* ((case-fold-search t)
  15097. (file-extension-re (image-file-name-regexp))
  15098. (link-abbrevs (mapcar #'car
  15099. (append org-link-abbrev-alist-local
  15100. org-link-abbrev-alist)))
  15101. ;; Check absolute, relative file names and explicit
  15102. ;; "file:" links. Also check link abbreviations since
  15103. ;; some might expand to "file" links.
  15104. (file-types-re
  15105. (format "\\[\\[\\(?:file%s:\\|attachment:\\|[./~]\\)\\|\\]\\[\\(<?file:\\)"
  15106. (if (not link-abbrevs) ""
  15107. (concat "\\|" (regexp-opt link-abbrevs))))))
  15108. (while (re-search-forward file-types-re end t)
  15109. (let* ((link (org-element-lineage
  15110. (save-match-data (org-element-context))
  15111. '(link) t))
  15112. (linktype (org-element-property :type link))
  15113. (inner-start (match-beginning 1))
  15114. (path
  15115. (cond
  15116. ;; No link at point; no inline image.
  15117. ((not link) nil)
  15118. ;; File link without a description. Also handle
  15119. ;; INCLUDE-LINKED here since it should have
  15120. ;; precedence over the next case. I.e., if link
  15121. ;; contains filenames in both the path and the
  15122. ;; description, prioritize the path only when
  15123. ;; INCLUDE-LINKED is non-nil.
  15124. ((or (not (org-element-property :contents-begin link))
  15125. include-linked)
  15126. (and (or (equal "file" linktype)
  15127. (equal "attachment" linktype))
  15128. (org-element-property :path link)))
  15129. ;; Link with a description. Check if description
  15130. ;; is a filename. Even if Org doesn't have syntax
  15131. ;; for those -- clickable image -- constructs, fake
  15132. ;; them, as in `org-export-insert-image-links'.
  15133. ((not inner-start) nil)
  15134. (t
  15135. (org-with-point-at inner-start
  15136. (and (looking-at
  15137. (if (char-equal ?< (char-after inner-start))
  15138. org-link-angle-re
  15139. org-link-plain-re))
  15140. ;; File name must fill the whole
  15141. ;; description.
  15142. (= (org-element-property :contents-end link)
  15143. (match-end 0))
  15144. (match-string 2)))))))
  15145. (when (and path (string-match-p file-extension-re path))
  15146. (let ((file (if (equal "attachment" linktype)
  15147. (progn
  15148. (require 'org-attach)
  15149. (ignore-errors (org-attach-expand path)))
  15150. (expand-file-name path))))
  15151. (when (and file (file-exists-p file))
  15152. (let ((width (org-display-inline-image--width link))
  15153. (old (get-char-property-and-overlay
  15154. (org-element-property :begin link)
  15155. 'org-image-overlay)))
  15156. (if (and (car-safe old) refresh)
  15157. (image-flush (overlay-get (cdr old) 'display))
  15158. (let ((image (org--create-inline-image file width)))
  15159. (when image
  15160. (let ((ov (make-overlay
  15161. (org-element-property :begin link)
  15162. (progn
  15163. (goto-char
  15164. (org-element-property :end link))
  15165. (skip-chars-backward " \t")
  15166. (point)))))
  15167. (overlay-put ov 'display image)
  15168. (overlay-put ov 'face 'default)
  15169. (overlay-put ov 'org-image-overlay t)
  15170. (overlay-put
  15171. ov 'modification-hooks
  15172. (list 'org-display-inline-remove-overlay))
  15173. (when (boundp 'image-map)
  15174. (overlay-put ov 'keymap image-map))
  15175. (push ov org-inline-image-overlays))))))))))))))))
  15176. (defvar visual-fill-column-width) ; Silence compiler warning
  15177. (defun org-display-inline-image--width (link)
  15178. "Determine the display width of the image LINK, in pixels.
  15179. - When `org-image-actual-width' is t, the image's pixel width is used.
  15180. - When `org-image-actual-width' is a number, that value will is used.
  15181. - When `org-image-actual-width' is nil or a list, the first :width attribute
  15182. set (if it exists) is used to set the image width. A width of X% is
  15183. divided by 100.
  15184. If no :width attribute is given and `org-image-actual-width' is a list with
  15185. a number as the car, then that number is used as the default value.
  15186. If the value is a float between 0 and 2, it interpreted as that proportion
  15187. of the text width in the buffer."
  15188. ;; Apply `org-image-actual-width' specifications.
  15189. (cond
  15190. ((eq org-image-actual-width t) nil)
  15191. ((listp org-image-actual-width)
  15192. (let* ((case-fold-search t)
  15193. (par (org-element-lineage link '(paragraph)))
  15194. (attr-re "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)")
  15195. (par-end (org-element-property :post-affiliated par))
  15196. ;; Try to find an attribute providing a :width.
  15197. (attr-width
  15198. (when (and par (org-with-point-at
  15199. (org-element-property :begin par)
  15200. (re-search-forward attr-re par-end t)))
  15201. (match-string 1)))
  15202. (attr-width-val
  15203. (cond
  15204. ((null attr-width) nil)
  15205. ((string-match-p "\\`[0-9.]+%" attr-width)
  15206. (/ (string-to-number attr-width) 100.0))
  15207. (t (string-to-number attr-width))))
  15208. ;; Fallback to `org-image-actual-width' if no explicit width is given.
  15209. (width (or attr-width-val (car org-image-actual-width))))
  15210. (if (and (floatp width) (<= 0.0 width 2.0))
  15211. ;; A float in [0,2] should be interpereted as this portion of
  15212. ;; the text width in the window. This works well with cases like
  15213. ;; #+attr_latex: :width 0.X\{line,page,column,etc.}width,
  15214. ;; as the "0.X" is pulled out as a float. We use 2 as the upper
  15215. ;; bound as cases such as 1.2\linewidth are feasible.
  15216. (round (* width
  15217. (window-pixel-width)
  15218. (/ (or (and (bound-and-true-p visual-fill-column-mode)
  15219. (or visual-fill-column-width auto-fill-function))
  15220. (when auto-fill-function fill-column)
  15221. (window-text-width))
  15222. (float (window-total-width)))))
  15223. width)))
  15224. ((numberp org-image-actual-width)
  15225. org-image-actual-width)
  15226. (t nil)))
  15227. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  15228. "Remove inline-display overlay if a corresponding region is modified."
  15229. (when (and ov after)
  15230. (delete ov org-inline-image-overlays)
  15231. (delete-overlay ov)))
  15232. (defun org-remove-inline-images ()
  15233. "Remove inline display of images."
  15234. (interactive)
  15235. (mapc #'delete-overlay org-inline-image-overlays)
  15236. (setq org-inline-image-overlays nil))
  15237. (defvar org-self-insert-command-undo-counter 0)
  15238. (defvar org-speed-command nil)
  15239. (defun org-self-insert-command (N)
  15240. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  15241. If the cursor is in a table looking at whitespace, the whitespace is
  15242. overwritten, and the table is not marked as requiring realignment."
  15243. (interactive "p")
  15244. (org-check-before-invisible-edit 'insert)
  15245. (cond
  15246. ((and org-use-speed-commands
  15247. (let ((kv (this-command-keys-vector)))
  15248. (setq org-speed-command
  15249. (run-hook-with-args-until-success
  15250. 'org-speed-command-hook
  15251. (make-string 1 (aref kv (1- (length kv))))))))
  15252. (cond
  15253. ((commandp org-speed-command)
  15254. (setq this-command org-speed-command)
  15255. (call-interactively org-speed-command))
  15256. ((functionp org-speed-command)
  15257. (funcall org-speed-command))
  15258. ((and org-speed-command (listp org-speed-command))
  15259. (eval org-speed-command))
  15260. (t (let (org-use-speed-commands)
  15261. (call-interactively 'org-self-insert-command)))))
  15262. ((and
  15263. (= N 1)
  15264. (not (org-region-active-p))
  15265. (org-at-table-p)
  15266. (progn
  15267. ;; Check if we blank the field, and if that triggers align.
  15268. (and (featurep 'org-table)
  15269. org-table-auto-blank-field
  15270. (memq last-command
  15271. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  15272. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  15273. ;; Got extra space, this field does not determine
  15274. ;; column width.
  15275. (let (org-table-may-need-update) (org-table-blank-field))
  15276. ;; No extra space, this field may determine column
  15277. ;; width.
  15278. (org-table-blank-field)))
  15279. t)
  15280. (looking-at "[^|\n]* |"))
  15281. ;; There is room for insertion without re-aligning the table.
  15282. (self-insert-command N)
  15283. (org-table-with-shrunk-field
  15284. (save-excursion
  15285. (skip-chars-forward "^|")
  15286. ;; Do not delete last space, which is
  15287. ;; `org-table-separator-space', but the regular space before
  15288. ;; it.
  15289. (delete-region (- (point) 2) (1- (point))))))
  15290. (t
  15291. (setq org-table-may-need-update t)
  15292. (self-insert-command N)
  15293. (org-fix-tags-on-the-fly)
  15294. (when org-self-insert-cluster-for-undo
  15295. (if (not (eq last-command 'org-self-insert-command))
  15296. (setq org-self-insert-command-undo-counter 1)
  15297. (if (>= org-self-insert-command-undo-counter 20)
  15298. (setq org-self-insert-command-undo-counter 1)
  15299. (and (> org-self-insert-command-undo-counter 0)
  15300. buffer-undo-list (listp buffer-undo-list)
  15301. (not (cadr buffer-undo-list)) ; remove nil entry
  15302. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  15303. (setq org-self-insert-command-undo-counter
  15304. (1+ org-self-insert-command-undo-counter))))))))
  15305. (defun org-check-before-invisible-edit (kind)
  15306. "Check if editing kind KIND would be dangerous with invisible text around.
  15307. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  15308. ;; First, try to get out of here as quickly as possible, to reduce overhead
  15309. (when (and org-catch-invisible-edits
  15310. (or (not (boundp 'visible-mode)) (not visible-mode))
  15311. (or (get-char-property (point) 'invisible)
  15312. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  15313. ;; OK, we need to take a closer look. Do not consider
  15314. ;; invisibility obtained through text properties (e.g., link
  15315. ;; fontification), as it cannot be toggled.
  15316. (let* ((invisible-at-point
  15317. (pcase (get-char-property-and-overlay (point) 'invisible)
  15318. (`(,_ . ,(and (pred overlayp) o)) o)))
  15319. ;; Assume that point cannot land in the middle of an
  15320. ;; overlay, or between two overlays.
  15321. (invisible-before-point
  15322. (and (not invisible-at-point)
  15323. (not (bobp))
  15324. (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  15325. (`(,_ . ,(and (pred overlayp) o)) o))))
  15326. (border-and-ok-direction
  15327. (or
  15328. ;; Check if we are acting predictably before invisible
  15329. ;; text.
  15330. (and invisible-at-point
  15331. (memq kind '(insert delete-backward)))
  15332. ;; Check if we are acting predictably after invisible text
  15333. ;; This works not well, and I have turned it off. It seems
  15334. ;; better to always show and stop after invisible text.
  15335. ;; (and (not invisible-at-point) invisible-before-point
  15336. ;; (memq kind '(insert delete)))
  15337. )))
  15338. (when (or invisible-at-point invisible-before-point)
  15339. (when (eq org-catch-invisible-edits 'error)
  15340. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  15341. (if (and org-custom-properties-overlays
  15342. (y-or-n-p "Display invisible properties in this buffer? "))
  15343. (org-toggle-custom-properties-visibility)
  15344. ;; Make the area visible
  15345. (save-excursion
  15346. (when invisible-before-point
  15347. (goto-char
  15348. (previous-single-char-property-change (point) 'invisible)))
  15349. ;; Remove whatever overlay is currently making yet-to-be
  15350. ;; edited text invisible. Also remove nested invisibility
  15351. ;; related overlays.
  15352. (delete-overlay (or invisible-at-point invisible-before-point))
  15353. (let ((origin (if invisible-at-point (point) (1- (point)))))
  15354. (while (pcase (get-char-property-and-overlay origin 'invisible)
  15355. (`(,_ . ,(and (pred overlayp) o))
  15356. (delete-overlay o)
  15357. t)))))
  15358. (cond
  15359. ((eq org-catch-invisible-edits 'show)
  15360. ;; That's it, we do the edit after showing
  15361. (message
  15362. "Unfolding invisible region around point before editing")
  15363. (sit-for 1))
  15364. ((and (eq org-catch-invisible-edits 'smart)
  15365. border-and-ok-direction)
  15366. (message "Unfolding invisible region around point before editing"))
  15367. (t
  15368. ;; Don't do the edit, make the user repeat it in full visibility
  15369. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  15370. (defun org-fix-tags-on-the-fly ()
  15371. "Align tags in headline at point.
  15372. Unlike `org-align-tags', this function does nothing if point is
  15373. either not currently on a tagged headline or on a tag."
  15374. (when (and (org-match-line org-tag-line-re)
  15375. (< (point) (match-beginning 1)))
  15376. (org-align-tags)))
  15377. (defun org-delete-backward-char (N)
  15378. "Like `delete-backward-char', insert whitespace at field end in tables.
  15379. When deleting backwards, in tables this function will insert whitespace in
  15380. front of the next \"|\" separator, to keep the table aligned. The table will
  15381. still be marked for re-alignment if the field did fill the entire column,
  15382. because, in this case the deletion might narrow the column."
  15383. (interactive "p")
  15384. (save-match-data
  15385. (org-check-before-invisible-edit 'delete-backward)
  15386. (if (and (= N 1)
  15387. (not overwrite-mode)
  15388. (not (org-region-active-p))
  15389. (not (eq (char-before) ?|))
  15390. (save-excursion (skip-chars-backward " \t") (not (bolp)))
  15391. (looking-at-p ".*?|")
  15392. (org-at-table-p))
  15393. (progn (forward-char -1) (org-delete-char 1))
  15394. (backward-delete-char N)
  15395. (org-fix-tags-on-the-fly))))
  15396. (defun org-delete-char (N)
  15397. "Like `delete-char', but insert whitespace at field end in tables.
  15398. When deleting characters, in tables this function will insert whitespace in
  15399. front of the next \"|\" separator, to keep the table aligned. The table will
  15400. still be marked for re-alignment if the field did fill the entire column,
  15401. because, in this case the deletion might narrow the column."
  15402. (interactive "p")
  15403. (save-match-data
  15404. (org-check-before-invisible-edit 'delete)
  15405. (cond
  15406. ((or (/= N 1)
  15407. (eq (char-after) ?|)
  15408. (save-excursion (skip-chars-backward " \t") (bolp))
  15409. (not (org-at-table-p)))
  15410. (delete-char N)
  15411. (org-fix-tags-on-the-fly))
  15412. ((looking-at ".\\(.*?\\)|")
  15413. (let* ((update? org-table-may-need-update)
  15414. (noalign (looking-at-p ".*? |")))
  15415. (delete-char 1)
  15416. (org-table-with-shrunk-field
  15417. (save-excursion
  15418. ;; Last space is `org-table-separator-space', so insert
  15419. ;; a regular one before it instead.
  15420. (goto-char (- (match-end 0) 2))
  15421. (insert " ")))
  15422. ;; If there were two spaces at the end, this field does not
  15423. ;; determine the width of the column.
  15424. (when noalign (setq org-table-may-need-update update?))))
  15425. (t
  15426. (delete-char N)))))
  15427. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  15428. (put 'org-self-insert-command 'delete-selection
  15429. (lambda ()
  15430. (not (run-hook-with-args-until-success
  15431. 'self-insert-uses-region-functions))))
  15432. (put 'orgtbl-self-insert-command 'delete-selection
  15433. (lambda ()
  15434. (not (run-hook-with-args-until-success
  15435. 'self-insert-uses-region-functions))))
  15436. (put 'org-delete-char 'delete-selection 'supersede)
  15437. (put 'org-delete-backward-char 'delete-selection 'supersede)
  15438. (put 'org-yank 'delete-selection 'yank)
  15439. (put 'org-return 'delete-selection t)
  15440. ;; Make `flyspell-mode' delay after some commands
  15441. (put 'org-self-insert-command 'flyspell-delayed t)
  15442. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  15443. (put 'org-delete-char 'flyspell-delayed t)
  15444. (put 'org-delete-backward-char 'flyspell-delayed t)
  15445. ;; Make pabbrev-mode expand after Org mode commands
  15446. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  15447. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  15448. (defun org-transpose-words ()
  15449. "Transpose words for Org.
  15450. This uses the `org-mode-transpose-word-syntax-table' syntax
  15451. table, which interprets characters in `org-emphasis-alist' as
  15452. word constituents."
  15453. (interactive)
  15454. (with-syntax-table org-mode-transpose-word-syntax-table
  15455. (call-interactively 'transpose-words)))
  15456. (defvar org-ctrl-c-ctrl-c-hook nil
  15457. "Hook for functions attaching themselves to `C-c C-c'.
  15458. This can be used to add additional functionality to the `C-c C-c'
  15459. key which executes context-dependent commands. This hook is run
  15460. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  15461. run after the last test.
  15462. Each function will be called with no arguments. The function
  15463. must check if the context is appropriate for it to act. If yes,
  15464. it should do its thing and then return a non-nil value. If the
  15465. context is wrong, just do nothing and return nil.")
  15466. (defvar org-ctrl-c-ctrl-c-final-hook nil
  15467. "Hook for functions attaching themselves to `C-c C-c'.
  15468. This can be used to add additional functionality to the `C-c C-c'
  15469. key which executes context-dependent commands. This hook is run
  15470. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  15471. before the first test.
  15472. Each function will be called with no arguments. The function
  15473. must check if the context is appropriate for it to act. If yes,
  15474. it should do its thing and then return a non-nil value. If the
  15475. context is wrong, just do nothing and return nil.")
  15476. (defvar org-tab-first-hook nil
  15477. "Hook for functions to attach themselves to TAB.
  15478. See `org-ctrl-c-ctrl-c-hook' for more information.
  15479. This hook runs as the first action when TAB is pressed, even before
  15480. `org-cycle' messes around with the `outline-regexp' to cater for
  15481. inline tasks and plain list item folding.
  15482. If any function in this hook returns t, any other actions that
  15483. would have been caused by TAB (such as table field motion or visibility
  15484. cycling) will not occur.")
  15485. (defvar org-tab-after-check-for-table-hook nil
  15486. "Hook for functions to attach themselves to TAB.
  15487. See `org-ctrl-c-ctrl-c-hook' for more information.
  15488. This hook runs after it has been established that the cursor is not in a
  15489. table, but before checking if the cursor is in a headline or if global cycling
  15490. should be done.
  15491. If any function in this hook returns t, not other actions like visibility
  15492. cycling will be done.")
  15493. (defvar org-tab-after-check-for-cycling-hook nil
  15494. "Hook for functions to attach themselves to TAB.
  15495. See `org-ctrl-c-ctrl-c-hook' for more information.
  15496. This hook runs after it has been established that not table field motion and
  15497. not visibility should be done because of current context. This is probably
  15498. the place where a package like yasnippets can hook in.")
  15499. (defvar org-tab-before-tab-emulation-hook nil
  15500. "Hook for functions to attach themselves to TAB.
  15501. See `org-ctrl-c-ctrl-c-hook' for more information.
  15502. This hook runs after every other options for TAB have been exhausted, but
  15503. before indentation and \t insertion takes place.")
  15504. (defvar org-metaleft-hook nil
  15505. "Hook for functions attaching themselves to `M-left'.
  15506. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15507. (defvar org-metaright-hook nil
  15508. "Hook for functions attaching themselves to `M-right'.
  15509. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15510. (defvar org-metaup-hook nil
  15511. "Hook for functions attaching themselves to `M-up'.
  15512. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15513. (defvar org-metadown-hook nil
  15514. "Hook for functions attaching themselves to `M-down'.
  15515. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15516. (defvar org-shiftmetaleft-hook nil
  15517. "Hook for functions attaching themselves to `M-S-left'.
  15518. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15519. (defvar org-shiftmetaright-hook nil
  15520. "Hook for functions attaching themselves to `M-S-right'.
  15521. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15522. (defvar org-shiftmetaup-hook nil
  15523. "Hook for functions attaching themselves to `M-S-up'.
  15524. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15525. (defvar org-shiftmetadown-hook nil
  15526. "Hook for functions attaching themselves to `M-S-down'.
  15527. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15528. (defvar org-metareturn-hook nil
  15529. "Hook for functions attaching themselves to `M-RET'.
  15530. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15531. (defvar org-shiftup-hook nil
  15532. "Hook for functions attaching themselves to `S-up'.
  15533. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15534. (defvar org-shiftup-final-hook nil
  15535. "Hook for functions attaching themselves to `S-up'.
  15536. This one runs after all other options except shift-select have been excluded.
  15537. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15538. (defvar org-shiftdown-hook nil
  15539. "Hook for functions attaching themselves to `S-down'.
  15540. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15541. (defvar org-shiftdown-final-hook nil
  15542. "Hook for functions attaching themselves to `S-down'.
  15543. This one runs after all other options except shift-select have been excluded.
  15544. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15545. (defvar org-shiftleft-hook nil
  15546. "Hook for functions attaching themselves to `S-left'.
  15547. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15548. (defvar org-shiftleft-final-hook nil
  15549. "Hook for functions attaching themselves to `S-left'.
  15550. This one runs after all other options except shift-select have been excluded.
  15551. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15552. (defvar org-shiftright-hook nil
  15553. "Hook for functions attaching themselves to `S-right'.
  15554. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15555. (defvar org-shiftright-final-hook nil
  15556. "Hook for functions attaching themselves to `S-right'.
  15557. This one runs after all other options except shift-select have been excluded.
  15558. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15559. (defun org-modifier-cursor-error ()
  15560. "Throw an error, a modified cursor command was applied in wrong context."
  15561. (user-error "This command is active in special context like tables, headlines or items"))
  15562. (defun org-shiftselect-error ()
  15563. "Throw an error because Shift-Cursor command was applied in wrong context."
  15564. (if (and (boundp 'shift-select-mode) shift-select-mode)
  15565. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  15566. (user-error "This command works only in special context like headlines or timestamps")))
  15567. (defun org-call-for-shift-select (cmd)
  15568. (let ((this-command-keys-shift-translated t))
  15569. (call-interactively cmd)))
  15570. (defun org-shifttab (&optional arg)
  15571. "Global visibility cycling or move to previous table field.
  15572. Call `org-table-previous-field' within a table.
  15573. When ARG is nil, cycle globally through visibility states.
  15574. When ARG is a numeric prefix, show contents of this level."
  15575. (interactive "P")
  15576. (cond
  15577. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  15578. ((integerp arg)
  15579. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  15580. (message "Content view to level: %d" arg)
  15581. (org-content (prefix-numeric-value arg2))
  15582. (org-cycle-show-empty-lines t)
  15583. (setq org-cycle-global-status 'overview)
  15584. (run-hook-with-args 'org-cycle-hook 'overview)))
  15585. (t (call-interactively 'org-global-cycle))))
  15586. (defun org-shiftmetaleft ()
  15587. "Promote subtree or delete table column.
  15588. Calls `org-promote-subtree', `org-outdent-item-tree', or
  15589. `org-table-delete-column', depending on context. See the
  15590. individual commands for more information."
  15591. (interactive)
  15592. (cond
  15593. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  15594. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  15595. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  15596. ((if (not (org-region-active-p)) (org-at-item-p)
  15597. (save-excursion (goto-char (region-beginning))
  15598. (org-at-item-p)))
  15599. (call-interactively 'org-outdent-item-tree))
  15600. (t (org-modifier-cursor-error))))
  15601. (defun org-shiftmetaright ()
  15602. "Demote subtree or insert table column.
  15603. Calls `org-demote-subtree', `org-indent-item-tree', or
  15604. `org-table-insert-column', depending on context. See the
  15605. individual commands for more information."
  15606. (interactive)
  15607. (cond
  15608. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  15609. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  15610. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  15611. ((if (not (org-region-active-p)) (org-at-item-p)
  15612. (save-excursion (goto-char (region-beginning))
  15613. (org-at-item-p)))
  15614. (call-interactively 'org-indent-item-tree))
  15615. (t (org-modifier-cursor-error))))
  15616. (defun org-shiftmetaup (&optional _arg)
  15617. "Drag the line at point up.
  15618. In a table, kill the current row.
  15619. On a clock timestamp, update the value of the timestamp like `S-<up>'
  15620. but also adjust the previous clocked item in the clock history.
  15621. Everywhere else, drag the line at point up."
  15622. (interactive "P")
  15623. (cond
  15624. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  15625. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  15626. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15627. (call-interactively 'org-timestamp-up)))
  15628. (t (call-interactively 'org-drag-line-backward))))
  15629. (defun org-shiftmetadown (&optional _arg)
  15630. "Drag the line at point down.
  15631. In a table, insert an empty row at the current line.
  15632. On a clock timestamp, update the value of the timestamp like `S-<down>'
  15633. but also adjust the previous clocked item in the clock history.
  15634. Everywhere else, drag the line at point down."
  15635. (interactive "P")
  15636. (cond
  15637. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  15638. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  15639. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15640. (call-interactively 'org-timestamp-down)))
  15641. (t (call-interactively 'org-drag-line-forward))))
  15642. (defsubst org-hidden-tree-error ()
  15643. (user-error
  15644. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  15645. (defun org-metaleft (&optional _arg)
  15646. "Promote heading, list item at point or move table column left.
  15647. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  15648. depending on context. With no specific context, calls the Emacs
  15649. default `backward-word'. See the individual commands for more
  15650. information.
  15651. This function runs the hook `org-metaleft-hook' as a first step,
  15652. and returns at first non-nil value."
  15653. (interactive "P")
  15654. (cond
  15655. ((run-hook-with-args-until-success 'org-metaleft-hook))
  15656. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  15657. ((org-with-limited-levels
  15658. (or (org-at-heading-p)
  15659. (and (org-region-active-p)
  15660. (save-excursion
  15661. (goto-char (region-beginning))
  15662. (org-at-heading-p)))))
  15663. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15664. (call-interactively 'org-do-promote))
  15665. ;; At an inline task.
  15666. ((org-at-heading-p)
  15667. (call-interactively 'org-inlinetask-promote))
  15668. ((or (org-at-item-p)
  15669. (and (org-region-active-p)
  15670. (save-excursion
  15671. (goto-char (region-beginning))
  15672. (org-at-item-p))))
  15673. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15674. (call-interactively 'org-outdent-item))
  15675. (t (call-interactively 'backward-word))))
  15676. (defun org-metaright (&optional _arg)
  15677. "Demote heading, list item at point or move table column right.
  15678. In front of a drawer or a block keyword, indent it correctly.
  15679. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  15680. `org-indent-drawer' or `org-indent-block' depending on context.
  15681. With no specific context, calls the Emacs default `forward-word'.
  15682. See the individual commands for more information.
  15683. This function runs the hook `org-metaright-hook' as a first step,
  15684. and returns at first non-nil value."
  15685. (interactive "P")
  15686. (cond
  15687. ((run-hook-with-args-until-success 'org-metaright-hook))
  15688. ((org-at-table-p) (call-interactively 'org-table-move-column))
  15689. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  15690. ((org-at-block-p) (call-interactively 'org-indent-block))
  15691. ((org-with-limited-levels
  15692. (or (org-at-heading-p)
  15693. (and (org-region-active-p)
  15694. (save-excursion
  15695. (goto-char (region-beginning))
  15696. (org-at-heading-p)))))
  15697. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15698. (call-interactively 'org-do-demote))
  15699. ;; At an inline task.
  15700. ((org-at-heading-p)
  15701. (call-interactively 'org-inlinetask-demote))
  15702. ((or (org-at-item-p)
  15703. (and (org-region-active-p)
  15704. (save-excursion
  15705. (goto-char (region-beginning))
  15706. (org-at-item-p))))
  15707. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15708. (call-interactively 'org-indent-item))
  15709. (t (call-interactively 'forward-word))))
  15710. (defun org-check-for-hidden (what)
  15711. "Check if there are hidden headlines/items in the current visual line.
  15712. WHAT can be either `headlines' or `items'. If the current line is
  15713. an outline or item heading and it has a folded subtree below it,
  15714. this function returns t, nil otherwise."
  15715. (let ((re (cond
  15716. ((eq what 'headlines) org-outline-regexp-bol)
  15717. ((eq what 'items) (org-item-beginning-re))
  15718. (t (error "This should not happen"))))
  15719. beg end)
  15720. (save-excursion
  15721. (catch 'exit
  15722. (unless (org-region-active-p)
  15723. (setq beg (line-beginning-position))
  15724. (beginning-of-line 2)
  15725. (while (and (not (eobp)) ;; this is like `next-line'
  15726. (get-char-property (1- (point)) 'invisible))
  15727. (beginning-of-line 2))
  15728. (setq end (point))
  15729. (goto-char beg)
  15730. (goto-char (line-end-position))
  15731. (setq end (max end (point)))
  15732. (while (re-search-forward re end t)
  15733. (when (get-char-property (match-beginning 0) 'invisible)
  15734. (throw 'exit t))))
  15735. nil))))
  15736. (defun org-metaup (&optional _arg)
  15737. "Move subtree up or move table row up.
  15738. Calls `org-move-subtree-up' or `org-table-move-row' or
  15739. `org-move-item-up', depending on context. See the individual commands
  15740. for more information."
  15741. (interactive "P")
  15742. (cond
  15743. ((run-hook-with-args-until-success 'org-metaup-hook))
  15744. ((org-region-active-p)
  15745. (let* ((a (save-excursion
  15746. (goto-char (min (region-beginning) (region-end)))
  15747. (line-beginning-position)))
  15748. (b (save-excursion
  15749. (goto-char (max (region-beginning) (region-end)))
  15750. (if (bolp) (1- (point)) (line-end-position))))
  15751. (c (save-excursion
  15752. (goto-char a)
  15753. (move-beginning-of-line 0)
  15754. (point)))
  15755. (d (save-excursion
  15756. (goto-char a)
  15757. (move-end-of-line 0)
  15758. (point))))
  15759. (transpose-regions a b c d)
  15760. (goto-char c)))
  15761. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  15762. ((and (featurep 'org-inlinetask)
  15763. (org-inlinetask-in-task-p))
  15764. (org-drag-element-backward))
  15765. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  15766. ((org-at-item-p) (call-interactively 'org-move-item-up))
  15767. (t (org-drag-element-backward))))
  15768. (defun org-metadown (&optional _arg)
  15769. "Move subtree down or move table row down.
  15770. Calls `org-move-subtree-down' or `org-table-move-row' or
  15771. `org-move-item-down', depending on context. See the individual
  15772. commands for more information."
  15773. (interactive "P")
  15774. (cond
  15775. ((run-hook-with-args-until-success 'org-metadown-hook))
  15776. ((org-region-active-p)
  15777. (let* ((a (save-excursion
  15778. (goto-char (min (region-beginning) (region-end)))
  15779. (line-beginning-position)))
  15780. (b (save-excursion
  15781. (goto-char (max (region-beginning) (region-end)))
  15782. (if (bolp) (1- (point)) (line-end-position))))
  15783. (c (save-excursion
  15784. (goto-char b)
  15785. (move-beginning-of-line (if (bolp) 1 2))
  15786. (point)))
  15787. (d (save-excursion
  15788. (goto-char b)
  15789. (move-end-of-line (if (bolp) 1 2))
  15790. (point))))
  15791. (transpose-regions a b c d)
  15792. (goto-char d)))
  15793. ((org-at-table-p) (call-interactively 'org-table-move-row))
  15794. ((and (featurep 'org-inlinetask)
  15795. (org-inlinetask-in-task-p))
  15796. (org-drag-element-forward))
  15797. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  15798. ((org-at-item-p) (call-interactively 'org-move-item-down))
  15799. (t (org-drag-element-forward))))
  15800. (defun org-shiftup (&optional arg)
  15801. "Act on current element according to context.
  15802. Call `org-timestamp-up' or `org-priority-up', or
  15803. `org-previous-item', or `org-table-move-cell-up'. See the
  15804. individual commands for more information."
  15805. (interactive "P")
  15806. (cond
  15807. ((run-hook-with-args-until-success 'org-shiftup-hook))
  15808. ((and org-support-shift-select (org-region-active-p))
  15809. (org-call-for-shift-select 'previous-line))
  15810. ((org-at-timestamp-p 'lax)
  15811. (call-interactively (if org-edit-timestamp-down-means-later
  15812. 'org-timestamp-down 'org-timestamp-up)))
  15813. ((and (not (eq org-support-shift-select 'always))
  15814. org-priority-enable-commands
  15815. (org-at-heading-p))
  15816. (call-interactively 'org-priority-up))
  15817. ((and (not org-support-shift-select) (org-at-item-p))
  15818. (call-interactively 'org-previous-item))
  15819. ((org-clocktable-try-shift 'up arg))
  15820. ((and (not (eq org-support-shift-select 'always))
  15821. (org-at-table-p))
  15822. (org-table-move-cell-up))
  15823. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  15824. (org-support-shift-select
  15825. (org-call-for-shift-select 'previous-line))
  15826. (t (org-shiftselect-error))))
  15827. (defun org-shiftdown (&optional arg)
  15828. "Act on current element according to context.
  15829. Call `org-timestamp-down' or `org-priority-down', or
  15830. `org-next-item', or `org-table-move-cell-down'. See the
  15831. individual commands for more information."
  15832. (interactive "P")
  15833. (cond
  15834. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  15835. ((and org-support-shift-select (org-region-active-p))
  15836. (org-call-for-shift-select 'next-line))
  15837. ((org-at-timestamp-p 'lax)
  15838. (call-interactively (if org-edit-timestamp-down-means-later
  15839. 'org-timestamp-up 'org-timestamp-down)))
  15840. ((and (not (eq org-support-shift-select 'always))
  15841. org-priority-enable-commands
  15842. (org-at-heading-p))
  15843. (call-interactively 'org-priority-down))
  15844. ((and (not org-support-shift-select) (org-at-item-p))
  15845. (call-interactively 'org-next-item))
  15846. ((org-clocktable-try-shift 'down arg))
  15847. ((and (not (eq org-support-shift-select 'always))
  15848. (org-at-table-p))
  15849. (org-table-move-cell-down))
  15850. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  15851. (org-support-shift-select
  15852. (org-call-for-shift-select 'next-line))
  15853. (t (org-shiftselect-error))))
  15854. (defun org-shiftright (&optional arg)
  15855. "Act on the current element according to context.
  15856. This does one of the following:
  15857. - switch a timestamp at point one day into the future
  15858. - on a headline, switch to the next TODO keyword
  15859. - on an item, switch entire list to the next bullet type
  15860. - on a property line, switch to the next allowed value
  15861. - on a clocktable definition line, move time block into the future
  15862. - in a table, move a single cell right"
  15863. (interactive "P")
  15864. (cond
  15865. ((run-hook-with-args-until-success 'org-shiftright-hook))
  15866. ((and org-support-shift-select (org-region-active-p))
  15867. (org-call-for-shift-select 'forward-char))
  15868. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  15869. ((and (not (eq org-support-shift-select 'always))
  15870. (org-at-heading-p))
  15871. (let ((org-inhibit-logging
  15872. (not org-treat-S-cursor-todo-selection-as-state-change))
  15873. (org-inhibit-blocking
  15874. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15875. (org-call-with-arg 'org-todo 'right)))
  15876. ((or (and org-support-shift-select
  15877. (not (eq org-support-shift-select 'always))
  15878. (org-at-item-bullet-p))
  15879. (and (not org-support-shift-select) (org-at-item-p)))
  15880. (org-call-with-arg 'org-cycle-list-bullet nil))
  15881. ((and (not (eq org-support-shift-select 'always))
  15882. (org-at-property-p))
  15883. (call-interactively 'org-property-next-allowed-value))
  15884. ((org-clocktable-try-shift 'right arg))
  15885. ((and (not (eq org-support-shift-select 'always))
  15886. (org-at-table-p))
  15887. (org-table-move-cell-right))
  15888. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  15889. (org-support-shift-select
  15890. (org-call-for-shift-select 'forward-char))
  15891. (t (org-shiftselect-error))))
  15892. (defun org-shiftleft (&optional arg)
  15893. "Act on current element according to context.
  15894. This does one of the following:
  15895. - switch a timestamp at point one day into the past
  15896. - on a headline, switch to the previous TODO keyword.
  15897. - on an item, switch entire list to the previous bullet type
  15898. - on a property line, switch to the previous allowed value
  15899. - on a clocktable definition line, move time block into the past
  15900. - in a table, move a single cell left"
  15901. (interactive "P")
  15902. (cond
  15903. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  15904. ((and org-support-shift-select (org-region-active-p))
  15905. (org-call-for-shift-select 'backward-char))
  15906. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  15907. ((and (not (eq org-support-shift-select 'always))
  15908. (org-at-heading-p))
  15909. (let ((org-inhibit-logging
  15910. (not org-treat-S-cursor-todo-selection-as-state-change))
  15911. (org-inhibit-blocking
  15912. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15913. (org-call-with-arg 'org-todo 'left)))
  15914. ((or (and org-support-shift-select
  15915. (not (eq org-support-shift-select 'always))
  15916. (org-at-item-bullet-p))
  15917. (and (not org-support-shift-select) (org-at-item-p)))
  15918. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  15919. ((and (not (eq org-support-shift-select 'always))
  15920. (org-at-property-p))
  15921. (call-interactively 'org-property-previous-allowed-value))
  15922. ((org-clocktable-try-shift 'left arg))
  15923. ((and (not (eq org-support-shift-select 'always))
  15924. (org-at-table-p))
  15925. (org-table-move-cell-left))
  15926. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  15927. (org-support-shift-select
  15928. (org-call-for-shift-select 'backward-char))
  15929. (t (org-shiftselect-error))))
  15930. (defun org-shiftcontrolright ()
  15931. "Switch to next TODO set."
  15932. (interactive)
  15933. (cond
  15934. ((and org-support-shift-select (org-region-active-p))
  15935. (org-call-for-shift-select 'forward-word))
  15936. ((and (not (eq org-support-shift-select 'always))
  15937. (org-at-heading-p))
  15938. (org-call-with-arg 'org-todo 'nextset))
  15939. (org-support-shift-select
  15940. (org-call-for-shift-select 'forward-word))
  15941. (t (org-shiftselect-error))))
  15942. (defun org-shiftcontrolleft ()
  15943. "Switch to previous TODO set."
  15944. (interactive)
  15945. (cond
  15946. ((and org-support-shift-select (org-region-active-p))
  15947. (org-call-for-shift-select 'backward-word))
  15948. ((and (not (eq org-support-shift-select 'always))
  15949. (org-at-heading-p))
  15950. (org-call-with-arg 'org-todo 'previousset))
  15951. (org-support-shift-select
  15952. (org-call-for-shift-select 'backward-word))
  15953. (t (org-shiftselect-error))))
  15954. (defun org-shiftcontrolup (&optional n)
  15955. "Change timestamps synchronously up in CLOCK log lines.
  15956. Optional argument N tells to change by that many units."
  15957. (interactive "P")
  15958. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  15959. (let (org-support-shift-select)
  15960. (org-clock-timestamps-up n))
  15961. (user-error "Not at a clock log")))
  15962. (defun org-shiftcontroldown (&optional n)
  15963. "Change timestamps synchronously down in CLOCK log lines.
  15964. Optional argument N tells to change by that many units."
  15965. (interactive "P")
  15966. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  15967. (let (org-support-shift-select)
  15968. (org-clock-timestamps-down n))
  15969. (user-error "Not at a clock log")))
  15970. (defun org-increase-number-at-point (&optional inc)
  15971. "Increment the number at point.
  15972. With an optional prefix numeric argument INC, increment using
  15973. this numeric value."
  15974. (interactive "p")
  15975. (if (not (number-at-point))
  15976. (user-error "Not on a number")
  15977. (unless inc (setq inc 1))
  15978. (let ((pos (point))
  15979. (beg (skip-chars-backward "-+^/*0-9eE."))
  15980. (end (skip-chars-forward "-+^/*0-9eE.")) nap)
  15981. (setq nap (buffer-substring-no-properties
  15982. (+ pos beg) (+ pos beg end)))
  15983. (delete-region (+ pos beg) (+ pos beg end))
  15984. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  15985. (when (org-at-table-p)
  15986. (org-table-align)
  15987. (org-table-end-of-field 1))))
  15988. (defun org-decrease-number-at-point (&optional inc)
  15989. "Decrement the number at point.
  15990. With an optional prefix numeric argument INC, decrement using
  15991. this numeric value."
  15992. (interactive "p")
  15993. (org-increase-number-at-point (- (or inc 1))))
  15994. (defun org-ctrl-c-ret ()
  15995. "Call `org-table-hline-and-move' or `org-insert-heading'."
  15996. (interactive)
  15997. (cond
  15998. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  15999. (t (call-interactively 'org-insert-heading))))
  16000. (defun org-copy-visible (beg end)
  16001. "Copy the visible parts of the region."
  16002. (interactive "r")
  16003. (let ((result ""))
  16004. (while (/= beg end)
  16005. (if (invisible-p beg)
  16006. (setq beg (next-single-char-property-change beg 'invisible nil end))
  16007. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  16008. (setq result (concat result (buffer-substring beg next)))
  16009. (setq beg next))))
  16010. (setq deactivate-mark t)
  16011. (kill-new result)
  16012. (message "Visible strings have been copied to the kill ring.")))
  16013. (defun org-copy-special ()
  16014. "Copy region in table or copy current subtree.
  16015. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  16016. context. See the individual commands for more information."
  16017. (interactive)
  16018. (call-interactively
  16019. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  16020. (defun org-cut-special ()
  16021. "Cut region in table or cut current subtree.
  16022. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  16023. context. See the individual commands for more information."
  16024. (interactive)
  16025. (call-interactively
  16026. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  16027. (defun org-paste-special (arg)
  16028. "Paste rectangular region into table, or past subtree relative to level.
  16029. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  16030. See the individual commands for more information."
  16031. (interactive "P")
  16032. (if (org-at-table-p)
  16033. (org-table-paste-rectangle)
  16034. (org-paste-subtree arg)))
  16035. (defun org-edit-special (&optional arg)
  16036. "Call a special editor for the element at point.
  16037. When at a table, call the formula editor with `org-table-edit-formulas'.
  16038. When in a source code block, call `org-edit-src-code'.
  16039. When in a fixed-width region, call `org-edit-fixed-width-region'.
  16040. When in an export block, call `org-edit-export-block'.
  16041. When in a LaTeX environment, call `org-edit-latex-environment'.
  16042. When at an INCLUDE, SETUPFILE or BIBLIOGRAPHY keyword, visit the included file.
  16043. When at a footnote reference, call `org-edit-footnote-reference'.
  16044. When at a planning line call, `org-deadline' and/or `org-schedule'.
  16045. When at an active timestamp, call `org-time-stamp'.
  16046. When at an inactive timestamp, call `org-time-stamp-inactive'.
  16047. On a link, call `ffap' to visit the link at point.
  16048. Otherwise, return a user error."
  16049. (interactive "P")
  16050. (let ((element (org-element-at-point)))
  16051. (barf-if-buffer-read-only)
  16052. (pcase (org-element-type element)
  16053. (`src-block
  16054. (if (not arg) (org-edit-src-code)
  16055. (let* ((info (org-babel-get-src-block-info))
  16056. (lang (nth 0 info))
  16057. (params (nth 2 info))
  16058. (session (cdr (assq :session params))))
  16059. (if (not session) (org-edit-src-code)
  16060. ;; At a source block with a session and function called
  16061. ;; with an ARG: switch to the buffer related to the
  16062. ;; inferior process.
  16063. (switch-to-buffer
  16064. (funcall (intern (concat "org-babel-prep-session:" lang))
  16065. session params))))))
  16066. (`keyword
  16067. (unless (member (org-element-property :key element)
  16068. '("BIBLIOGRAPHY" "INCLUDE" "SETUPFILE"))
  16069. (user-error "No special environment to edit here"))
  16070. (let ((value (org-element-property :value element)))
  16071. (unless (org-string-nw-p value) (user-error "No file to edit"))
  16072. (let ((file (and (string-match "\\`\"\\(.*?\\)\"\\|\\S-+" value)
  16073. (or (match-string 1 value)
  16074. (match-string 0 value)))))
  16075. (when (org-url-p file)
  16076. (user-error "Files located with a URL cannot be edited"))
  16077. (org-link-open-from-string
  16078. (format "[[%s]]" (expand-file-name file))))))
  16079. (`table
  16080. (if (eq (org-element-property :type element) 'table.el)
  16081. (org-edit-table.el)
  16082. (call-interactively 'org-table-edit-formulas)))
  16083. ;; Only Org tables contain `table-row' type elements.
  16084. (`table-row (call-interactively 'org-table-edit-formulas))
  16085. (`example-block (org-edit-src-code))
  16086. (`export-block (org-edit-export-block))
  16087. (`fixed-width (org-edit-fixed-width-region))
  16088. (`latex-environment (org-edit-latex-environment))
  16089. (`planning
  16090. (let ((proplist (cadr element)))
  16091. (mapc #'call-interactively
  16092. (remq nil
  16093. (list
  16094. (when (plist-get proplist :deadline) #'org-deadline)
  16095. (when (plist-get proplist :scheduled) #'org-schedule))))))
  16096. (_
  16097. ;; No notable element at point. Though, we may be at a link or
  16098. ;; a footnote reference, which are objects. Thus, scan deeper.
  16099. (let ((context (org-element-context element)))
  16100. (pcase (org-element-type context)
  16101. (`footnote-reference (org-edit-footnote-reference))
  16102. (`inline-src-block (org-edit-inline-src-code))
  16103. (`latex-fragment (org-edit-latex-fragment))
  16104. (`timestamp (if (eq 'inactive (org-element-property :type context))
  16105. (call-interactively #'org-time-stamp-inactive)
  16106. (call-interactively #'org-time-stamp)))
  16107. (`link (call-interactively #'ffap))
  16108. (_ (user-error "No special environment to edit here"))))))))
  16109. (defun org-ctrl-c-ctrl-c (&optional arg)
  16110. "Set tags in headline, or update according to changed information at point.
  16111. This command does many different things, depending on context:
  16112. - If column view is active, in agenda or org buffers, quit it.
  16113. - If there are highlights, remove them.
  16114. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  16115. this is what we do.
  16116. - If the cursor is on a statistics cookie, update it.
  16117. - If the cursor is in a headline, in an agenda or an org buffer,
  16118. prompt for tags and insert them into the current line, aligned
  16119. to `org-tags-column'. When called with prefix arg, realign all
  16120. tags in the current buffer.
  16121. - If the cursor is in one of the special #+KEYWORD lines, this
  16122. triggers scanning the buffer for these lines and updating the
  16123. information.
  16124. - If the cursor is inside a table, realign the table. This command
  16125. works even if the automatic table editor has been turned off.
  16126. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  16127. the entire table.
  16128. - If the cursor is at a footnote reference or definition, jump to
  16129. the corresponding definition or references, respectively.
  16130. - If the cursor is a the beginning of a dynamic block, update it.
  16131. - If the current buffer is a capture buffer, close note and file it.
  16132. - If the cursor is on a <<<target>>>, update radio targets and
  16133. corresponding links in this buffer.
  16134. - If the cursor is on a numbered item in a plain list, renumber the
  16135. ordered list.
  16136. - If the cursor is on a checkbox, toggle it.
  16137. - If the cursor is on a code block, evaluate it. The variable
  16138. `org-confirm-babel-evaluate' can be used to control prompting
  16139. before code block evaluation, by default every code block
  16140. evaluation requires confirmation. Code block evaluation can be
  16141. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  16142. (interactive "P")
  16143. (cond
  16144. ((bound-and-true-p org-columns-overlays) (org-columns-quit))
  16145. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  16146. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  16147. (org-remove-occur-highlights)
  16148. (message "Temporary highlights/overlays removed from current buffer"))
  16149. ((and (local-variable-p 'org-finish-function)
  16150. (fboundp org-finish-function))
  16151. (funcall org-finish-function))
  16152. ((org-babel-hash-at-point))
  16153. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  16154. (t
  16155. (let* ((context
  16156. (org-element-lineage
  16157. (org-element-context)
  16158. ;; Limit to supported contexts.
  16159. '(babel-call clock dynamic-block footnote-definition
  16160. footnote-reference inline-babel-call inline-src-block
  16161. inlinetask item keyword node-property paragraph
  16162. plain-list planning property-drawer radio-target
  16163. src-block statistics-cookie table table-cell table-row
  16164. timestamp)
  16165. t))
  16166. (radio-list-p (org-at-radio-list-p))
  16167. (type (org-element-type context)))
  16168. ;; For convenience: at the first line of a paragraph on the same
  16169. ;; line as an item, apply function on that item instead.
  16170. (when (eq type 'paragraph)
  16171. (let ((parent (org-element-property :parent context)))
  16172. (when (and (eq (org-element-type parent) 'item)
  16173. (= (line-beginning-position)
  16174. (org-element-property :begin parent)))
  16175. (setq context parent)
  16176. (setq type 'item))))
  16177. ;; Act according to type of element or object at point.
  16178. ;;
  16179. ;; Do nothing on a blank line, except if it is contained in
  16180. ;; a source block. Hence, we first check if point is in such
  16181. ;; a block and then if it is at a blank line.
  16182. (pcase type
  16183. ((or `inline-src-block `src-block)
  16184. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  16185. (org-babel-eval-wipe-error-buffer)
  16186. (org-babel-execute-src-block
  16187. current-prefix-arg (org-babel-get-src-block-info nil context))))
  16188. ((guard (org-match-line "[ \t]*$"))
  16189. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  16190. (user-error
  16191. (substitute-command-keys
  16192. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  16193. ((or `babel-call `inline-babel-call)
  16194. (let ((info (org-babel-lob-get-info context)))
  16195. (when info (org-babel-execute-src-block nil info))))
  16196. (`clock (org-clock-update-time-maybe))
  16197. (`dynamic-block
  16198. (save-excursion
  16199. (goto-char (org-element-property :post-affiliated context))
  16200. (org-update-dblock)))
  16201. (`footnote-definition
  16202. (goto-char (org-element-property :post-affiliated context))
  16203. (call-interactively 'org-footnote-action))
  16204. (`footnote-reference (call-interactively #'org-footnote-action))
  16205. ((or `headline `inlinetask)
  16206. (save-excursion (goto-char (org-element-property :begin context))
  16207. (call-interactively #'org-set-tags-command)))
  16208. (`item
  16209. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  16210. ;; unconditionally, whereas `C-u' will toggle its presence.
  16211. ;; Without a universal argument, if the item has a checkbox,
  16212. ;; toggle it. Otherwise repair the list.
  16213. (if (or radio-list-p
  16214. (and (boundp org-list-checkbox-radio-mode)
  16215. org-list-checkbox-radio-mode))
  16216. (org-toggle-radio-button arg)
  16217. (let* ((box (org-element-property :checkbox context))
  16218. (struct (org-element-property :structure context))
  16219. (old-struct (copy-tree struct))
  16220. (parents (org-list-parents-alist struct))
  16221. (prevs (org-list-prevs-alist struct))
  16222. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  16223. (org-list-set-checkbox
  16224. (org-element-property :begin context) struct
  16225. (cond ((equal arg '(16)) "[-]")
  16226. ((and (not box) (equal arg '(4))) "[ ]")
  16227. ((or (not box) (equal arg '(4))) nil)
  16228. ((eq box 'on) "[ ]")
  16229. (t "[X]")))
  16230. ;; Mimic `org-list-write-struct' but with grabbing a return
  16231. ;; value from `org-list-struct-fix-box'.
  16232. (org-list-struct-fix-ind struct parents 2)
  16233. (org-list-struct-fix-item-end struct)
  16234. (org-list-struct-fix-bul struct prevs)
  16235. (org-list-struct-fix-ind struct parents)
  16236. (let ((block-item
  16237. (org-list-struct-fix-box struct parents prevs orderedp)))
  16238. (if (and box (equal struct old-struct))
  16239. (if (equal arg '(16))
  16240. (message "Checkboxes already reset")
  16241. (user-error "Cannot toggle this checkbox: %s"
  16242. (if (eq box 'on)
  16243. "all subitems checked"
  16244. "unchecked subitems")))
  16245. (org-list-struct-apply-struct struct old-struct)
  16246. (org-update-checkbox-count-maybe))
  16247. (when block-item
  16248. (message "Checkboxes were removed due to empty box at line %d"
  16249. (org-current-line block-item)))))))
  16250. (`plain-list
  16251. ;; At a plain list, with a double C-u argument, set
  16252. ;; checkboxes of each item to "[-]", whereas a single one
  16253. ;; will toggle their presence according to the state of the
  16254. ;; first item in the list. Without an argument, repair the
  16255. ;; list.
  16256. (if (or radio-list-p
  16257. (and (boundp org-list-checkbox-radio-mode)
  16258. org-list-checkbox-radio-mode))
  16259. (org-toggle-radio-button arg)
  16260. (let* ((begin (org-element-property :contents-begin context))
  16261. (struct (org-element-property :structure context))
  16262. (old-struct (copy-tree struct))
  16263. (first-box (save-excursion
  16264. (goto-char begin)
  16265. (looking-at org-list-full-item-re)
  16266. (match-string-no-properties 3)))
  16267. (new-box (cond ((equal arg '(16)) "[-]")
  16268. ((equal arg '(4)) (unless first-box "[ ]"))
  16269. ((equal first-box "[X]") "[ ]")
  16270. (t "[X]"))))
  16271. (cond
  16272. (arg
  16273. (dolist (pos
  16274. (org-list-get-all-items
  16275. begin struct (org-list-prevs-alist struct)))
  16276. (org-list-set-checkbox pos struct new-box)))
  16277. ((and first-box (eq (point) begin))
  16278. ;; For convenience, when point is at bol on the first
  16279. ;; item of the list and no argument is provided, simply
  16280. ;; toggle checkbox of that item, if any.
  16281. (org-list-set-checkbox begin struct new-box)))
  16282. (when (equal
  16283. (org-list-write-struct
  16284. struct (org-list-parents-alist struct) old-struct)
  16285. old-struct)
  16286. (message "Cannot update this checkbox"))
  16287. (org-update-checkbox-count-maybe))))
  16288. (`keyword
  16289. (let ((org-inhibit-startup-visibility-stuff t)
  16290. (org-startup-align-all-tables nil))
  16291. (when (boundp 'org-table-coordinate-overlays)
  16292. (mapc #'delete-overlay org-table-coordinate-overlays)
  16293. (setq org-table-coordinate-overlays nil))
  16294. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  16295. (message "Local setup has been refreshed"))
  16296. ((or `property-drawer `node-property)
  16297. (call-interactively #'org-property-action))
  16298. (`radio-target
  16299. (call-interactively #'org-update-radio-target-regexp))
  16300. (`statistics-cookie
  16301. (call-interactively #'org-update-statistics-cookies))
  16302. ((or `table `table-cell `table-row)
  16303. ;; At a table, generate a plot if on the #+plot line,
  16304. ;; recalculate every field and align it otherwise. Also
  16305. ;; send the table if necessary.
  16306. (cond
  16307. ((and (org-match-line "[ \t]*#\\+plot:")
  16308. (< (point) (org-element-property :post-affiliated context)))
  16309. (org-plot/gnuplot))
  16310. ;; If the table has a `table.el' type, just give up.
  16311. ((eq (org-element-property :type context) 'table.el)
  16312. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  16313. Use `\\[org-edit-special]' to edit table.el tables")))
  16314. ;; At a table row or cell, maybe recalculate line but always
  16315. ;; align table.
  16316. ((or (eq type 'table)
  16317. ;; Check if point is at a TBLFM line.
  16318. (and (eq type 'table-row)
  16319. (= (point) (org-element-property :end context))))
  16320. (save-excursion
  16321. (if (org-at-TBLFM-p)
  16322. (progn (require 'org-table)
  16323. (org-table-calc-current-TBLFM))
  16324. (goto-char (org-element-property :contents-begin context))
  16325. (org-call-with-arg 'org-table-recalculate (or arg t))
  16326. (orgtbl-send-table 'maybe))))
  16327. (t
  16328. (org-table-maybe-eval-formula)
  16329. (cond (arg (call-interactively #'org-table-recalculate))
  16330. ((org-table-maybe-recalculate-line))
  16331. (t (org-table-align))))))
  16332. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  16333. (org-timestamp-change 0 'day))
  16334. ((and `nil (guard (org-at-heading-p)))
  16335. ;; When point is on an unsupported object type, we can miss
  16336. ;; the fact that it also is at a heading. Handle it here.
  16337. (call-interactively #'org-set-tags-command))
  16338. ((guard
  16339. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  16340. (_
  16341. (user-error
  16342. (substitute-command-keys
  16343. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  16344. (defun org-mode-restart ()
  16345. "Restart `org-mode'."
  16346. (interactive)
  16347. (let ((indent-status (bound-and-true-p org-indent-mode)))
  16348. (funcall major-mode)
  16349. (hack-local-variables)
  16350. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  16351. (org-indent-mode -1))
  16352. (org-reset-file-cache))
  16353. (message "%s restarted" major-mode))
  16354. (defun org-flag-above-first-heading (&optional arg)
  16355. "Hide from bob up to the first heading.
  16356. Move point to the beginning of first heading or end of buffer."
  16357. (goto-char (point-min))
  16358. (unless (org-at-heading-p)
  16359. (outline-next-heading))
  16360. (unless (bobp)
  16361. (org-flag-region 1 (1- (point)) (not arg) 'outline)))
  16362. (defun org-show-branches-buffer ()
  16363. "Show all branches in the buffer."
  16364. (org-flag-above-first-heading)
  16365. (outline-hide-sublevels 1)
  16366. (unless (eobp)
  16367. (outline-show-branches)
  16368. (while (outline-get-next-sibling)
  16369. (outline-show-branches)))
  16370. (goto-char (point-min)))
  16371. (defun org-kill-note-or-show-branches ()
  16372. "Abort storing current note, or show just branches."
  16373. (interactive)
  16374. (cond (org-finish-function
  16375. (let ((org-note-abort t)) (funcall org-finish-function)))
  16376. ((org-before-first-heading-p)
  16377. (org-show-branches-buffer)
  16378. (org-hide-archived-subtrees (point-min) (point-max)))
  16379. (t
  16380. (let ((beg (progn (org-back-to-heading) (point)))
  16381. (end (save-excursion (org-end-of-subtree t t) (point))))
  16382. (outline-hide-subtree)
  16383. (outline-show-branches)
  16384. (org-hide-archived-subtrees beg end)))))
  16385. (defun org-delete-indentation (&optional arg)
  16386. "Join current line to previous and fix whitespace at join.
  16387. If previous line is a headline add to headline title. Otherwise
  16388. the function calls `delete-indentation'.
  16389. I.e. with a non-nil optional argument, join the line with the
  16390. following one. If there is a region then join the lines in that
  16391. region."
  16392. (interactive "*P")
  16393. (if (save-excursion
  16394. (beginning-of-line (if arg 1 0))
  16395. (let ((case-fold-search nil))
  16396. (looking-at org-complex-heading-regexp)))
  16397. ;; At headline.
  16398. (let ((tags-column (when (match-beginning 5)
  16399. (save-excursion (goto-char (match-beginning 5))
  16400. (current-column))))
  16401. (string (concat " " (progn (when arg (forward-line 1))
  16402. (org-trim (delete-and-extract-region
  16403. (line-beginning-position)
  16404. (line-end-position)))))))
  16405. (unless (bobp) (delete-region (point) (1- (point))))
  16406. (goto-char (or (match-end 4)
  16407. (match-beginning 5)
  16408. (match-end 0)))
  16409. (skip-chars-backward " \t")
  16410. (save-excursion (insert string))
  16411. ;; Adjust alignment of tags.
  16412. (cond
  16413. ((not tags-column)) ;no tags
  16414. (org-auto-align-tags (org-align-tags))
  16415. (t (org--align-tags-here tags-column)))) ;preserve tags column
  16416. (let ((current-prefix-arg arg))
  16417. (call-interactively #'delete-indentation))))
  16418. (defun org-open-line (n)
  16419. "Insert a new row in tables, call `open-line' elsewhere.
  16420. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  16421. As a special case, when a document starts with a table, allow to
  16422. call `open-line' on the very first character."
  16423. (interactive "*p")
  16424. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  16425. (org-table-insert-row)
  16426. (open-line n)))
  16427. (defun org--newline (indent arg interactive)
  16428. "Call `newline-and-indent' or just `newline'.
  16429. If INDENT is non-nil, call `newline-and-indent' with ARG to
  16430. indent unconditionally; otherwise, call `newline' with ARG and
  16431. INTERACTIVE, which can trigger indentation if
  16432. `electric-indent-mode' is enabled."
  16433. (if indent
  16434. (org-newline-and-indent arg)
  16435. (newline arg interactive)))
  16436. (defun org-return (&optional indent arg interactive)
  16437. "Goto next table row or insert a newline.
  16438. Calls `org-table-next-row' or `newline', depending on context.
  16439. When optional INDENT argument is non-nil, call
  16440. `newline-and-indent' with ARG, otherwise call `newline' with ARG
  16441. and INTERACTIVE.
  16442. When `org-return-follows-link' is non-nil and point is on
  16443. a timestamp or a link, call `org-open-at-point'. However, it
  16444. will not happen if point is in a table or on a \"dead\"
  16445. object (e.g., within a comment). In these case, you need to use
  16446. `org-open-at-point' directly."
  16447. (interactive "i\nP\np")
  16448. (let* ((context (if org-return-follows-link (org-element-context)
  16449. (org-element-at-point)))
  16450. (element-type (org-element-type context)))
  16451. (cond
  16452. ;; In a table, call `org-table-next-row'. However, before first
  16453. ;; column or after last one, split the table.
  16454. ((or (and (eq 'table element-type)
  16455. (not (eq 'table.el (org-element-property :type context)))
  16456. (>= (point) (org-element-property :contents-begin context))
  16457. (< (point) (org-element-property :contents-end context)))
  16458. (org-element-lineage context '(table-row table-cell) t))
  16459. (if (or (looking-at-p "[ \t]*$")
  16460. (save-excursion (skip-chars-backward " \t") (bolp)))
  16461. (insert "\n")
  16462. (org-table-justify-field-maybe)
  16463. (call-interactively #'org-table-next-row)))
  16464. ;; On a link or a timestamp, call `org-open-at-point' if
  16465. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  16466. ;; locations, e.g., in a comment, as `org-open-at-point'.
  16467. ((and org-return-follows-link
  16468. (or (and (eq 'link element-type)
  16469. ;; Ensure point is not on the white spaces after
  16470. ;; the link.
  16471. (let ((origin (point)))
  16472. (org-with-point-at (org-element-property :end context)
  16473. (skip-chars-backward " \t")
  16474. (> (point) origin))))
  16475. (org-in-regexp org-ts-regexp-both nil t)
  16476. (org-in-regexp org-tsr-regexp-both nil t)
  16477. (org-in-regexp org-link-any-re nil t)))
  16478. (call-interactively #'org-open-at-point))
  16479. ;; Insert newline in heading, but preserve tags.
  16480. ((and (not (bolp))
  16481. (let ((case-fold-search nil))
  16482. (org-match-line org-complex-heading-regexp)))
  16483. ;; At headline. Split line. However, if point is on keyword,
  16484. ;; priority cookie or tags, do not break any of them: add
  16485. ;; a newline after the headline instead.
  16486. (let ((tags-column (and (match-beginning 5)
  16487. (save-excursion (goto-char (match-beginning 5))
  16488. (current-column))))
  16489. (string
  16490. (when (and (match-end 4) (org-point-in-group (point) 4))
  16491. (delete-and-extract-region (point) (match-end 4)))))
  16492. ;; Adjust tag alignment.
  16493. (cond
  16494. ((not (and tags-column string)))
  16495. (org-auto-align-tags (org-align-tags))
  16496. (t (org--align-tags-here tags-column))) ;preserve tags column
  16497. (end-of-line)
  16498. (org-show-entry)
  16499. (org--newline indent arg interactive)
  16500. (when string (save-excursion (insert (org-trim string))))))
  16501. ;; In a list, make sure indenting keeps trailing text within.
  16502. ((and (not (eolp))
  16503. (org-element-lineage context '(item)))
  16504. (let ((trailing-data
  16505. (delete-and-extract-region (point) (line-end-position))))
  16506. (org--newline indent arg interactive)
  16507. (save-excursion (insert trailing-data))))
  16508. (t
  16509. ;; Do not auto-fill when point is in an Org property drawer.
  16510. (let ((auto-fill-function (and (not (org-at-property-p))
  16511. auto-fill-function)))
  16512. (org--newline indent arg interactive))))))
  16513. (defun org-return-and-maybe-indent ()
  16514. "Goto next table row, or insert a newline, maybe indented.
  16515. Call `org-table-next-row' or `org-return', depending on context.
  16516. See the individual commands for more information.
  16517. When inserting a newline, if `org-adapt-indentation' is t:
  16518. indent the line if `electric-indent-mode' is disabled, don't
  16519. indent it if it is enabled."
  16520. (interactive)
  16521. (org-return (not electric-indent-mode)))
  16522. (defun org-ctrl-c-tab (&optional arg)
  16523. "Toggle columns width in a table, or show children.
  16524. Call `org-table-toggle-column-width' if point is in a table.
  16525. Otherwise provide a compact view of the children. ARG is the
  16526. level to hide."
  16527. (interactive "p")
  16528. (cond
  16529. ((org-at-table-p)
  16530. (call-interactively #'org-table-toggle-column-width))
  16531. ((org-before-first-heading-p)
  16532. (save-excursion
  16533. (org-flag-above-first-heading)
  16534. (outline-hide-sublevels (or arg 1))))
  16535. (t
  16536. (outline-hide-subtree)
  16537. (org-show-children arg))))
  16538. (defun org-ctrl-c-star ()
  16539. "Compute table, or change heading status of lines.
  16540. Calls `org-table-recalculate' or `org-toggle-heading',
  16541. depending on context."
  16542. (interactive)
  16543. (cond
  16544. ((org-at-table-p)
  16545. (call-interactively 'org-table-recalculate))
  16546. (t
  16547. ;; Convert all lines in region to list items
  16548. (call-interactively 'org-toggle-heading))))
  16549. (defun org-ctrl-c-minus ()
  16550. "Insert separator line in table or modify bullet status of line.
  16551. Also turns a plain line or a region of lines into list items.
  16552. Calls `org-table-insert-hline', `org-toggle-item', or
  16553. `org-cycle-list-bullet', depending on context."
  16554. (interactive)
  16555. (cond
  16556. ((org-at-table-p)
  16557. (call-interactively 'org-table-insert-hline))
  16558. ((org-region-active-p)
  16559. (call-interactively 'org-toggle-item))
  16560. ((org-in-item-p)
  16561. (call-interactively 'org-cycle-list-bullet))
  16562. (t
  16563. (call-interactively 'org-toggle-item))))
  16564. (defun org-toggle-heading (&optional nstars)
  16565. "Convert headings to normal text, or items or text to headings.
  16566. If there is no active region, only convert the current line.
  16567. With a `\\[universal-argument]' prefix, convert the whole list at
  16568. point into heading.
  16569. In a region:
  16570. - If the first non blank line is a headline, remove the stars
  16571. from all headlines in the region.
  16572. - If it is a normal line, turn each and every normal line (i.e.,
  16573. not an heading or an item) in the region into headings. If you
  16574. want to convert only the first line of this region, use one
  16575. universal prefix argument.
  16576. - If it is a plain list item, turn all plain list items into headings.
  16577. When converting a line into a heading, the number of stars is chosen
  16578. such that the lines become children of the current entry. However,
  16579. when a numeric prefix argument is given, its value determines the
  16580. number of stars to add."
  16581. (interactive "P")
  16582. (let ((skip-blanks
  16583. ;; Return beginning of first non-blank line, starting from
  16584. ;; line at POS.
  16585. (lambda (pos)
  16586. (save-excursion
  16587. (goto-char pos)
  16588. (while (org-at-comment-p) (forward-line))
  16589. (skip-chars-forward " \r\t\n")
  16590. (line-beginning-position))))
  16591. beg end toggled)
  16592. ;; Determine boundaries of changes. If a universal prefix has
  16593. ;; been given, put the list in a region. If region ends at a bol,
  16594. ;; do not consider the last line to be in the region.
  16595. (when (and current-prefix-arg (org-at-item-p))
  16596. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  16597. (org-mark-element))
  16598. (if (org-region-active-p)
  16599. (setq beg (funcall skip-blanks (region-beginning))
  16600. end (copy-marker (save-excursion
  16601. (goto-char (region-end))
  16602. (if (bolp) (point) (line-end-position)))))
  16603. (setq beg (funcall skip-blanks (line-beginning-position))
  16604. end (copy-marker (line-end-position))))
  16605. ;; Ensure inline tasks don't count as headings.
  16606. (org-with-limited-levels
  16607. (save-excursion
  16608. (goto-char beg)
  16609. (cond
  16610. ;; Case 1. Started at an heading: de-star headings.
  16611. ((org-at-heading-p)
  16612. (while (< (point) end)
  16613. (when (org-at-heading-p t)
  16614. (looking-at org-outline-regexp) (replace-match "")
  16615. (setq toggled t))
  16616. (forward-line)))
  16617. ;; Case 2. Started at an item: change items into headlines.
  16618. ;; One star will be added by `org-list-to-subtree'.
  16619. ((org-at-item-p)
  16620. (while (< (point) end)
  16621. (when (org-at-item-p)
  16622. ;; Pay attention to cases when region ends before list.
  16623. (let* ((struct (org-list-struct))
  16624. (list-end
  16625. (min (org-list-get-bottom-point struct) (1+ end))))
  16626. (save-restriction
  16627. (narrow-to-region (point) list-end)
  16628. (insert (org-list-to-subtree
  16629. (org-list-to-lisp t)
  16630. (pcase (org-current-level)
  16631. (`nil 1)
  16632. (l (1+ (org-reduced-level l)))))
  16633. "\n")))
  16634. (setq toggled t))
  16635. (forward-line)))
  16636. ;; Case 3. Started at normal text: make every line an heading,
  16637. ;; skipping headlines and items.
  16638. (t (let* ((stars
  16639. (make-string
  16640. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  16641. (add-stars
  16642. (cond (nstars "") ; stars from prefix only
  16643. ((equal stars "") "*") ; before first heading
  16644. (org-odd-levels-only "**") ; inside heading, odd
  16645. (t "*"))) ; inside heading, oddeven
  16646. (rpl (concat stars add-stars " "))
  16647. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  16648. (while (< (point) (if (equal nstars '(4)) lend end))
  16649. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  16650. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  16651. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  16652. (forward-line)))))))
  16653. (unless toggled (message "Cannot toggle heading from here"))))
  16654. (defun org-meta-return (&optional arg)
  16655. "Insert a new heading or wrap a region in a table.
  16656. Calls `org-insert-heading', `org-insert-item' or
  16657. `org-table-wrap-region', depending on context. When called with
  16658. an argument, unconditionally call `org-insert-heading'."
  16659. (interactive "P")
  16660. (org-check-before-invisible-edit 'insert)
  16661. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  16662. (call-interactively (cond (arg #'org-insert-heading)
  16663. ((org-at-table-p) #'org-table-wrap-region)
  16664. ((org-in-item-p) #'org-insert-item)
  16665. (t #'org-insert-heading)))))
  16666. ;;; Menu entries
  16667. (defsubst org-in-subtree-not-table-p ()
  16668. "Are we in a subtree and not in a table?"
  16669. (and (not (org-before-first-heading-p))
  16670. (not (org-at-table-p))))
  16671. ;; Define the Org mode menus
  16672. (easy-menu-define org-org-menu org-mode-map "Org menu."
  16673. `("Org"
  16674. ("Show/Hide"
  16675. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  16676. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  16677. ["Sparse Tree..." org-sparse-tree t]
  16678. ["Reveal Context" org-reveal t]
  16679. ["Show All" org-show-all t]
  16680. "--"
  16681. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  16682. "--"
  16683. ["New Heading" org-insert-heading t]
  16684. ("Navigate Headings"
  16685. ["Up" outline-up-heading t]
  16686. ["Next" outline-next-visible-heading t]
  16687. ["Previous" outline-previous-visible-heading t]
  16688. ["Next Same Level" outline-forward-same-level t]
  16689. ["Previous Same Level" outline-backward-same-level t]
  16690. "--"
  16691. ["Jump" org-goto t])
  16692. ("Edit Structure"
  16693. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  16694. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  16695. "--"
  16696. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  16697. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  16698. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  16699. "--"
  16700. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  16701. "--"
  16702. ["Copy visible text" org-copy-visible t]
  16703. "--"
  16704. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  16705. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  16706. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  16707. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  16708. "--"
  16709. ["Sort Region/Children" org-sort t]
  16710. "--"
  16711. ["Convert to odd levels" org-convert-to-odd-levels t]
  16712. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  16713. ("Editing"
  16714. ["Emphasis..." org-emphasize t]
  16715. ["Add block structure" org-insert-structure-template t]
  16716. ["Edit Source Example" org-edit-special t]
  16717. "--"
  16718. ["Footnote new/jump" org-footnote-action t]
  16719. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  16720. ("Archive"
  16721. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  16722. "--"
  16723. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  16724. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  16725. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)])
  16726. "--"
  16727. ("Hyperlinks"
  16728. ["Store Link (Global)" org-store-link t]
  16729. ["Find existing link to here" org-occur-link-in-agenda-files t]
  16730. ["Insert Link" org-insert-link t]
  16731. ["Follow Link" org-open-at-point t]
  16732. "--"
  16733. ["Next link" org-next-link t]
  16734. ["Previous link" org-previous-link t]
  16735. "--"
  16736. ["Descriptive Links"
  16737. org-toggle-link-display
  16738. :style radio
  16739. :selected org-descriptive-links
  16740. ]
  16741. ["Literal Links"
  16742. org-toggle-link-display
  16743. :style radio
  16744. :selected (not org-descriptive-links)])
  16745. "--"
  16746. ("TODO Lists"
  16747. ["TODO/DONE/-" org-todo t]
  16748. ("Select keyword"
  16749. ["Next keyword" org-shiftright (org-at-heading-p)]
  16750. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  16751. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  16752. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  16753. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  16754. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  16755. ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  16756. "--"
  16757. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  16758. :selected org-enforce-todo-dependencies :style toggle :active t]
  16759. "Settings for tree at point"
  16760. ["Do Children sequentially" org-toggle-ordered-property :style radio
  16761. :selected (org-entry-get nil "ORDERED")
  16762. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16763. ["Do Children parallel" org-toggle-ordered-property :style radio
  16764. :selected (not (org-entry-get nil "ORDERED"))
  16765. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16766. "--"
  16767. ["Set Priority" org-priority t]
  16768. ["Priority Up" org-shiftup t]
  16769. ["Priority Down" org-shiftdown t]
  16770. "--"
  16771. ["Get news from all feeds" org-feed-update-all t]
  16772. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  16773. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  16774. ("TAGS and Properties"
  16775. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  16776. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  16777. "--"
  16778. ["Set property" org-set-property (not (org-before-first-heading-p))]
  16779. ["Column view of properties" org-columns t]
  16780. ["Insert Column View DBlock" org-columns-insert-dblock t])
  16781. ("Dates and Scheduling"
  16782. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  16783. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  16784. ("Change Date"
  16785. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  16786. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  16787. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  16788. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  16789. ["Compute Time Range" org-evaluate-time-range t]
  16790. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  16791. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  16792. "--"
  16793. ["Custom time format" org-toggle-time-stamp-overlays
  16794. :style radio :selected org-display-custom-times]
  16795. "--"
  16796. ["Goto Calendar" org-goto-calendar t]
  16797. ["Date from Calendar" org-date-from-calendar t]
  16798. "--"
  16799. ["Start/Restart Timer" org-timer-start t]
  16800. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  16801. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  16802. ["Insert Timer String" org-timer t]
  16803. ["Insert Timer Item" org-timer-item t])
  16804. ("Logging work"
  16805. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  16806. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  16807. ["Clock out" org-clock-out t]
  16808. ["Clock cancel" org-clock-cancel t]
  16809. "--"
  16810. ["Mark as default task" org-clock-mark-default-task t]
  16811. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  16812. ["Goto running clock" org-clock-goto t]
  16813. "--"
  16814. ["Display times" org-clock-display t]
  16815. ["Create clock table" org-clock-report t]
  16816. "--"
  16817. ["Record DONE time"
  16818. (progn (setq org-log-done (not org-log-done))
  16819. (message "Switching to %s will %s record a timestamp"
  16820. (car org-done-keywords)
  16821. (if org-log-done "automatically" "not")))
  16822. :style toggle :selected org-log-done])
  16823. "--"
  16824. ["Agenda Command..." org-agenda t]
  16825. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  16826. ("File List for Agenda")
  16827. ("Special views current file"
  16828. ["TODO Tree" org-show-todo-tree t]
  16829. ["Check Deadlines" org-check-deadlines t]
  16830. ["Tags/Property tree" org-match-sparse-tree t])
  16831. "--"
  16832. ["Export/Publish..." org-export-dispatch t]
  16833. ("LaTeX"
  16834. ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  16835. :style toggle :selected org-cdlatex-mode]
  16836. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  16837. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  16838. ["Modify math symbol" org-cdlatex-math-modify
  16839. (org-inside-LaTeX-fragment-p)]
  16840. ["Insert citation" org-reftex-citation t])
  16841. "--"
  16842. ("Documentation"
  16843. ["Show Version" org-version t]
  16844. ["Info Documentation" org-info t]
  16845. ["Browse Org News" org-browse-news t])
  16846. ("Customize"
  16847. ["Browse Org Group" org-customize t]
  16848. "--"
  16849. ["Expand This Menu" org-create-customize-menu t])
  16850. ["Send bug report" org-submit-bug-report t]
  16851. "--"
  16852. ("Refresh/Reload"
  16853. ["Refresh setup current buffer" org-mode-restart t]
  16854. ["Reload Org (after update)" org-reload t]
  16855. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])))
  16856. (easy-menu-define org-tbl-menu org-mode-map "Org Table menu."
  16857. '("Table"
  16858. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  16859. ["Next Field" org-cycle (org-at-table-p)]
  16860. ["Previous Field" org-shifttab (org-at-table-p)]
  16861. ["Next Row" org-return (org-at-table-p)]
  16862. "--"
  16863. ["Blank Field" org-table-blank-field (org-at-table-p)]
  16864. ["Edit Field" org-table-edit-field (org-at-table-p)]
  16865. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  16866. "--"
  16867. ("Column"
  16868. ["Move Column Left" org-metaleft (org-at-table-p)]
  16869. ["Move Column Right" org-metaright (org-at-table-p)]
  16870. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  16871. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  16872. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  16873. ("Row"
  16874. ["Move Row Up" org-metaup (org-at-table-p)]
  16875. ["Move Row Down" org-metadown (org-at-table-p)]
  16876. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  16877. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  16878. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  16879. "--"
  16880. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  16881. ("Rectangle"
  16882. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  16883. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  16884. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  16885. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  16886. "--"
  16887. ("Calculate"
  16888. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  16889. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  16890. ["Edit Formulas" org-edit-special (org-at-table-p)]
  16891. "--"
  16892. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  16893. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  16894. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  16895. "--"
  16896. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  16897. "--"
  16898. ["Sum Column/Rectangle" org-table-sum
  16899. (or (org-at-table-p) (org-region-active-p))]
  16900. ["Which Column?" org-table-current-column (org-at-table-p)])
  16901. ["Debug Formulas"
  16902. org-table-toggle-formula-debugger
  16903. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  16904. ["Show Col/Row Numbers"
  16905. org-table-toggle-coordinate-overlays
  16906. :style toggle
  16907. :selected (bound-and-true-p org-table-overlay-coordinates)]
  16908. "--"
  16909. ["Create" org-table-create (not (org-at-table-p))]
  16910. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  16911. ["Import from File" org-table-import (not (org-at-table-p))]
  16912. ["Export to File" org-table-export (org-at-table-p)]
  16913. "--"
  16914. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  16915. "--"
  16916. ("Plot"
  16917. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  16918. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  16919. (defun org-info (&optional node)
  16920. "Read documentation for Org in the info system.
  16921. With optional NODE, go directly to that node."
  16922. (interactive)
  16923. (info (format "(org)%s" (or node ""))))
  16924. (defun org-browse-news ()
  16925. "Browse the news for the latest major release."
  16926. (interactive)
  16927. (browse-url "https://orgmode.org/Changes.html"))
  16928. ;;;###autoload
  16929. (defun org-submit-bug-report ()
  16930. "Submit a bug report on Org via mail.
  16931. Don't hesitate to report any problems or inaccurate documentation.
  16932. If you don't have setup sending mail from (X)Emacs, please copy the
  16933. output buffer into your mail program, as it gives us important
  16934. information about your Org version and configuration."
  16935. (interactive)
  16936. (require 'reporter)
  16937. (defvar reporter-prompt-for-summary-p)
  16938. (org-load-modules-maybe)
  16939. (org-require-autoloaded-modules)
  16940. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  16941. (reporter-submit-bug-report
  16942. "emacs-orgmode@gnu.org"
  16943. (org-version nil 'full)
  16944. (let (list)
  16945. (save-window-excursion
  16946. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  16947. (delete-other-windows)
  16948. (erase-buffer)
  16949. (insert "You are about to submit a bug report to the Org mailing list.
  16950. If your report is about Org installation, please read this section:
  16951. https://orgmode.org/org.html#Installation
  16952. Please read https://orgmode.org/org.html#Feedback on how to make
  16953. a good report, it will help Org contributors fixing your problem.
  16954. Search https://lists.gnu.org/archive/html/emacs-orgmode/ to see
  16955. if the issue you are about to raise has already been dealt with.
  16956. We also would like to add your full Org and Outline configuration
  16957. to the bug report. It will help us debugging the issue.
  16958. *HOWEVER*, some variables you have customized may contain private
  16959. information. The names of customers, colleagues, or friends, might
  16960. appear in the form of file names, tags, todo states or search strings.
  16961. If you answer \"yes\" to the prompt, you might want to check and remove
  16962. such private information before sending the email.")
  16963. (add-text-properties (point-min) (point-max) '(face org-warning))
  16964. (when (yes-or-no-p "Include your Org configuration ")
  16965. (mapatoms
  16966. (lambda (v)
  16967. (and (boundp v)
  16968. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  16969. (or (and (symbol-value v)
  16970. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  16971. (and
  16972. (get v 'custom-type) (get v 'standard-value)
  16973. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  16974. (push v list)))))
  16975. (kill-buffer (get-buffer "*Warn about privacy*"))
  16976. list))
  16977. nil nil
  16978. "Remember to cover the basics, that is, what you expected to happen and
  16979. what in fact did happen. You don't know how to make a good report? See
  16980. https://orgmode.org/manual/Feedback.html#Feedback
  16981. Your bug report will be posted to the Org mailing list.
  16982. ------------------------------------------------------------------------")
  16983. (save-excursion
  16984. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  16985. (replace-match "\\1[BUG] \\3 [\\2]")))))
  16986. (defun org-install-agenda-files-menu ()
  16987. "Install agenda file menu."
  16988. (let ((bl (buffer-list)))
  16989. (save-excursion
  16990. (while bl
  16991. (set-buffer (pop bl))
  16992. (when (derived-mode-p 'org-mode) (setq bl nil)))
  16993. (when (derived-mode-p 'org-mode)
  16994. (easy-menu-change
  16995. '("Org") "File List for Agenda"
  16996. (append
  16997. (list
  16998. ["Edit File List" (org-edit-agenda-file-list) t]
  16999. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  17000. ["Remove Current File from List" org-remove-file t]
  17001. ["Cycle through agenda files" org-cycle-agenda-files t]
  17002. ["Occur in all agenda files" org-occur-in-agenda-files t]
  17003. "--")
  17004. (mapcar 'org-file-menu-entry
  17005. ;; Prevent initialization from failing.
  17006. (ignore-errors (org-agenda-files t)))))))))
  17007. ;;;; Documentation
  17008. (defun org-require-autoloaded-modules ()
  17009. (interactive)
  17010. (mapc #'require
  17011. '(org-agenda org-archive org-attach org-clock org-colview org-id
  17012. org-table org-timer)))
  17013. ;;;###autoload
  17014. (defun org-reload (&optional uncompiled)
  17015. "Reload all Org Lisp files.
  17016. With prefix arg UNCOMPILED, load the uncompiled versions."
  17017. (interactive "P")
  17018. (require 'loadhist)
  17019. (let* ((org-dir (org-find-library-dir "org"))
  17020. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  17021. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  17022. (remove-re (format "\\`%s\\'"
  17023. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  17024. (feats (delete-dups
  17025. (mapcar 'file-name-sans-extension
  17026. (mapcar 'file-name-nondirectory
  17027. (delq nil
  17028. (mapcar 'feature-file
  17029. features))))))
  17030. (lfeat (append
  17031. (sort
  17032. (setq feats
  17033. (delq nil (mapcar
  17034. (lambda (f)
  17035. (if (and (string-match feature-re f)
  17036. (not (string-match remove-re f)))
  17037. f nil))
  17038. feats)))
  17039. 'string-lessp)
  17040. (list "org-version" "org")))
  17041. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  17042. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  17043. load-uncore load-misses)
  17044. (setq load-misses
  17045. (delq 't
  17046. (mapcar (lambda (f)
  17047. (or (org-load-noerror-mustsuffix (concat org-dir f))
  17048. (and (string= org-dir contrib-dir)
  17049. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  17050. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  17051. (push f load-uncore)
  17052. 't)
  17053. f))
  17054. lfeat)))
  17055. (when load-uncore
  17056. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  17057. (if (> (length load-uncore) 1) "s were" " was")
  17058. (reverse load-uncore)))
  17059. (if load-misses
  17060. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  17061. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  17062. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  17063. ;;;###autoload
  17064. (defun org-customize ()
  17065. "Call the customize function with org as argument."
  17066. (interactive)
  17067. (org-load-modules-maybe)
  17068. (org-require-autoloaded-modules)
  17069. (customize-browse 'org))
  17070. (defun org-create-customize-menu ()
  17071. "Create a full customization menu for Org mode, insert it into the menu."
  17072. (interactive)
  17073. (org-load-modules-maybe)
  17074. (org-require-autoloaded-modules)
  17075. (easy-menu-change
  17076. '("Org") "Customize"
  17077. `(["Browse Org group" org-customize t]
  17078. "--"
  17079. ,(customize-menu-create 'org)
  17080. ["Set" Custom-set t]
  17081. ["Save" Custom-save t]
  17082. ["Reset to Current" Custom-reset-current t]
  17083. ["Reset to Saved" Custom-reset-saved t]
  17084. ["Reset to Standard Settings" Custom-reset-standard t]))
  17085. (message "\"Org\"-menu now contains full customization menu"))
  17086. ;;;; Miscellaneous stuff
  17087. ;;; Generally useful functions
  17088. (defun org-in-clocktable-p ()
  17089. "Check if the cursor is in a clocktable."
  17090. (let ((pos (point)) start)
  17091. (save-excursion
  17092. (end-of-line 1)
  17093. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  17094. (setq start (match-beginning 0))
  17095. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  17096. (>= (match-end 0) pos)
  17097. start))))
  17098. (defun org-in-verbatim-emphasis ()
  17099. (save-match-data
  17100. (and (org-in-regexp org-verbatim-re 2)
  17101. (>= (point) (match-beginning 3))
  17102. (<= (point) (match-end 4)))))
  17103. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  17104. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  17105. (if (and marker (marker-buffer marker)
  17106. (buffer-live-p (marker-buffer marker)))
  17107. (progn
  17108. (pop-to-buffer-same-window (marker-buffer marker))
  17109. (when (or (> marker (point-max)) (< marker (point-min)))
  17110. (widen))
  17111. (goto-char marker)
  17112. (org-show-context 'org-goto))
  17113. (if bookmark
  17114. (bookmark-jump bookmark)
  17115. (error "Cannot find location"))))
  17116. (defun org-quote-csv-field (s)
  17117. "Quote field for inclusion in CSV material."
  17118. (if (string-match "[\",]" s)
  17119. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  17120. s))
  17121. (defun org-force-self-insert (N)
  17122. "Needed to enforce self-insert under remapping."
  17123. (interactive "p")
  17124. (self-insert-command N))
  17125. (defun org-quote-vert (s)
  17126. "Replace \"|\" with \"\\vert\"."
  17127. (while (string-match "|" s)
  17128. (setq s (replace-match "\\vert" t t s)))
  17129. s)
  17130. (defun org-uuidgen-p (s)
  17131. "Is S an ID created by UUIDGEN?"
  17132. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  17133. (defun org-in-src-block-p (&optional inside element)
  17134. "Whether point is in a code source block.
  17135. When INSIDE is non-nil, don't consider we are within a source
  17136. block when point is at #+BEGIN_SRC or #+END_SRC.
  17137. When ELEMENT is provided, it is considered to be element at point."
  17138. (save-match-data (setq element (or element (org-element-at-point))))
  17139. (when (eq 'src-block (org-element-type element))
  17140. (or (not inside)
  17141. (not (or (= (line-beginning-position)
  17142. (org-element-property :post-affiliated element))
  17143. (= (1+ (line-end-position))
  17144. (- (org-element-property :end element)
  17145. (org-element-property :post-blank element))))))))
  17146. (defun org-context ()
  17147. "Return a list of contexts of the current cursor position.
  17148. If several contexts apply, all are returned.
  17149. Each context entry is a list with a symbol naming the context, and
  17150. two positions indicating start and end of the context. Possible
  17151. contexts are:
  17152. :headline anywhere in a headline
  17153. :headline-stars on the leading stars in a headline
  17154. :todo-keyword on a TODO keyword (including DONE) in a headline
  17155. :tags on the TAGS in a headline
  17156. :priority on the priority cookie in a headline
  17157. :item on the first line of a plain list item
  17158. :item-bullet on the bullet/number of a plain list item
  17159. :checkbox on the checkbox in a plain list item
  17160. :table in an Org table
  17161. :table-special on a special filed in a table
  17162. :table-table in a table.el table
  17163. :clocktable in a clocktable
  17164. :src-block in a source block
  17165. :link on a hyperlink
  17166. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  17167. :latex-fragment on a LaTeX fragment
  17168. :latex-preview on a LaTeX fragment with overlaid preview image
  17169. This function expects the position to be visible because it uses font-lock
  17170. faces as a help to recognize the following contexts: :table-special, :link,
  17171. and :keyword."
  17172. (let* ((f (get-text-property (point) 'face))
  17173. (faces (if (listp f) f (list f)))
  17174. (case-fold-search t)
  17175. (p (point)) clist o)
  17176. ;; First the large context
  17177. (cond
  17178. ((org-at-heading-p t)
  17179. (push (list :headline (line-beginning-position)
  17180. (line-end-position))
  17181. clist)
  17182. (when (progn
  17183. (beginning-of-line 1)
  17184. (looking-at org-todo-line-tags-regexp))
  17185. (push (org-point-in-group p 1 :headline-stars) clist)
  17186. (push (org-point-in-group p 2 :todo-keyword) clist)
  17187. (push (org-point-in-group p 4 :tags) clist))
  17188. (goto-char p)
  17189. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  17190. (when (looking-at "\\[#[A-Z0-9]\\]")
  17191. (push (org-point-in-group p 0 :priority) clist)))
  17192. ((org-at-item-p)
  17193. (push (org-point-in-group p 2 :item-bullet) clist)
  17194. (push (list :item (line-beginning-position)
  17195. (save-excursion (org-end-of-item) (point)))
  17196. clist)
  17197. (and (org-at-item-checkbox-p)
  17198. (push (org-point-in-group p 0 :checkbox) clist)))
  17199. ((org-at-table-p)
  17200. (push (list :table (org-table-begin) (org-table-end)) clist)
  17201. (when (memq 'org-formula faces)
  17202. (push (list :table-special
  17203. (previous-single-property-change p 'face)
  17204. (next-single-property-change p 'face))
  17205. clist)))
  17206. ((org-at-table-p 'any)
  17207. (push (list :table-table) clist)))
  17208. (goto-char p)
  17209. (let ((case-fold-search t))
  17210. ;; New the "medium" contexts: clocktables, source blocks
  17211. (cond ((org-in-clocktable-p)
  17212. (push (list :clocktable
  17213. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  17214. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  17215. (match-beginning 1))
  17216. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  17217. (match-end 0)))
  17218. clist))
  17219. ((org-in-src-block-p)
  17220. (push (list :src-block
  17221. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  17222. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  17223. (match-beginning 1))
  17224. (and (search-forward "#+END_SRC" nil t)
  17225. (match-beginning 0)))
  17226. clist))))
  17227. (goto-char p)
  17228. ;; Now the small context
  17229. (cond
  17230. ((org-at-timestamp-p)
  17231. (push (org-point-in-group p 0 :timestamp) clist))
  17232. ((memq 'org-link faces)
  17233. (push (list :link
  17234. (previous-single-property-change p 'face)
  17235. (next-single-property-change p 'face))
  17236. clist))
  17237. ((memq 'org-special-keyword faces)
  17238. (push (list :keyword
  17239. (previous-single-property-change p 'face)
  17240. (next-single-property-change p 'face))
  17241. clist))
  17242. ((setq o (cl-some
  17243. (lambda (o)
  17244. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  17245. o))
  17246. (overlays-at (point))))
  17247. (push (list :latex-fragment
  17248. (overlay-start o) (overlay-end o))
  17249. clist)
  17250. (push (list :latex-preview
  17251. (overlay-start o) (overlay-end o))
  17252. clist))
  17253. ((org-inside-LaTeX-fragment-p)
  17254. ;; FIXME: positions wrong.
  17255. (push (list :latex-fragment (point) (point)) clist)))
  17256. (setq clist (nreverse (delq nil clist)))
  17257. clist))
  17258. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  17259. "Non-nil when point is between matches of START-RE and END-RE.
  17260. Also return a non-nil value when point is on one of the matches.
  17261. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  17262. buffer positions. Default values are the positions of headlines
  17263. surrounding the point.
  17264. The functions returns a cons cell whose car (resp. cdr) is the
  17265. position before START-RE (resp. after END-RE)."
  17266. (save-match-data
  17267. (let ((pos (point))
  17268. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  17269. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  17270. beg end)
  17271. (save-excursion
  17272. ;; Point is on a block when on START-RE or if START-RE can be
  17273. ;; found before it...
  17274. (and (or (org-in-regexp start-re)
  17275. (re-search-backward start-re limit-up t))
  17276. (setq beg (match-beginning 0))
  17277. ;; ... and END-RE after it...
  17278. (goto-char (match-end 0))
  17279. (re-search-forward end-re limit-down t)
  17280. (> (setq end (match-end 0)) pos)
  17281. ;; ... without another START-RE in-between.
  17282. (goto-char (match-beginning 0))
  17283. (not (re-search-backward start-re (1+ beg) t))
  17284. ;; Return value.
  17285. (cons beg end))))))
  17286. (defun org-in-block-p (names)
  17287. "Non-nil when point belongs to a block whose name belongs to NAMES.
  17288. NAMES is a list of strings containing names of blocks.
  17289. Return first block name matched, or nil. Beware that in case of
  17290. nested blocks, the returned name may not belong to the closest
  17291. block from point."
  17292. (save-match-data
  17293. (catch 'exit
  17294. (let ((case-fold-search t)
  17295. (lim-up (save-excursion (outline-previous-heading)))
  17296. (lim-down (save-excursion (outline-next-heading))))
  17297. (dolist (name names)
  17298. (let ((n (regexp-quote name)))
  17299. (when (org-between-regexps-p
  17300. (concat "^[ \t]*#\\+begin_" n)
  17301. (concat "^[ \t]*#\\+end_" n)
  17302. lim-up lim-down)
  17303. (throw 'exit n)))))
  17304. nil)))
  17305. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  17306. "Call `multi-occur' with buffers for all agenda files."
  17307. (interactive "sOrg-files matching: ")
  17308. (let* ((files (org-agenda-files))
  17309. (tnames (mapcar #'file-truename files))
  17310. (extra org-agenda-text-search-extra-files))
  17311. (when (eq (car extra) 'agenda-archives)
  17312. (setq extra (cdr extra))
  17313. (setq files (org-add-archive-files files)))
  17314. (dolist (f extra)
  17315. (unless (member (file-truename f) tnames)
  17316. (unless (member f files) (setq files (append files (list f))))
  17317. (setq tnames (append tnames (list (file-truename f))))))
  17318. (multi-occur
  17319. (mapcar (lambda (x)
  17320. (with-current-buffer
  17321. ;; FIXME: Why not just (find-file-noselect x)?
  17322. ;; Is it to avoid the "revert buffer" prompt?
  17323. (or (get-file-buffer x) (find-file-noselect x))
  17324. (widen)
  17325. (current-buffer)))
  17326. files)
  17327. regexp)))
  17328. (add-hook 'occur-mode-find-occurrence-hook
  17329. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  17330. (defun org-occur-link-in-agenda-files ()
  17331. "Create a link and search for it in the agendas.
  17332. The link is not stored in `org-stored-links', it is just created
  17333. for the search purpose."
  17334. (interactive)
  17335. (let ((link (condition-case nil
  17336. (org-store-link nil)
  17337. (error "Unable to create a link to here"))))
  17338. (org-occur-in-agenda-files (regexp-quote link))))
  17339. (defun org-back-over-empty-lines ()
  17340. "Move backwards over whitespace, to the beginning of the first empty line.
  17341. Returns the number of empty lines passed."
  17342. (let ((pos (point)))
  17343. (if (cdr (assq 'heading org-blank-before-new-entry))
  17344. (skip-chars-backward " \t\n\r")
  17345. (unless (eobp)
  17346. (forward-line -1)))
  17347. (beginning-of-line 2)
  17348. (goto-char (min (point) pos))
  17349. (count-lines (point) pos)))
  17350. ;;; TODO: Only called once, from ox-odt which should probably use
  17351. ;;; org-export-inline-image-p or something.
  17352. (defun org-file-image-p (file)
  17353. "Return non-nil if FILE is an image."
  17354. (save-match-data
  17355. (string-match (image-file-name-regexp) file)))
  17356. (defun org-get-cursor-date (&optional with-time)
  17357. "Return the date at cursor in as a time.
  17358. This works in the calendar and in the agenda, anywhere else it just
  17359. returns the current time.
  17360. If WITH-TIME is non-nil, returns the time of the event at point (in
  17361. the agenda) or the current time of the day; otherwise returns the
  17362. earliest time on the cursor date that Org treats as that date
  17363. (bearing in mind `org-extend-today-until')."
  17364. (let (date day defd tp hod mod)
  17365. (when with-time
  17366. (setq tp (get-text-property (point) 'time))
  17367. (when (and tp (string-match "\\([0-2]?[0-9]\\):\\([0-5][0-9]\\)" tp))
  17368. (setq hod (string-to-number (match-string 1 tp))
  17369. mod (string-to-number (match-string 2 tp))))
  17370. (or tp (let ((now (decode-time)))
  17371. (setq hod (nth 2 now)
  17372. mod (nth 1 now)))))
  17373. (cond
  17374. ((eq major-mode 'calendar-mode)
  17375. (setq date (calendar-cursor-to-date)
  17376. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  17377. (nth 1 date) (nth 0 date) (nth 2 date))))
  17378. ((eq major-mode 'org-agenda-mode)
  17379. (setq day (get-text-property (point) 'day))
  17380. (when day
  17381. (setq date (calendar-gregorian-from-absolute day)
  17382. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  17383. (nth 1 date) (nth 0 date) (nth 2 date))))))
  17384. (or defd (current-time))))
  17385. (defun org-mark-subtree (&optional up)
  17386. "Mark the current subtree.
  17387. This puts point at the start of the current subtree, and mark at
  17388. the end. If a numeric prefix UP is given, move up into the
  17389. hierarchy of headlines by UP levels before marking the subtree."
  17390. (interactive "P")
  17391. (org-with-limited-levels
  17392. (cond ((org-at-heading-p) (beginning-of-line))
  17393. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  17394. (t (outline-previous-visible-heading 1))))
  17395. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  17396. (if (called-interactively-p 'any)
  17397. (call-interactively 'org-mark-element)
  17398. (org-mark-element)))
  17399. ;;; Indentation
  17400. (defvar org-element-greater-elements)
  17401. (defun org--get-expected-indentation (element contentsp)
  17402. "Expected indentation column for current line, according to ELEMENT.
  17403. ELEMENT is an element containing point. CONTENTSP is non-nil
  17404. when indentation is to be computed according to contents of
  17405. ELEMENT."
  17406. (let ((type (org-element-type element))
  17407. (start (org-element-property :begin element))
  17408. (post-affiliated (org-element-property :post-affiliated element)))
  17409. (org-with-wide-buffer
  17410. (cond
  17411. (contentsp
  17412. (cl-case type
  17413. ((diary-sexp footnote-definition) 0)
  17414. ((headline inlinetask nil)
  17415. (if (not org-adapt-indentation) 0
  17416. (let ((level (org-current-level)))
  17417. (if level (1+ level) 0))))
  17418. ((item plain-list) (org-list-item-body-column post-affiliated))
  17419. (t
  17420. (goto-char start)
  17421. (current-indentation))))
  17422. ((memq type '(headline inlinetask nil))
  17423. (if (org-match-line "[ \t]*$")
  17424. (org--get-expected-indentation element t)
  17425. 0))
  17426. ((memq type '(diary-sexp footnote-definition)) 0)
  17427. ;; First paragraph of a footnote definition or an item.
  17428. ;; Indent like parent.
  17429. ((< (line-beginning-position) start)
  17430. (org--get-expected-indentation
  17431. (org-element-property :parent element) t))
  17432. ;; At first line: indent according to previous sibling, if any,
  17433. ;; ignoring footnote definitions and inline tasks, or parent's
  17434. ;; contents.
  17435. ((and ( = (line-beginning-position) start)
  17436. (eq org-adapt-indentation t))
  17437. (catch 'exit
  17438. (while t
  17439. (if (= (point-min) start) (throw 'exit 0)
  17440. (goto-char (1- start))
  17441. (let* ((previous (org-element-at-point))
  17442. (parent previous))
  17443. (while (and parent (<= (org-element-property :end parent) start))
  17444. (setq previous parent
  17445. parent (org-element-property :parent parent)))
  17446. (cond
  17447. ((not previous) (throw 'exit 0))
  17448. ((> (org-element-property :end previous) start)
  17449. (throw 'exit (org--get-expected-indentation previous t)))
  17450. ((memq (org-element-type previous)
  17451. '(footnote-definition inlinetask))
  17452. (setq start (org-element-property :begin previous)))
  17453. (t (goto-char (org-element-property :begin previous))
  17454. (throw 'exit
  17455. (if (bolp) (current-indentation)
  17456. ;; At first paragraph in an item or
  17457. ;; a footnote definition.
  17458. (org--get-expected-indentation
  17459. (org-element-property :parent previous) t))))))))))
  17460. ;; Otherwise, move to the first non-blank line above.
  17461. (t
  17462. (beginning-of-line)
  17463. (let ((pos (point)))
  17464. (skip-chars-backward " \r\t\n")
  17465. (cond
  17466. ;; Two blank lines end a footnote definition or a plain
  17467. ;; list. When we indent an empty line after them, the
  17468. ;; containing list or footnote definition is over, so it
  17469. ;; qualifies as a previous sibling. Therefore, we indent
  17470. ;; like its first line.
  17471. ((and (memq type '(footnote-definition plain-list))
  17472. (> (count-lines (point) pos) 2))
  17473. (goto-char start)
  17474. (current-indentation))
  17475. ;; Line above is the first one of a paragraph at the
  17476. ;; beginning of an item or a footnote definition. Indent
  17477. ;; like parent.
  17478. ((< (line-beginning-position) start)
  17479. (org--get-expected-indentation
  17480. (org-element-property :parent element) t))
  17481. ;; Line above is the beginning of an element, i.e., point
  17482. ;; was originally on the blank lines between element's start
  17483. ;; and contents.
  17484. ((= (line-beginning-position) post-affiliated)
  17485. (org--get-expected-indentation element t))
  17486. ;; POS is after contents in a greater element. Indent like
  17487. ;; the beginning of the element.
  17488. ((and (memq type org-element-greater-elements)
  17489. (let ((cend (org-element-property :contents-end element)))
  17490. (and cend (<= cend pos))))
  17491. ;; As a special case, if point is at the end of a footnote
  17492. ;; definition or an item, indent like the very last element
  17493. ;; within. If that last element is an item, indent like
  17494. ;; its contents.
  17495. (if (memq type '(footnote-definition item plain-list))
  17496. (let ((last (org-element-at-point)))
  17497. (goto-char pos)
  17498. (org--get-expected-indentation
  17499. last (eq (org-element-type last) 'item)))
  17500. (goto-char start)
  17501. (current-indentation)))
  17502. ;; In any other case, indent like the current line.
  17503. (t (current-indentation)))))
  17504. ;; Finally, no indentation is needed, fall back to 0.
  17505. (t (current-indentation))))))
  17506. (defun org--align-node-property ()
  17507. "Align node property at point.
  17508. Alignment is done according to `org-property-format', which see."
  17509. (when (save-excursion
  17510. (beginning-of-line)
  17511. (looking-at org-property-re))
  17512. (replace-match
  17513. (concat (match-string 4)
  17514. (org-trim
  17515. (format org-property-format (match-string 1) (match-string 3))))
  17516. t t)))
  17517. (defun org-indent-line ()
  17518. "Indent line depending on context.
  17519. Indentation is done according to the following rules:
  17520. - Footnote definitions, diary sexps, headlines and inline tasks
  17521. have to start at column 0.
  17522. - On the very first line of an element, consider, in order, the
  17523. next rules until one matches:
  17524. 1. If there's a sibling element before, ignoring footnote
  17525. definitions and inline tasks, indent like its first line.
  17526. 2. If element has a parent, indent like its contents. More
  17527. precisely, if parent is an item, indent after the bullet.
  17528. Else, indent like parent's first line.
  17529. 3. Otherwise, indent relatively to current level, if
  17530. `org-adapt-indentation' is t, or to left margin.
  17531. - On a blank line at the end of an element, indent according to
  17532. the type of the element. More precisely
  17533. 1. If element is a plain list, an item, or a footnote
  17534. definition, indent like the very last element within.
  17535. 2. If element is a paragraph, indent like its last non blank
  17536. line.
  17537. 3. Otherwise, indent like its very first line.
  17538. - In the code part of a source block, use language major mode
  17539. to indent current line if `org-src-tab-acts-natively' is
  17540. non-nil. If it is nil, do nothing.
  17541. - Otherwise, indent like the first non-blank line above.
  17542. The function doesn't indent an item as it could break the whole
  17543. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  17544. `\\[org-shiftmetaright]'.
  17545. Also align node properties according to `org-property-format'."
  17546. (interactive)
  17547. (unless (or (org-at-heading-p)
  17548. (and (eq org-adapt-indentation 'headline-data)
  17549. (not (or (org-at-clock-log-p)
  17550. (org-at-planning-p)))
  17551. (save-excursion
  17552. (beginning-of-line 1)
  17553. (skip-chars-backward "\n")
  17554. (or (org-at-heading-p)
  17555. (looking-back ":END:.*" (line-beginning-position))))))
  17556. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  17557. (type (org-element-type element)))
  17558. (cond ((and (memq type '(plain-list item))
  17559. (= (line-beginning-position)
  17560. (org-element-property :post-affiliated element)))
  17561. nil)
  17562. ((and (eq type 'latex-environment)
  17563. (>= (point) (org-element-property :post-affiliated element))
  17564. (< (point)
  17565. (org-with-point-at (org-element-property :end element)
  17566. (skip-chars-backward " \t\n")
  17567. (line-beginning-position 2))))
  17568. nil)
  17569. ((and (eq type 'src-block)
  17570. org-src-tab-acts-natively
  17571. (> (line-beginning-position)
  17572. (org-element-property :post-affiliated element))
  17573. (< (line-beginning-position)
  17574. (org-with-point-at (org-element-property :end element)
  17575. (skip-chars-backward " \t\n")
  17576. (line-beginning-position))))
  17577. ;; At the beginning of a blank line, do some preindentation. This
  17578. ;; signals org-src--edit-element to preserve the indentation on exit
  17579. (when (and (looking-at-p "^[[:space:]]*$")
  17580. (not org-src-preserve-indentation))
  17581. (let ((element (org-element-at-point))
  17582. block-content-ind some-ind)
  17583. (org-with-point-at (org-element-property :begin element)
  17584. (setq block-content-ind (+ (current-indentation)
  17585. org-edit-src-content-indentation))
  17586. (forward-line)
  17587. (save-match-data (re-search-forward "^[ \t]*\\S-" nil t))
  17588. (backward-char)
  17589. (setq some-ind (if (looking-at-p "#\\+end_src")
  17590. block-content-ind (current-indentation))))
  17591. (indent-line-to (min block-content-ind some-ind))))
  17592. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  17593. (t
  17594. (let ((column (org--get-expected-indentation element nil)))
  17595. ;; Preserve current column.
  17596. (if (<= (current-column) (current-indentation))
  17597. (indent-line-to column)
  17598. (save-excursion (indent-line-to column))))
  17599. ;; Align node property. Also preserve current column.
  17600. (when (eq type 'node-property)
  17601. (let ((column (current-column)))
  17602. (org--align-node-property)
  17603. (org-move-to-column column))))))))
  17604. (defun org-indent-region (start end)
  17605. "Indent each non-blank line in the region.
  17606. Called from a program, START and END specify the region to
  17607. indent. The function will not indent contents of example blocks,
  17608. verse blocks and export blocks as leading white spaces are
  17609. assumed to be significant there."
  17610. (interactive "r")
  17611. (save-excursion
  17612. (goto-char start)
  17613. (skip-chars-forward " \r\t\n")
  17614. (unless (eobp) (beginning-of-line))
  17615. (let ((indent-to
  17616. (lambda (ind pos)
  17617. ;; Set IND as indentation for all lines between point and
  17618. ;; POS. Blank lines are ignored. Leave point after POS
  17619. ;; once done.
  17620. (let ((limit (copy-marker pos)))
  17621. (while (< (point) limit)
  17622. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  17623. (forward-line))
  17624. (set-marker limit nil))))
  17625. (end (copy-marker end)))
  17626. (while (< (point) end)
  17627. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  17628. (let* ((element (org-element-at-point))
  17629. (type (org-element-type element))
  17630. (element-end (copy-marker (org-element-property :end element)))
  17631. (ind (org--get-expected-indentation element nil)))
  17632. (cond
  17633. ;; Element indented as a single block. Example blocks
  17634. ;; preserving indentation are a special case since the
  17635. ;; "contents" must not be indented whereas the block
  17636. ;; boundaries can.
  17637. ((or (memq type '(export-block latex-environment))
  17638. (and (eq type 'example-block)
  17639. (not
  17640. (or org-src-preserve-indentation
  17641. (org-element-property :preserve-indent element)))))
  17642. (let ((offset (- ind (current-indentation))))
  17643. (unless (zerop offset)
  17644. (indent-rigidly (org-element-property :begin element)
  17645. (org-element-property :end element)
  17646. offset)))
  17647. (goto-char element-end))
  17648. ;; Elements indented line wise. Be sure to exclude
  17649. ;; example blocks (preserving indentation) and source
  17650. ;; blocks from this category as they are treated
  17651. ;; specially later.
  17652. ((or (memq type '(paragraph table table-row))
  17653. (not (or (org-element-property :contents-begin element)
  17654. (memq type '(example-block src-block)))))
  17655. (when (eq type 'node-property)
  17656. (org--align-node-property)
  17657. (beginning-of-line))
  17658. (funcall indent-to ind (min element-end end)))
  17659. ;; Elements consisting of three parts: before the
  17660. ;; contents, the contents, and after the contents. The
  17661. ;; contents are treated specially, according to the
  17662. ;; element type, or not indented at all. Other parts are
  17663. ;; indented as a single block.
  17664. (t
  17665. (let* ((post (copy-marker
  17666. (org-element-property :post-affiliated element)))
  17667. (cbeg
  17668. (copy-marker
  17669. (cond
  17670. ((not (org-element-property :contents-begin element))
  17671. ;; Fake contents for source blocks.
  17672. (org-with-wide-buffer
  17673. (goto-char post)
  17674. (line-beginning-position 2)))
  17675. ((memq type '(footnote-definition item plain-list))
  17676. ;; Contents in these elements could start on
  17677. ;; the same line as the beginning of the
  17678. ;; element. Make sure we start indenting
  17679. ;; from the second line.
  17680. (org-with-wide-buffer
  17681. (goto-char post)
  17682. (end-of-line)
  17683. (skip-chars-forward " \r\t\n")
  17684. (if (eobp) (point) (line-beginning-position))))
  17685. (t (org-element-property :contents-begin element)))))
  17686. (cend (copy-marker
  17687. (or (org-element-property :contents-end element)
  17688. ;; Fake contents for source blocks.
  17689. (org-with-wide-buffer
  17690. (goto-char element-end)
  17691. (skip-chars-backward " \r\t\n")
  17692. (line-beginning-position)))
  17693. t)))
  17694. ;; Do not change items indentation individually as it
  17695. ;; might break the list as a whole. On the other
  17696. ;; hand, when at a plain list, indent it as a whole.
  17697. (cond ((eq type 'plain-list)
  17698. (let ((offset (- ind (current-indentation))))
  17699. (unless (zerop offset)
  17700. (indent-rigidly (org-element-property :begin element)
  17701. (org-element-property :end element)
  17702. offset))
  17703. (goto-char cbeg)))
  17704. ((eq type 'item) (goto-char cbeg))
  17705. (t (funcall indent-to ind (min cbeg end))))
  17706. (when (< (point) end)
  17707. (cl-case type
  17708. ((example-block verse-block))
  17709. (src-block
  17710. ;; In a source block, indent source code
  17711. ;; according to language major mode, but only if
  17712. ;; `org-src-tab-acts-natively' is non-nil.
  17713. (when (and (< (point) end) org-src-tab-acts-natively)
  17714. (ignore-errors
  17715. (org-babel-do-in-edit-buffer
  17716. (indent-region (point-min) (point-max))))))
  17717. (t (org-indent-region (point) (min cend end))))
  17718. (goto-char (min cend end))
  17719. (when (< (point) end)
  17720. (funcall indent-to ind (min element-end end))))
  17721. (set-marker post nil)
  17722. (set-marker cbeg nil)
  17723. (set-marker cend nil))))
  17724. (set-marker element-end nil))))
  17725. (set-marker end nil))))
  17726. (defun org-indent-drawer ()
  17727. "Indent the drawer at point."
  17728. (interactive)
  17729. (unless (save-excursion
  17730. (beginning-of-line)
  17731. (looking-at-p org-drawer-regexp))
  17732. (user-error "Not at a drawer"))
  17733. (let ((element (org-element-at-point)))
  17734. (unless (memq (org-element-type element) '(drawer property-drawer))
  17735. (user-error "Not at a drawer"))
  17736. (org-with-wide-buffer
  17737. (org-indent-region (org-element-property :begin element)
  17738. (org-element-property :end element))))
  17739. (message "Drawer at point indented"))
  17740. (defun org-indent-block ()
  17741. "Indent the block at point."
  17742. (interactive)
  17743. (unless (save-excursion
  17744. (beginning-of-line)
  17745. (let ((case-fold-search t))
  17746. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  17747. (user-error "Not at a block"))
  17748. (let ((element (org-element-at-point)))
  17749. (unless (memq (org-element-type element)
  17750. '(comment-block center-block dynamic-block example-block
  17751. export-block quote-block special-block
  17752. src-block verse-block))
  17753. (user-error "Not at a block"))
  17754. (org-with-wide-buffer
  17755. (org-indent-region (org-element-property :begin element)
  17756. (org-element-property :end element))))
  17757. (message "Block at point indented"))
  17758. ;;; Filling
  17759. ;; We use our own fill-paragraph and auto-fill functions.
  17760. ;; `org-fill-paragraph' relies on adaptive filling and context
  17761. ;; checking. Appropriate `fill-prefix' is computed with
  17762. ;; `org-adaptive-fill-function'.
  17763. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  17764. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  17765. ;; `org-adaptive-fill-function' value. Internally,
  17766. ;; `org-comment-line-break-function' breaks the line.
  17767. ;; `org-setup-filling' installs filling and auto-filling related
  17768. ;; variables during `org-mode' initialization.
  17769. (defun org-setup-filling ()
  17770. (require 'org-element)
  17771. ;; Prevent auto-fill from inserting unwanted new items.
  17772. (when (boundp 'fill-nobreak-predicate)
  17773. (setq-local
  17774. fill-nobreak-predicate
  17775. (org-uniquify
  17776. (append fill-nobreak-predicate
  17777. '(org-fill-line-break-nobreak-p
  17778. org-fill-n-macro-as-item-nobreak-p
  17779. org-fill-paragraph-with-timestamp-nobreak-p)))))
  17780. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  17781. (setq-local paragraph-start paragraph-ending)
  17782. (setq-local paragraph-separate paragraph-ending))
  17783. (setq-local fill-paragraph-function 'org-fill-paragraph)
  17784. (setq-local auto-fill-inhibit-regexp nil)
  17785. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  17786. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  17787. (setq-local comment-line-break-function 'org-comment-line-break-function))
  17788. (defun org-fill-line-break-nobreak-p ()
  17789. "Non-nil when a new line at point would create an Org line break."
  17790. (save-excursion
  17791. (skip-chars-backward " \t")
  17792. (skip-chars-backward "\\\\")
  17793. (looking-at "\\\\\\\\\\($\\|[^\\]\\)")))
  17794. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  17795. "Non-nil when a new line at point would split a timestamp."
  17796. (and (org-at-timestamp-p 'lax)
  17797. (not (looking-at org-ts-regexp-both))))
  17798. (defun org-fill-n-macro-as-item-nobreak-p ()
  17799. "Non-nil when a new line at point would create a new list."
  17800. ;; During export, a "n" macro followed by a dot or a closing
  17801. ;; parenthesis can end up being parsed as a new list item.
  17802. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  17803. (defun org-adaptive-fill-function ()
  17804. "Compute a fill prefix for the current line.
  17805. Return fill prefix, as a string, or nil if current line isn't
  17806. meant to be filled. For convenience, if `adaptive-fill-regexp'
  17807. matches in paragraphs or comments, use it."
  17808. (org-with-wide-buffer
  17809. (unless (org-at-heading-p)
  17810. (let* ((p (line-beginning-position))
  17811. (element (save-excursion
  17812. (beginning-of-line)
  17813. (org-element-at-point)))
  17814. (type (org-element-type element))
  17815. (post-affiliated (org-element-property :post-affiliated element)))
  17816. (unless (< p post-affiliated)
  17817. (cl-case type
  17818. (comment
  17819. (save-excursion
  17820. (beginning-of-line)
  17821. (looking-at "[ \t]*")
  17822. (concat (match-string 0) "# ")))
  17823. (footnote-definition "")
  17824. ((item plain-list)
  17825. (make-string (org-list-item-body-column post-affiliated) ?\s))
  17826. (paragraph
  17827. ;; Fill prefix is usually the same as the current line,
  17828. ;; unless the paragraph is at the beginning of an item.
  17829. (let ((parent (org-element-property :parent element)))
  17830. (save-excursion
  17831. (beginning-of-line)
  17832. (cond ((eq (org-element-type parent) 'item)
  17833. (make-string (org-list-item-body-column
  17834. (org-element-property :begin parent))
  17835. ?\s))
  17836. ((and adaptive-fill-regexp
  17837. ;; Locally disable
  17838. ;; `adaptive-fill-function' to let
  17839. ;; `fill-context-prefix' handle
  17840. ;; `adaptive-fill-regexp' variable.
  17841. (let (adaptive-fill-function)
  17842. (fill-context-prefix
  17843. post-affiliated
  17844. (org-element-property :end element)))))
  17845. ((looking-at "[ \t]+") (match-string 0))
  17846. (t "")))))
  17847. (comment-block
  17848. ;; Only fill contents if P is within block boundaries.
  17849. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  17850. (forward-line)
  17851. (point)))
  17852. (cend (save-excursion
  17853. (goto-char (org-element-property :end element))
  17854. (skip-chars-backward " \r\t\n")
  17855. (line-beginning-position))))
  17856. (when (and (>= p cbeg) (< p cend))
  17857. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  17858. (match-string 0)
  17859. ""))))))))))
  17860. (defun org-fill-element (&optional justify)
  17861. "Fill element at point, when applicable.
  17862. This function only applies to comment blocks, comments, example
  17863. blocks and paragraphs. Also, as a special case, re-align table
  17864. when point is at one.
  17865. If JUSTIFY is non-nil (interactively, with prefix argument),
  17866. justify as well. If `sentence-end-double-space' is non-nil, then
  17867. period followed by one space does not end a sentence, so don't
  17868. break a line there. The variable `fill-column' controls the
  17869. width for filling.
  17870. For convenience, when point is at a plain list, an item or
  17871. a footnote definition, try to fill the first paragraph within."
  17872. (with-syntax-table org-mode-transpose-word-syntax-table
  17873. ;; Move to end of line in order to get the first paragraph within
  17874. ;; a plain list or a footnote definition.
  17875. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  17876. ;; First check if point is in a blank line at the beginning of
  17877. ;; the buffer. In that case, ignore filling.
  17878. (cl-case (org-element-type element)
  17879. ;; Use major mode filling function is source blocks.
  17880. (src-block (org-babel-do-in-edit-buffer
  17881. (push-mark (point-min))
  17882. (goto-char (point-max))
  17883. (setq mark-active t)
  17884. (funcall-interactively #'fill-paragraph justify 'region)))
  17885. ;; Align Org tables, leave table.el tables as-is.
  17886. (table-row (org-table-align) t)
  17887. (table
  17888. (when (eq (org-element-property :type element) 'org)
  17889. (save-excursion
  17890. (goto-char (org-element-property :post-affiliated element))
  17891. (org-table-align)))
  17892. t)
  17893. (paragraph
  17894. ;; Paragraphs may contain `line-break' type objects.
  17895. (let ((beg (max (point-min)
  17896. (org-element-property :contents-begin element)))
  17897. (end (min (point-max)
  17898. (org-element-property :contents-end element))))
  17899. ;; Do nothing if point is at an affiliated keyword.
  17900. (if (< (line-end-position) beg) t
  17901. ;; Fill paragraph, taking line breaks into account.
  17902. (save-excursion
  17903. (goto-char beg)
  17904. (let ((cuts (list beg)))
  17905. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  17906. (when (eq 'line-break
  17907. (org-element-type
  17908. (save-excursion (backward-char)
  17909. (org-element-context))))
  17910. (push (point) cuts)))
  17911. (dolist (c (delq end cuts))
  17912. (fill-region-as-paragraph c end justify)
  17913. (setq end c))))
  17914. t)))
  17915. ;; Contents of `comment-block' type elements should be
  17916. ;; filled as plain text, but only if point is within block
  17917. ;; markers.
  17918. (comment-block
  17919. (let* ((case-fold-search t)
  17920. (beg (save-excursion
  17921. (goto-char (org-element-property :begin element))
  17922. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  17923. (forward-line)
  17924. (point)))
  17925. (end (save-excursion
  17926. (goto-char (org-element-property :end element))
  17927. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  17928. (line-beginning-position))))
  17929. (if (or (< (point) beg) (> (point) end)) t
  17930. (fill-region-as-paragraph
  17931. (save-excursion (end-of-line)
  17932. (re-search-backward "^[ \t]*$" beg 'move)
  17933. (line-beginning-position))
  17934. (save-excursion (beginning-of-line)
  17935. (re-search-forward "^[ \t]*$" end 'move)
  17936. (line-beginning-position))
  17937. justify))))
  17938. ;; Fill comments.
  17939. (comment
  17940. (let ((begin (org-element-property :post-affiliated element))
  17941. (end (org-element-property :end element)))
  17942. (when (and (>= (point) begin) (<= (point) end))
  17943. (let ((begin (save-excursion
  17944. (end-of-line)
  17945. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  17946. (progn (forward-line) (point))
  17947. begin)))
  17948. (end (save-excursion
  17949. (end-of-line)
  17950. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  17951. (1- (line-beginning-position))
  17952. (skip-chars-backward " \r\t\n")
  17953. (line-end-position)))))
  17954. ;; Do not fill comments when at a blank line.
  17955. (when (> end begin)
  17956. (let ((fill-prefix
  17957. (save-excursion
  17958. (beginning-of-line)
  17959. (looking-at "[ \t]*#")
  17960. (let ((comment-prefix (match-string 0)))
  17961. (goto-char (match-end 0))
  17962. (if (looking-at adaptive-fill-regexp)
  17963. (concat comment-prefix (match-string 0))
  17964. (concat comment-prefix " "))))))
  17965. (save-excursion
  17966. (fill-region-as-paragraph begin end justify))))))
  17967. t))
  17968. ;; Ignore every other element.
  17969. (otherwise t)))))
  17970. (defun org-fill-paragraph (&optional justify region)
  17971. "Fill element at point, when applicable.
  17972. This function only applies to comment blocks, comments, example
  17973. blocks and paragraphs. Also, as a special case, re-align table
  17974. when point is at one.
  17975. For convenience, when point is at a plain list, an item or
  17976. a footnote definition, try to fill the first paragraph within.
  17977. If JUSTIFY is non-nil (interactively, with prefix argument),
  17978. justify as well. If `sentence-end-double-space' is non-nil, then
  17979. period followed by one space does not end a sentence, so don't
  17980. break a line there. The variable `fill-column' controls the
  17981. width for filling.
  17982. The REGION argument is non-nil if called interactively; in that
  17983. case, if Transient Mark mode is enabled and the mark is active,
  17984. fill each of the elements in the active region, instead of just
  17985. filling the current element."
  17986. (interactive (progn
  17987. (barf-if-buffer-read-only)
  17988. (list (when current-prefix-arg 'full) t)))
  17989. (let ((hash (and (not (buffer-modified-p))
  17990. (org-buffer-hash))))
  17991. (cond
  17992. ((and region transient-mark-mode mark-active
  17993. (not (eq (region-beginning) (region-end))))
  17994. (let ((origin (point-marker))
  17995. (start (region-beginning)))
  17996. (unwind-protect
  17997. (progn
  17998. (goto-char (region-end))
  17999. (skip-chars-backward " \t\n")
  18000. (while (> (point) start)
  18001. (org-fill-element justify)
  18002. (org-backward-paragraph)))
  18003. (goto-char origin)
  18004. (set-marker origin nil))))
  18005. (t
  18006. (save-excursion
  18007. (when (org-match-line "[ \t]*$")
  18008. (skip-chars-forward " \t\n"))
  18009. (org-fill-element justify))))
  18010. ;; If we didn't change anything in the buffer (and the buffer was
  18011. ;; previously unmodified), then flip the modification status back
  18012. ;; to "unchanged".
  18013. (when (and hash (equal hash (org-buffer-hash)))
  18014. (set-buffer-modified-p nil))
  18015. ;; Return non-nil.
  18016. t))
  18017. (defun org-auto-fill-function ()
  18018. "Auto-fill function."
  18019. ;; Check if auto-filling is meaningful.
  18020. (let ((fc (current-fill-column)))
  18021. (when (and fc (> (current-column) fc))
  18022. (let* ((fill-prefix (org-adaptive-fill-function))
  18023. ;; Enforce empty fill prefix, if required. Otherwise, it
  18024. ;; will be computed again.
  18025. (adaptive-fill-mode (not (equal fill-prefix ""))))
  18026. (when fill-prefix (do-auto-fill))))))
  18027. (defun org-comment-line-break-function (&optional soft)
  18028. "Break line at point and indent, continuing comment if within one.
  18029. The inserted newline is marked hard if variable
  18030. `use-hard-newlines' is true, unless optional argument SOFT is
  18031. non-nil."
  18032. (if soft (insert-and-inherit ?\n) (newline 1))
  18033. (save-excursion (forward-char -1) (delete-horizontal-space))
  18034. (delete-horizontal-space)
  18035. (indent-to-left-margin)
  18036. (insert-before-markers-and-inherit fill-prefix))
  18037. ;;; Fixed Width Areas
  18038. (defun org-toggle-fixed-width ()
  18039. "Toggle fixed-width markup.
  18040. Add or remove fixed-width markup on current line, whenever it
  18041. makes sense. Return an error otherwise.
  18042. If a region is active and if it contains only fixed-width areas
  18043. or blank lines, remove all fixed-width markup in it. If the
  18044. region contains anything else, convert all non-fixed-width lines
  18045. to fixed-width ones.
  18046. Blank lines at the end of the region are ignored unless the
  18047. region only contains such lines."
  18048. (interactive)
  18049. (if (not (org-region-active-p))
  18050. ;; No region:
  18051. ;;
  18052. ;; Remove fixed width marker only in a fixed-with element.
  18053. ;;
  18054. ;; Add fixed width maker in paragraphs, in blank lines after
  18055. ;; elements or at the beginning of a headline or an inlinetask,
  18056. ;; and before any one-line elements (e.g., a clock).
  18057. (progn
  18058. (beginning-of-line)
  18059. (let* ((element (org-element-at-point))
  18060. (type (org-element-type element)))
  18061. (cond
  18062. ((and (eq type 'fixed-width)
  18063. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  18064. (replace-match
  18065. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  18066. ((and (memq type '(babel-call clock comment diary-sexp headline
  18067. horizontal-rule keyword paragraph
  18068. planning))
  18069. (<= (org-element-property :post-affiliated element) (point)))
  18070. (skip-chars-forward " \t")
  18071. (insert ": "))
  18072. ((and (looking-at-p "[ \t]*$")
  18073. (or (eq type 'inlinetask)
  18074. (save-excursion
  18075. (skip-chars-forward " \r\t\n")
  18076. (<= (org-element-property :end element) (point)))))
  18077. (delete-region (point) (line-end-position))
  18078. (org-indent-line)
  18079. (insert ": "))
  18080. (t (user-error "Cannot insert a fixed-width line here")))))
  18081. ;; Region active.
  18082. (let* ((begin (save-excursion
  18083. (goto-char (region-beginning))
  18084. (line-beginning-position)))
  18085. (end (copy-marker
  18086. (save-excursion
  18087. (goto-char (region-end))
  18088. (unless (eolp) (beginning-of-line))
  18089. (if (save-excursion (re-search-backward "\\S-" begin t))
  18090. (progn (skip-chars-backward " \r\t\n") (point))
  18091. (point)))))
  18092. (all-fixed-width-p
  18093. (catch 'not-all-p
  18094. (save-excursion
  18095. (goto-char begin)
  18096. (skip-chars-forward " \r\t\n")
  18097. (when (eobp) (throw 'not-all-p nil))
  18098. (while (< (point) end)
  18099. (let ((element (org-element-at-point)))
  18100. (if (eq (org-element-type element) 'fixed-width)
  18101. (goto-char (org-element-property :end element))
  18102. (throw 'not-all-p nil))))
  18103. t))))
  18104. (if all-fixed-width-p
  18105. (save-excursion
  18106. (goto-char begin)
  18107. (while (< (point) end)
  18108. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  18109. (replace-match
  18110. "" nil nil nil
  18111. (if (= (line-end-position) (match-end 0)) 0 1)))
  18112. (forward-line)))
  18113. (let ((min-ind (point-max)))
  18114. ;; Find minimum indentation across all lines.
  18115. (save-excursion
  18116. (goto-char begin)
  18117. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  18118. (setq min-ind 0)
  18119. (catch 'zerop
  18120. (while (< (point) end)
  18121. (unless (looking-at-p "[ \t]*$")
  18122. (let ((ind (current-indentation)))
  18123. (setq min-ind (min min-ind ind))
  18124. (when (zerop ind) (throw 'zerop t))))
  18125. (forward-line)))))
  18126. ;; Loop over all lines and add fixed-width markup everywhere
  18127. ;; but in fixed-width lines.
  18128. (save-excursion
  18129. (goto-char begin)
  18130. (while (< (point) end)
  18131. (cond
  18132. ((org-at-heading-p)
  18133. (insert ": ")
  18134. (forward-line)
  18135. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  18136. (insert ":")
  18137. (forward-line)))
  18138. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  18139. (let* ((element (org-element-at-point))
  18140. (element-end (org-element-property :end element)))
  18141. (if (eq (org-element-type element) 'fixed-width)
  18142. (progn (goto-char element-end)
  18143. (skip-chars-backward " \r\t\n")
  18144. (forward-line))
  18145. (let ((limit (min end element-end)))
  18146. (while (< (point) limit)
  18147. (org-move-to-column min-ind t)
  18148. (insert ": ")
  18149. (forward-line))))))
  18150. (t
  18151. (org-move-to-column min-ind t)
  18152. (insert ": ")
  18153. (forward-line)))))))
  18154. (set-marker end nil))))
  18155. ;;; Blocks
  18156. (defun org-block-map (function &optional start end)
  18157. "Call FUNCTION at the head of all source blocks in the current buffer.
  18158. Optional arguments START and END can be used to limit the range."
  18159. (let ((start (or start (point-min)))
  18160. (end (or end (point-max))))
  18161. (save-excursion
  18162. (goto-char start)
  18163. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  18164. (save-excursion
  18165. (save-match-data
  18166. (goto-char (match-beginning 0))
  18167. (funcall function)))))))
  18168. (defun org-next-block (arg &optional backward block-regexp)
  18169. "Jump to the next block.
  18170. With a prefix argument ARG, jump forward ARG many blocks.
  18171. When BACKWARD is non-nil, jump to the previous block.
  18172. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  18173. Match data is set according to this regexp when the function
  18174. returns.
  18175. Return point at beginning of the opening line of found block.
  18176. Throw an error if no block is found."
  18177. (interactive "p")
  18178. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  18179. (case-fold-search t)
  18180. (search-fn (if backward #'re-search-backward #'re-search-forward))
  18181. (count (or arg 1))
  18182. (origin (point))
  18183. last-element)
  18184. (if backward (beginning-of-line) (end-of-line))
  18185. (while (and (> count 0) (funcall search-fn re nil t))
  18186. (let ((element (save-excursion
  18187. (goto-char (match-beginning 0))
  18188. (save-match-data (org-element-at-point)))))
  18189. (when (and (memq (org-element-type element)
  18190. '(center-block comment-block dynamic-block
  18191. example-block export-block quote-block
  18192. special-block src-block verse-block))
  18193. (<= (match-beginning 0)
  18194. (org-element-property :post-affiliated element)))
  18195. (setq last-element element)
  18196. (cl-decf count))))
  18197. (if (= count 0)
  18198. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  18199. (save-match-data (org-show-context)))
  18200. (goto-char origin)
  18201. (user-error "No %s code blocks" (if backward "previous" "further")))))
  18202. (defun org-previous-block (arg &optional block-regexp)
  18203. "Jump to the previous block.
  18204. With a prefix argument ARG, jump backward ARG many source blocks.
  18205. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  18206. (interactive "p")
  18207. (org-next-block arg t block-regexp))
  18208. ;;; Comments
  18209. ;; Org comments syntax is quite complex. It requires the entire line
  18210. ;; to be just a comment. Also, even with the right syntax at the
  18211. ;; beginning of line, some elements (e.g., verse-block or
  18212. ;; example-block) don't accept comments. Usual Emacs comment commands
  18213. ;; cannot cope with those requirements. Therefore, Org replaces them.
  18214. ;; Org still relies on 'comment-dwim', but cannot trust
  18215. ;; 'comment-only-p'. So, 'comment-region-function' and
  18216. ;; 'uncomment-region-function' both point
  18217. ;; to 'org-comment-or-uncomment-region'. Eventually,
  18218. ;; 'org-insert-comment' takes care of insertion of comments at the
  18219. ;; beginning of line.
  18220. ;; 'org-setup-comments-handling' install comments related variables
  18221. ;; during 'org-mode' initialization.
  18222. (defun org-setup-comments-handling ()
  18223. (interactive)
  18224. (setq-local comment-use-syntax nil)
  18225. (setq-local comment-start "# ")
  18226. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  18227. (setq-local comment-insert-comment-function 'org-insert-comment)
  18228. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  18229. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  18230. (defun org-insert-comment ()
  18231. "Insert an empty comment above current line.
  18232. If the line is empty, insert comment at its beginning. When
  18233. point is within a source block, comment according to the related
  18234. major mode."
  18235. (if (let ((element (org-element-at-point)))
  18236. (and (eq (org-element-type element) 'src-block)
  18237. (< (save-excursion
  18238. (goto-char (org-element-property :post-affiliated element))
  18239. (line-end-position))
  18240. (point))
  18241. (> (save-excursion
  18242. (goto-char (org-element-property :end element))
  18243. (skip-chars-backward " \r\t\n")
  18244. (line-beginning-position))
  18245. (point))))
  18246. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  18247. (beginning-of-line)
  18248. (if (looking-at "\\s-*$") (delete-region (point) (line-end-position))
  18249. (open-line 1))
  18250. (org-indent-line)
  18251. (insert "# ")))
  18252. (defvar comment-empty-lines) ; From newcomment.el.
  18253. (defun org-comment-or-uncomment-region (beg end &rest _)
  18254. "Comment or uncomment each non-blank line in the region.
  18255. Uncomment each non-blank line between BEG and END if it only
  18256. contains commented lines. Otherwise, comment them. If region is
  18257. strictly within a source block, use appropriate comment syntax."
  18258. (if (let ((element (org-element-at-point)))
  18259. (and (eq (org-element-type element) 'src-block)
  18260. (< (save-excursion
  18261. (goto-char (org-element-property :post-affiliated element))
  18262. (line-end-position))
  18263. beg)
  18264. (>= (save-excursion
  18265. (goto-char (org-element-property :end element))
  18266. (skip-chars-backward " \r\t\n")
  18267. (line-beginning-position))
  18268. end)))
  18269. ;; Translate region boundaries for the Org buffer to the source
  18270. ;; buffer.
  18271. (let ((offset (- end beg)))
  18272. (save-excursion
  18273. (goto-char beg)
  18274. (org-babel-do-in-edit-buffer
  18275. (comment-or-uncomment-region (point) (+ offset (point))))))
  18276. (save-restriction
  18277. ;; Restrict region
  18278. (narrow-to-region (save-excursion (goto-char beg)
  18279. (skip-chars-forward " \r\t\n" end)
  18280. (line-beginning-position))
  18281. (save-excursion (goto-char end)
  18282. (skip-chars-backward " \r\t\n" beg)
  18283. (line-end-position)))
  18284. (let ((uncommentp
  18285. ;; UNCOMMENTP is non-nil when every non blank line between
  18286. ;; BEG and END is a comment.
  18287. (save-excursion
  18288. (goto-char (point-min))
  18289. (while (and (not (eobp))
  18290. (let ((element (org-element-at-point)))
  18291. (and (eq (org-element-type element) 'comment)
  18292. (goto-char (min (point-max)
  18293. (org-element-property
  18294. :end element)))))))
  18295. (eobp))))
  18296. (if uncommentp
  18297. ;; Only blank lines and comments in region: uncomment it.
  18298. (save-excursion
  18299. (goto-char (point-min))
  18300. (while (not (eobp))
  18301. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  18302. (replace-match "" nil nil nil 1))
  18303. (forward-line)))
  18304. ;; Comment each line in region.
  18305. (let ((min-indent (point-max)))
  18306. ;; First find the minimum indentation across all lines.
  18307. (save-excursion
  18308. (goto-char (point-min))
  18309. (while (and (not (eobp)) (not (zerop min-indent)))
  18310. (unless (looking-at "[ \t]*$")
  18311. (setq min-indent (min min-indent (current-indentation))))
  18312. (forward-line)))
  18313. ;; Then loop over all lines.
  18314. (save-excursion
  18315. (goto-char (point-min))
  18316. (while (not (eobp))
  18317. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  18318. ;; Don't get fooled by invisible text (e.g. link path)
  18319. ;; when moving to column MIN-INDENT.
  18320. (let ((buffer-invisibility-spec nil))
  18321. (org-move-to-column min-indent t))
  18322. (insert comment-start))
  18323. (forward-line)))))))))
  18324. (defun org-comment-dwim (_arg)
  18325. "Call the comment command you mean.
  18326. Call `org-toggle-comment' if on a heading, otherwise call
  18327. `comment-dwim', within a source edit buffer if needed."
  18328. (interactive "*P")
  18329. (cond ((org-at-heading-p)
  18330. (call-interactively #'org-toggle-comment))
  18331. ((org-in-src-block-p)
  18332. (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
  18333. (t (call-interactively #'comment-dwim))))
  18334. ;;; Timestamps API
  18335. ;; This section contains tools to operate on, or create, timestamp
  18336. ;; objects, as returned by, e.g. `org-element-context'.
  18337. (defun org-timestamp-from-string (s)
  18338. "Convert Org timestamp S, as a string, into a timestamp object.
  18339. Return nil if S is not a valid timestamp string."
  18340. (when (org-string-nw-p s)
  18341. (with-temp-buffer
  18342. (save-excursion (insert s))
  18343. (org-element-timestamp-parser))))
  18344. (defun org-timestamp-from-time (time &optional with-time inactive)
  18345. "Convert a time value into a timestamp object.
  18346. TIME is an Emacs internal time representation, as returned, e.g.,
  18347. by `current-time'.
  18348. When optional argument WITH-TIME is non-nil, return a timestamp
  18349. object with a time part, i.e., with hours and minutes.
  18350. Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
  18351. return an active timestamp."
  18352. (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
  18353. (org-element-create 'timestamp
  18354. (list :type (if inactive 'inactive 'active)
  18355. :year-start year
  18356. :month-start month
  18357. :day-start day
  18358. :hour-start (and with-time hour)
  18359. :minute-start (and with-time minute)))))
  18360. (defun org-timestamp-to-time (timestamp &optional end)
  18361. "Convert TIMESTAMP object into an Emacs internal time value.
  18362. Use end of date range or time range when END is non-nil.
  18363. Otherwise, use its start."
  18364. (apply #'encode-time 0
  18365. (mapcar
  18366. (lambda (prop) (or (org-element-property prop timestamp) 0))
  18367. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  18368. '(:minute-start :hour-start :day-start :month-start
  18369. :year-start)))))
  18370. (defun org-timestamp-has-time-p (timestamp)
  18371. "Non-nil when TIMESTAMP has a time specified."
  18372. (org-element-property :hour-start timestamp))
  18373. (defun org-timestamp-format (timestamp format &optional end utc)
  18374. "Format a TIMESTAMP object into a string.
  18375. FORMAT is a format specifier to be passed to
  18376. `format-time-string'.
  18377. When optional argument END is non-nil, use end of date-range or
  18378. time-range, if possible.
  18379. When optional argument UTC is non-nil, time is be expressed as
  18380. Universal Time."
  18381. (format-time-string format (org-timestamp-to-time timestamp end)
  18382. (and utc t)))
  18383. (defun org-timestamp-split-range (timestamp &optional end)
  18384. "Extract a TIMESTAMP object from a date or time range.
  18385. END, when non-nil, means extract the end of the range.
  18386. Otherwise, extract its start.
  18387. Return a new timestamp object."
  18388. (let ((type (org-element-property :type timestamp)))
  18389. (if (memq type '(active inactive diary)) timestamp
  18390. (let ((split-ts (org-element-copy timestamp)))
  18391. ;; Set new type.
  18392. (org-element-put-property
  18393. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  18394. ;; Copy start properties over end properties if END is
  18395. ;; non-nil. Otherwise, copy end properties over `start' ones.
  18396. (let ((p-alist '((:minute-start . :minute-end)
  18397. (:hour-start . :hour-end)
  18398. (:day-start . :day-end)
  18399. (:month-start . :month-end)
  18400. (:year-start . :year-end))))
  18401. (dolist (p-cell p-alist)
  18402. (org-element-put-property
  18403. split-ts
  18404. (funcall (if end #'car #'cdr) p-cell)
  18405. (org-element-property
  18406. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  18407. ;; Eventually refresh `:raw-value'.
  18408. (org-element-put-property split-ts :raw-value nil)
  18409. (org-element-put-property
  18410. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  18411. (defun org-timestamp-translate (timestamp &optional boundary)
  18412. "Translate TIMESTAMP object to custom format.
  18413. Format string is defined in `org-time-stamp-custom-formats',
  18414. which see.
  18415. When optional argument BOUNDARY is non-nil, it is either the
  18416. symbol `start' or `end'. In this case, only translate the
  18417. starting or ending part of TIMESTAMP if it is a date or time
  18418. range. Otherwise, translate both parts.
  18419. Return timestamp as-is if `org-display-custom-times' is nil or if
  18420. it has a `diary' type."
  18421. (let ((type (org-element-property :type timestamp)))
  18422. (if (or (not org-display-custom-times) (eq type 'diary))
  18423. (org-element-interpret-data timestamp)
  18424. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  18425. org-time-stamp-custom-formats)))
  18426. (if (and (not boundary) (memq type '(active-range inactive-range)))
  18427. (concat (org-timestamp-format timestamp fmt)
  18428. "--"
  18429. (org-timestamp-format timestamp fmt t))
  18430. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  18431. ;;; Other stuff
  18432. (defvar reftex-docstruct-symbol)
  18433. (defvar org--rds)
  18434. (defun org-reftex-citation ()
  18435. "Use `reftex-citation' to insert a citation into the buffer.
  18436. This looks for a line like
  18437. #+BIBLIOGRAPHY: foo plain option:-d
  18438. and derives from it that foo.bib is the bibliography file relevant
  18439. for this document. It then installs the necessary environment for RefTeX
  18440. to work in this buffer and calls `reftex-citation' to insert a citation
  18441. into the buffer.
  18442. Export of such citations to both LaTeX and HTML is handled by the contributed
  18443. package ox-bibtex by Taru Karttunen."
  18444. (interactive)
  18445. (let ((reftex-docstruct-symbol 'org--rds)
  18446. org--rds bib)
  18447. (org-with-wide-buffer
  18448. (let ((case-fold-search t)
  18449. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  18450. (if (not (save-excursion
  18451. (or (re-search-forward re nil t)
  18452. (re-search-backward re nil t))))
  18453. (user-error "No bibliography defined in file")
  18454. (setq bib (concat (match-string 1) ".bib")
  18455. org--rds (list (list 'bib bib))))))
  18456. (call-interactively 'reftex-citation)))
  18457. ;;;; Functions extending outline functionality
  18458. (defun org-beginning-of-line (&optional n)
  18459. "Go to the beginning of the current visible line.
  18460. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18461. symbol `reversed', on the first attempt move to where the
  18462. headline text starts, and only move to beginning of line when the
  18463. cursor is already before the start of the text of the headline.
  18464. If `org-special-ctrl-a/e' is symbol `reversed' then go to the
  18465. start of the text on the second attempt.
  18466. With argument N not nil or 1, move forward N - 1 lines first."
  18467. (interactive "^p")
  18468. (let ((origin (point))
  18469. (special (pcase org-special-ctrl-a/e
  18470. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  18471. deactivate-mark)
  18472. ;; First move to a visible line.
  18473. (if (bound-and-true-p visual-line-mode)
  18474. (beginning-of-visual-line n)
  18475. (move-beginning-of-line n)
  18476. ;; `move-beginning-of-line' may leave point after invisible
  18477. ;; characters if line starts with such of these (e.g., with
  18478. ;; a link at column 0). Really move to the beginning of the
  18479. ;; current visible line.
  18480. (beginning-of-line))
  18481. (cond
  18482. ;; No special behavior. Point is already at the beginning of
  18483. ;; a line, logical or visual.
  18484. ((not special))
  18485. ;; `beginning-of-visual-line' left point before logical beginning
  18486. ;; of line: point is at the beginning of a visual line. Bail
  18487. ;; out.
  18488. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  18489. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  18490. ;; At a headline, special position is before the title, but
  18491. ;; after any TODO keyword or priority cookie.
  18492. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  18493. (line-end-position)))
  18494. (bol (point)))
  18495. (if (eq special 'reversed)
  18496. (when (and (= origin bol) (eq last-command this-command))
  18497. (goto-char refpos))
  18498. (when (or (> origin refpos) (= origin bol))
  18499. (goto-char refpos)))))
  18500. ((and (looking-at org-list-full-item-re)
  18501. (memq (org-element-type (save-match-data (org-element-at-point)))
  18502. '(item plain-list)))
  18503. ;; Set special position at first white space character after
  18504. ;; bullet, and check-box, if any.
  18505. (let ((after-bullet
  18506. (let ((box (match-end 3)))
  18507. (cond ((not box) (match-end 1))
  18508. ((eq (char-after box) ?\s) (1+ box))
  18509. (t box)))))
  18510. (if (eq special 'reversed)
  18511. (when (and (= (point) origin) (eq last-command this-command))
  18512. (goto-char after-bullet))
  18513. (when (or (> origin after-bullet) (= (point) origin))
  18514. (goto-char after-bullet)))))
  18515. ;; No special context. Point is already at beginning of line.
  18516. (t nil))))
  18517. (defun org-end-of-line (&optional n)
  18518. "Go to the end of the line, but before ellipsis, if any.
  18519. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18520. symbol `reversed', ignore tags on the first attempt, and only
  18521. move to after the tags when the cursor is already beyond the end
  18522. of the headline.
  18523. If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
  18524. on the second attempt.
  18525. With argument N not nil or 1, move forward N - 1 lines first."
  18526. (interactive "^p")
  18527. (let ((origin (point))
  18528. (special (pcase org-special-ctrl-a/e
  18529. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  18530. deactivate-mark)
  18531. ;; First move to a visible line.
  18532. (if (bound-and-true-p visual-line-mode)
  18533. (beginning-of-visual-line n)
  18534. (move-beginning-of-line n))
  18535. (cond
  18536. ;; At a headline, with tags.
  18537. ((and special
  18538. (save-excursion
  18539. (beginning-of-line)
  18540. (let ((case-fold-search nil))
  18541. (looking-at org-complex-heading-regexp)))
  18542. (match-end 5))
  18543. (let ((tags (save-excursion
  18544. (goto-char (match-beginning 5))
  18545. (skip-chars-backward " \t")
  18546. (point)))
  18547. (visual-end (and (bound-and-true-p visual-line-mode)
  18548. (save-excursion
  18549. (end-of-visual-line)
  18550. (point)))))
  18551. ;; If `end-of-visual-line' brings us before end of line or
  18552. ;; even tags, i.e., the headline spans over multiple visual
  18553. ;; lines, move there.
  18554. (cond ((and visual-end
  18555. (< visual-end tags)
  18556. (<= origin visual-end))
  18557. (goto-char visual-end))
  18558. ((eq special 'reversed)
  18559. (if (and (= origin (line-end-position))
  18560. (eq this-command last-command))
  18561. (goto-char tags)
  18562. (end-of-line)))
  18563. (t
  18564. (if (or (< origin tags) (= origin (line-end-position)))
  18565. (goto-char tags)
  18566. (end-of-line))))))
  18567. ((bound-and-true-p visual-line-mode)
  18568. (let ((bol (line-beginning-position)))
  18569. (end-of-visual-line)
  18570. ;; If `end-of-visual-line' gets us past the ellipsis at the
  18571. ;; end of a line, backtrack and use `end-of-line' instead.
  18572. (when (/= bol (line-beginning-position))
  18573. (goto-char bol)
  18574. (end-of-line))))
  18575. (t (end-of-line)))))
  18576. (defun org-backward-sentence (&optional _arg)
  18577. "Go to beginning of sentence, or beginning of table field.
  18578. This will call `backward-sentence' or `org-table-beginning-of-field',
  18579. depending on context."
  18580. (interactive)
  18581. (let* ((element (org-element-at-point))
  18582. (contents-begin (org-element-property :contents-begin element))
  18583. (table (org-element-lineage element '(table) t)))
  18584. (if (and table
  18585. (> (point) contents-begin)
  18586. (<= (point) (org-element-property :contents-end table)))
  18587. (call-interactively #'org-table-beginning-of-field)
  18588. (save-restriction
  18589. (when (and contents-begin
  18590. (< (point-min) contents-begin)
  18591. (> (point) contents-begin))
  18592. (narrow-to-region contents-begin
  18593. (org-element-property :contents-end element)))
  18594. (call-interactively #'backward-sentence)))))
  18595. (defun org-forward-sentence (&optional _arg)
  18596. "Go to end of sentence, or end of table field.
  18597. This will call `forward-sentence' or `org-table-end-of-field',
  18598. depending on context."
  18599. (interactive)
  18600. (if (and (org-at-heading-p)
  18601. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  18602. (save-restriction
  18603. (narrow-to-region (line-beginning-position) (line-end-position))
  18604. (call-interactively #'forward-sentence))
  18605. (let* ((element (org-element-at-point))
  18606. (contents-end (org-element-property :contents-end element))
  18607. (table (org-element-lineage element '(table) t)))
  18608. (if (and table
  18609. (>= (point) (org-element-property :contents-begin table))
  18610. (< (point) contents-end))
  18611. (call-interactively #'org-table-end-of-field)
  18612. (save-restriction
  18613. (when (and contents-end
  18614. (> (point-max) contents-end)
  18615. ;; Skip blank lines between elements.
  18616. (< (org-element-property :end element)
  18617. (save-excursion (goto-char contents-end)
  18618. (skip-chars-forward " \r\t\n"))))
  18619. (narrow-to-region (org-element-property :contents-begin element)
  18620. contents-end))
  18621. ;; End of heading is considered as the end of a sentence.
  18622. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  18623. (call-interactively #'forward-sentence)))))))
  18624. (defun org-kill-line (&optional _arg)
  18625. "Kill line, to tags or end of line."
  18626. (interactive)
  18627. (cond
  18628. ((or (not org-special-ctrl-k)
  18629. (bolp)
  18630. (not (org-at-heading-p)))
  18631. (when (and (get-char-property (line-end-position) 'invisible)
  18632. org-ctrl-k-protect-subtree
  18633. (or (eq org-ctrl-k-protect-subtree 'error)
  18634. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  18635. (user-error
  18636. (substitute-command-keys
  18637. "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
  18638. (call-interactively
  18639. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  18640. ((org-match-line org-tag-line-re)
  18641. (let ((end (save-excursion
  18642. (goto-char (match-beginning 1))
  18643. (skip-chars-backward " \t")
  18644. (point))))
  18645. (if (<= end (point)) ;on tags part
  18646. (kill-region (point) (line-end-position))
  18647. (kill-region (point) end)))
  18648. ;; Only align tags when we are still on a heading:
  18649. (if (org-at-heading-p) (org-align-tags)))
  18650. (t (kill-region (point) (line-end-position)))))
  18651. (defun org-yank (&optional arg)
  18652. "Yank. If the kill is a subtree, treat it specially.
  18653. This command will look at the current kill and check if is a single
  18654. subtree, or a series of subtrees[1]. If it passes the test, and if the
  18655. cursor is at the beginning of a line or after the stars of a currently
  18656. empty headline, then the yank is handled specially. How exactly depends
  18657. on the value of the following variables.
  18658. `org-yank-folded-subtrees'
  18659. By default, this variable is non-nil, which results in
  18660. subtree(s) being folded after insertion, except if doing so
  18661. would swallow text after the yanked text.
  18662. `org-yank-adjusted-subtrees'
  18663. When non-nil (the default value is nil), the subtree will be
  18664. promoted or demoted in order to fit into the local outline tree
  18665. structure, which means that the level will be adjusted so that it
  18666. becomes the smaller one of the two *visible* surrounding headings.
  18667. Any prefix to this command will cause `yank' to be called directly with
  18668. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  18669. will just
  18670. plainly yank the text as it is.
  18671. \[1] The test checks if the first non-white line is a heading
  18672. and if there are no other headings with fewer stars."
  18673. (interactive "P")
  18674. (org-yank-generic 'yank arg))
  18675. (defun org-yank-generic (command arg)
  18676. "Perform some yank-like command.
  18677. This function implements the behavior described in the `org-yank'
  18678. documentation. However, it has been generalized to work for any
  18679. interactive command with similar behavior."
  18680. ;; pretend to be command COMMAND
  18681. (setq this-command command)
  18682. (if arg
  18683. (call-interactively command)
  18684. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  18685. (and (org-kill-is-subtree-p)
  18686. (or (bolp)
  18687. (and (looking-at "[ \t]*$")
  18688. (string-match
  18689. "\\`\\*+\\'"
  18690. (buffer-substring (line-beginning-position) (point)))))))
  18691. swallowp)
  18692. (cond
  18693. ((and subtreep org-yank-folded-subtrees)
  18694. (let ((beg (point))
  18695. end)
  18696. (if (and subtreep org-yank-adjusted-subtrees)
  18697. (org-paste-subtree nil nil 'for-yank)
  18698. (call-interactively command))
  18699. (setq end (point))
  18700. (goto-char beg)
  18701. (when (and (bolp) subtreep
  18702. (not (setq swallowp
  18703. (org-yank-folding-would-swallow-text beg end))))
  18704. (org-with-limited-levels
  18705. (or (looking-at org-outline-regexp)
  18706. (re-search-forward org-outline-regexp-bol end t))
  18707. (while (and (< (point) end) (looking-at org-outline-regexp))
  18708. (org-flag-subtree t)
  18709. (org-cycle-show-empty-lines 'folded)
  18710. (condition-case nil
  18711. (outline-forward-same-level 1)
  18712. (error (goto-char end))))))
  18713. (when swallowp
  18714. (message
  18715. "Inserted text not folded because that would swallow text"))
  18716. (goto-char end)
  18717. (skip-chars-forward " \t\n\r")
  18718. (beginning-of-line 1)
  18719. (push-mark beg 'nomsg)))
  18720. ((and subtreep org-yank-adjusted-subtrees)
  18721. (let ((beg (line-beginning-position)))
  18722. (org-paste-subtree nil nil 'for-yank)
  18723. (push-mark beg 'nomsg)))
  18724. (t
  18725. (call-interactively command))))))
  18726. (defun org-yank-folding-would-swallow-text (beg end)
  18727. "Would `hide-subtree' at BEG swallow any text after END?"
  18728. (let (level)
  18729. (org-with-limited-levels
  18730. (save-excursion
  18731. (goto-char beg)
  18732. (when (or (looking-at org-outline-regexp)
  18733. (re-search-forward org-outline-regexp-bol end t))
  18734. (setq level (org-outline-level)))
  18735. (goto-char end)
  18736. (skip-chars-forward " \t\r\n\v\f")
  18737. (not (or (eobp)
  18738. (and (bolp) (looking-at-p org-outline-regexp)
  18739. (<= (org-outline-level) level))))))))
  18740. (defun org-back-to-heading (&optional invisible-ok)
  18741. "Call `outline-back-to-heading', but provide a better error message."
  18742. (condition-case nil
  18743. (outline-back-to-heading invisible-ok)
  18744. (error
  18745. (user-error "Before first headline at position %d in buffer %s"
  18746. (point) (current-buffer)))))
  18747. (defun org-back-to-heading-or-point-min (&optional invisible-ok)
  18748. "Go back to heading or first point in buffer.
  18749. If point is before first heading go to first point in buffer
  18750. instead of back to heading."
  18751. (condition-case nil
  18752. (outline-back-to-heading invisible-ok)
  18753. (error
  18754. (goto-char (point-min)))))
  18755. (defun org-before-first-heading-p ()
  18756. "Before first heading?"
  18757. (org-with-limited-levels
  18758. (save-excursion
  18759. (end-of-line)
  18760. (null (re-search-backward org-outline-regexp-bol nil t)))))
  18761. (defun org-at-heading-p (&optional _)
  18762. "Non-nil when on a headline."
  18763. (outline-on-heading-p t))
  18764. (defun org-in-commented-heading-p (&optional no-inheritance)
  18765. "Non-nil if point is under a commented heading.
  18766. This function also checks ancestors of the current headline,
  18767. unless optional argument NO-INHERITANCE is non-nil."
  18768. (cond
  18769. ((org-before-first-heading-p) nil)
  18770. ((let ((headline (nth 4 (org-heading-components))))
  18771. (and headline
  18772. (let ((case-fold-search nil))
  18773. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  18774. headline)))))
  18775. (no-inheritance nil)
  18776. (t
  18777. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  18778. (defun org-in-archived-heading-p (&optional no-inheritance)
  18779. "Non-nil if point is under an archived heading.
  18780. This function also checks ancestors of the current headline,
  18781. unless optional argument NO-INHERITANCE is non-nil."
  18782. (cond
  18783. ((org-before-first-heading-p) nil)
  18784. ((let ((tags (org-get-tags nil 'local)))
  18785. (and tags
  18786. (cl-some (apply-partially #'string= org-archive-tag) tags))))
  18787. (no-inheritance nil)
  18788. (t
  18789. (save-excursion (and (org-up-heading-safe) (org-in-archived-heading-p))))))
  18790. (defun org-at-comment-p nil
  18791. "Return t if cursor is in a commented line."
  18792. (save-excursion
  18793. (save-match-data
  18794. (beginning-of-line)
  18795. (looking-at org-comment-regexp))))
  18796. (defun org-at-keyword-p nil
  18797. "Return t if cursor is at a keyword-line."
  18798. (save-excursion
  18799. (move-beginning-of-line 1)
  18800. (looking-at org-keyword-regexp)))
  18801. (defun org-at-drawer-p nil
  18802. "Return t if cursor is at a drawer keyword."
  18803. (save-excursion
  18804. (move-beginning-of-line 1)
  18805. (looking-at org-drawer-regexp)))
  18806. (defun org-at-block-p nil
  18807. "Return t if cursor is at a block keyword."
  18808. (save-excursion
  18809. (move-beginning-of-line 1)
  18810. (looking-at org-block-regexp)))
  18811. (defun org-point-at-end-of-empty-headline ()
  18812. "If point is at the end of an empty headline, return t, else nil.
  18813. If the heading only contains a TODO keyword, it is still considered
  18814. empty."
  18815. (let ((case-fold-search nil))
  18816. (and (looking-at "[ \t]*$")
  18817. org-todo-line-regexp
  18818. (save-excursion
  18819. (beginning-of-line)
  18820. (looking-at org-todo-line-regexp)
  18821. (string= (match-string 3) "")))))
  18822. (defun org-at-heading-or-item-p ()
  18823. (or (org-at-heading-p) (org-at-item-p)))
  18824. (defun org-up-heading-all (arg)
  18825. "Move to the heading line of which the present line is a subheading.
  18826. This function considers both visible and invisible heading lines.
  18827. With argument, move up ARG levels."
  18828. (outline-up-heading arg t))
  18829. (defvar-local org--up-heading-cache nil
  18830. "Buffer-local `org-up-heading-safe' cache.")
  18831. (defvar-local org--up-heading-cache-tick nil
  18832. "Buffer `buffer-chars-modified-tick' in `org--up-heading-cache'.")
  18833. (defun org-up-heading-safe ()
  18834. "Move to the heading line of which the present line is a subheading.
  18835. This version will not throw an error. It will return the level of the
  18836. headline found, or nil if no higher level is found.
  18837. Also, this function will be a lot faster than `outline-up-heading',
  18838. because it relies on stars being the outline starters. This can really
  18839. make a significant difference in outlines with very many siblings."
  18840. (when (ignore-errors (org-back-to-heading t))
  18841. (let (level-cache)
  18842. (unless org--up-heading-cache
  18843. (setq org--up-heading-cache (make-hash-table)))
  18844. (if (and (eq (buffer-chars-modified-tick) org--up-heading-cache-tick)
  18845. (setq level-cache (gethash (point) org--up-heading-cache)))
  18846. (when (<= (point-min) (car level-cache) (point-max))
  18847. ;; Parent is inside accessible part of the buffer.
  18848. (progn (goto-char (car level-cache))
  18849. (cdr level-cache)))
  18850. ;; Buffer modified. Invalidate cache.
  18851. (unless (eq (buffer-chars-modified-tick) org--up-heading-cache-tick)
  18852. (setq-local org--up-heading-cache-tick
  18853. (buffer-chars-modified-tick))
  18854. (clrhash org--up-heading-cache))
  18855. (let* ((level-up (1- (funcall outline-level)))
  18856. (pos (point))
  18857. (result (and (> level-up 0)
  18858. (re-search-backward
  18859. (format "^\\*\\{1,%d\\} " level-up) nil t)
  18860. (funcall outline-level))))
  18861. (when result (puthash pos (cons (point) result) org--up-heading-cache))
  18862. result)))))
  18863. (defun org-up-heading-or-point-min ()
  18864. "Move to the heading line of which the present is a subheading, or point-min.
  18865. This version is needed to make point-min behave like a virtual
  18866. heading of level 0 for property-inheritance. It will return the
  18867. level of the headline found (down to 0) or nil if already at a
  18868. point before the first headline or at point-min."
  18869. (when (ignore-errors (org-back-to-heading t))
  18870. (if (< 1 (funcall outline-level))
  18871. (org-up-heading-safe)
  18872. (unless (= (point) (point-min)) (goto-char (point-min))))))
  18873. (defun org-first-sibling-p ()
  18874. "Is this heading the first child of its parents?"
  18875. (interactive)
  18876. (let ((re org-outline-regexp-bol)
  18877. level l)
  18878. (unless (org-at-heading-p t)
  18879. (user-error "Not at a heading"))
  18880. (setq level (funcall outline-level))
  18881. (save-excursion
  18882. (if (not (re-search-backward re nil t))
  18883. t
  18884. (setq l (funcall outline-level))
  18885. (< l level)))))
  18886. (defun org-goto-sibling (&optional previous)
  18887. "Goto the next sibling, even if it is invisible.
  18888. When PREVIOUS is set, go to the previous sibling instead. Returns t
  18889. when a sibling was found. When none is found, return nil and don't
  18890. move point."
  18891. (let ((fun (if previous 're-search-backward 're-search-forward))
  18892. (pos (point))
  18893. (re org-outline-regexp-bol)
  18894. level l)
  18895. (when (ignore-errors (org-back-to-heading t))
  18896. (setq level (funcall outline-level))
  18897. (catch 'exit
  18898. (or previous (forward-char 1))
  18899. (while (funcall fun re nil t)
  18900. (setq l (funcall outline-level))
  18901. (when (< l level) (goto-char pos) (throw 'exit nil))
  18902. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  18903. (goto-char pos)
  18904. nil))))
  18905. (defun org-show-siblings ()
  18906. "Show all siblings of the current headline."
  18907. (save-excursion
  18908. (while (org-goto-sibling) (org-flag-heading nil)))
  18909. (save-excursion
  18910. (while (org-goto-sibling 'previous)
  18911. (org-flag-heading nil))))
  18912. (defun org-goto-first-child ()
  18913. "Goto the first child, even if it is invisible.
  18914. Return t when a child was found. Otherwise don't move point and
  18915. return nil."
  18916. (let (level (pos (point)) (re org-outline-regexp-bol))
  18917. (when (org-back-to-heading-or-point-min t)
  18918. (setq level (org-outline-level))
  18919. (forward-char 1)
  18920. (if (and (re-search-forward re nil t) (> (org-outline-level) level))
  18921. (progn (goto-char (match-beginning 0)) t)
  18922. (goto-char pos) nil))))
  18923. (defun org-show-hidden-entry ()
  18924. "Show an entry where even the heading is hidden."
  18925. (save-excursion
  18926. (org-show-entry)))
  18927. (defun org-flag-heading (flag &optional entry)
  18928. "Flag the current heading. FLAG non-nil means make invisible.
  18929. When ENTRY is non-nil, show the entire entry."
  18930. (save-excursion
  18931. (org-back-to-heading t)
  18932. ;; Check if we should show the entire entry
  18933. (if (not entry)
  18934. (org-flag-region
  18935. (line-end-position 0) (line-end-position) flag 'outline)
  18936. (org-show-entry)
  18937. (save-excursion
  18938. (and (outline-next-heading)
  18939. (org-flag-heading nil))))))
  18940. (defun org-get-next-sibling ()
  18941. "Move to next heading of the same level, and return point.
  18942. If there is no such heading, return nil.
  18943. This is like outline-next-sibling, but invisible headings are ok."
  18944. (let ((level (funcall outline-level)))
  18945. (outline-next-heading)
  18946. (while (and (not (eobp)) (> (funcall outline-level) level))
  18947. (outline-next-heading))
  18948. (unless (or (eobp) (< (funcall outline-level) level))
  18949. (point))))
  18950. (defun org-get-previous-sibling ()
  18951. "Move to previous heading of the same level, and return point.
  18952. If there is no such heading, return nil."
  18953. (let ((opoint (point))
  18954. (level (funcall outline-level)))
  18955. (outline-previous-heading)
  18956. (when (and (/= (point) opoint) (outline-on-heading-p t))
  18957. (while (and (> (funcall outline-level) level)
  18958. (not (bobp)))
  18959. (outline-previous-heading))
  18960. (unless (< (funcall outline-level) level)
  18961. (point)))))
  18962. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  18963. "Goto to the end of a subtree."
  18964. ;; This contains an exact copy of the original function, but it uses
  18965. ;; `org-back-to-heading-or-point-min', to make it work also in invisible
  18966. ;; trees and before first headline. And is uses an invisible-ok argument.
  18967. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  18968. ;; Furthermore, when used inside Org, finding the end of a large subtree
  18969. ;; with many children and grandchildren etc, this can be much faster
  18970. ;; than the outline version.
  18971. (org-back-to-heading-or-point-min invisible-ok)
  18972. (let ((first t)
  18973. (level (funcall outline-level)))
  18974. (cond ((= level 0)
  18975. (goto-char (point-max)))
  18976. ((and (derived-mode-p 'org-mode) (< level 1000))
  18977. ;; A true heading (not a plain list item), in Org
  18978. ;; This means we can easily find the end by looking
  18979. ;; only for the right number of stars. Using a regexp to do
  18980. ;; this is so much faster than using a Lisp loop.
  18981. (let ((re (concat "^\\*\\{1," (number-to-string level) "\\} ")))
  18982. (forward-char 1)
  18983. (and (re-search-forward re nil 'move) (beginning-of-line 1))))
  18984. (t
  18985. ;; something else, do it the slow way
  18986. (while (and (not (eobp))
  18987. (or first (> (funcall outline-level) level)))
  18988. (setq first nil)
  18989. (outline-next-heading))))
  18990. (unless to-heading
  18991. (when (memq (preceding-char) '(?\n ?\^M))
  18992. ;; Go to end of line before heading
  18993. (forward-char -1)
  18994. (when (memq (preceding-char) '(?\n ?\^M))
  18995. ;; leave blank line before heading
  18996. (forward-char -1)))))
  18997. (point))
  18998. (defun org-end-of-meta-data (&optional full)
  18999. "Skip planning line and properties drawer in current entry.
  19000. When optional argument FULL is t, also skip planning information,
  19001. clocking lines and any kind of drawer.
  19002. When FULL is non-nil but not t, skip planning information,
  19003. properties, clocking lines and logbook drawers."
  19004. (org-back-to-heading t)
  19005. (forward-line)
  19006. ;; Skip planning information.
  19007. (when (looking-at-p org-planning-line-re) (forward-line))
  19008. ;; Skip property drawer.
  19009. (when (looking-at org-property-drawer-re)
  19010. (goto-char (match-end 0))
  19011. (forward-line))
  19012. ;; When FULL is not nil, skip more.
  19013. (when (and full (not (org-at-heading-p)))
  19014. (catch 'exit
  19015. (let ((end (save-excursion (outline-next-heading) (point)))
  19016. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  19017. (while (not (eobp))
  19018. (cond ;; Skip clock lines.
  19019. ((looking-at-p re) (forward-line))
  19020. ;; Skip logbook drawer.
  19021. ((looking-at-p org-logbook-drawer-re)
  19022. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  19023. (forward-line)
  19024. (throw 'exit t)))
  19025. ;; When FULL is t, skip regular drawer too.
  19026. ((and (eq full t) (looking-at-p org-drawer-regexp))
  19027. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  19028. (forward-line)
  19029. (throw 'exit t)))
  19030. (t (throw 'exit t))))))))
  19031. (defun org--line-fully-invisible-p ()
  19032. "Return non-nil if the current line is fully invisible."
  19033. (let ((line-beg (line-beginning-position))
  19034. (line-pos (1- (line-end-position)))
  19035. (is-invisible t))
  19036. (while (and (< line-beg line-pos) is-invisible)
  19037. (setq is-invisible (org-invisible-p line-pos))
  19038. (setq line-pos (1- line-pos)))
  19039. is-invisible))
  19040. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  19041. "Move forward to the ARG'th subheading at same level as this one.
  19042. Stop at the first and last subheadings of a superior heading.
  19043. Normally this only looks at visible headings, but when INVISIBLE-OK is
  19044. non-nil it will also look at invisible ones."
  19045. (interactive "p")
  19046. (let ((backward? (and arg (< arg 0))))
  19047. (if (org-before-first-heading-p)
  19048. (if backward? (goto-char (point-min)) (outline-next-heading))
  19049. (org-back-to-heading invisible-ok)
  19050. (unless backward? (end-of-line)) ;do not match current headline
  19051. (let ((level (- (match-end 0) (match-beginning 0) 1))
  19052. (f (if backward? #'re-search-backward #'re-search-forward))
  19053. (count (if arg (abs arg) 1))
  19054. (result (point)))
  19055. (while (and (> count 0)
  19056. (funcall f org-outline-regexp-bol nil 'move))
  19057. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  19058. (cond ((< l level) (setq count 0))
  19059. ((and (= l level)
  19060. (or invisible-ok
  19061. ;; FIXME: See commit a700fadd72 and the
  19062. ;; related discussion on why using
  19063. ;; `org--line-fully-invisible-p' is needed
  19064. ;; here, which is to serve the needs of an
  19065. ;; external package. If the change is
  19066. ;; wrong regarding Org itself, it should
  19067. ;; be removed.
  19068. (not (org--line-fully-invisible-p))))
  19069. (cl-decf count)
  19070. (when (= l level) (setq result (point)))))))
  19071. (goto-char result))
  19072. (beginning-of-line))))
  19073. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  19074. "Move backward to the ARG'th subheading at same level as this one.
  19075. Stop at the first and last subheadings of a superior heading."
  19076. (interactive "p")
  19077. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  19078. (defun org-next-visible-heading (arg)
  19079. "Move to the next visible heading line.
  19080. With ARG, repeats or can move backward if negative."
  19081. (interactive "p")
  19082. (let ((regexp (concat "^" (org-get-limited-outline-regexp))))
  19083. (if (< arg 0)
  19084. (beginning-of-line)
  19085. (end-of-line))
  19086. (while (and (< arg 0) (re-search-backward regexp nil :move))
  19087. (unless (bobp)
  19088. (while (pcase (get-char-property-and-overlay (point) 'invisible)
  19089. (`(outline . ,o)
  19090. (goto-char (overlay-start o))
  19091. (re-search-backward regexp nil :move))
  19092. (_ nil))))
  19093. (cl-incf arg))
  19094. (while (and (> arg 0) (re-search-forward regexp nil t))
  19095. (while (pcase (get-char-property-and-overlay (point) 'invisible)
  19096. (`(outline . ,o)
  19097. (goto-char (overlay-end o))
  19098. (re-search-forward regexp nil :move))
  19099. (_
  19100. (end-of-line)
  19101. nil))) ;leave the loop
  19102. (cl-decf arg))
  19103. (if (> arg 0) (goto-char (point-max)) (beginning-of-line))))
  19104. (defun org-previous-visible-heading (arg)
  19105. "Move to the previous visible heading.
  19106. With ARG, repeats or can move forward if negative."
  19107. (interactive "p")
  19108. (org-next-visible-heading (- arg)))
  19109. (defun org-forward-paragraph (&optional arg)
  19110. "Move forward by a paragraph, or equivalent, unit.
  19111. With argument ARG, do it ARG times;
  19112. a negative argument ARG = -N means move backward N paragraphs.
  19113. The function moves point between two structural
  19114. elements (paragraphs, tables, lists, etc.).
  19115. It also provides the following special moves for convenience:
  19116. - on a table or a property drawer, move to its beginning;
  19117. - on comment, example, export, source and verse blocks, stop
  19118. at blank lines;
  19119. - skip consecutive clocks, diary S-exps, and keywords."
  19120. (interactive "^p")
  19121. (unless arg (setq arg 1))
  19122. (if (< arg 0) (org-backward-paragraph (- arg))
  19123. (while (and (> arg 0) (not (eobp)))
  19124. (org--forward-paragraph-once)
  19125. (cl-decf arg))
  19126. ;; Return moves left.
  19127. arg))
  19128. (defun org-backward-paragraph (&optional arg)
  19129. "Move backward by a paragraph, or equivalent, unit.
  19130. With argument ARG, do it ARG times;
  19131. a negative argument ARG = -N means move forward N paragraphs.
  19132. The function moves point between two structural
  19133. elements (paragraphs, tables, lists, etc.).
  19134. It also provides the following special moves for convenience:
  19135. - on a table or a property drawer, move to its beginning;
  19136. - on comment, example, export, source and verse blocks, stop
  19137. at blank lines;
  19138. - skip consecutive clocks, diary S-exps, and keywords."
  19139. (interactive "^p")
  19140. (unless arg (setq arg 1))
  19141. (if (< arg 0) (org-forward-paragraph (- arg))
  19142. (while (and (> arg 0) (not (bobp)))
  19143. (org--backward-paragraph-once)
  19144. (cl-decf arg))
  19145. ;; Return moves left.
  19146. arg))
  19147. (defun org--paragraph-at-point ()
  19148. "Return paragraph, or equivalent, element at point.
  19149. Paragraph element at point is the element at point, with the
  19150. following special cases:
  19151. - treat table rows (resp. node properties) as the table
  19152. \(resp. property drawer) containing them.
  19153. - treat plain lists with an item every line as a whole.
  19154. - treat consecutive keywords, clocks, and diary-sexps as a single
  19155. block.
  19156. Function may return a real element, or a pseudo-element with type
  19157. `pseudo-paragraph'."
  19158. (let* ((e (org-element-at-point))
  19159. (type (org-element-type e))
  19160. ;; If we need to fake a new pseudo-element, triplet is
  19161. ;;
  19162. ;; (BEG END PARENT)
  19163. ;;
  19164. ;; where BEG and END are element boundaries, and PARENT the
  19165. ;; element containing it, or nil.
  19166. (triplet
  19167. (cond
  19168. ((memq type '(table property-drawer))
  19169. (list (org-element-property :begin e)
  19170. (org-element-property :end e)
  19171. (org-element-property :parent e)))
  19172. ((memq type '(node-property table-row))
  19173. (let ((e (org-element-property :parent e)))
  19174. (list (org-element-property :begin e)
  19175. (org-element-property :end e)
  19176. (org-element-property :parent e))))
  19177. ((memq type '(clock diary-sexp keyword))
  19178. (let* ((regexp (pcase type
  19179. (`clock org-clock-line-re)
  19180. (`diary-sexp "%%(")
  19181. (_ org-keyword-regexp)))
  19182. (end (if (< 0 (org-element-property :post-blank e))
  19183. (org-element-property :end e)
  19184. (org-with-wide-buffer
  19185. (forward-line)
  19186. (while (looking-at regexp) (forward-line))
  19187. (skip-chars-forward " \t\n")
  19188. (line-beginning-position))))
  19189. (begin (org-with-point-at (org-element-property :begin e)
  19190. (while (and (not (bobp)) (looking-at regexp))
  19191. (forward-line -1))
  19192. ;; We may have gotten one line too far.
  19193. (if (looking-at regexp)
  19194. (point)
  19195. (line-beginning-position 2)))))
  19196. (list begin end (org-element-property :parent e))))
  19197. ;; Find the full plain list containing point, the check it
  19198. ;; contains exactly one line per item.
  19199. ((let ((l (org-element-lineage e '(plain-list) t)))
  19200. (while (memq (org-element-type (org-element-property :parent l))
  19201. '(item plain-list))
  19202. (setq l (org-element-property :parent l)))
  19203. (and l
  19204. (org-with-point-at (org-element-property :post-affiliated l)
  19205. (forward-line (length (org-element-property :structure l)))
  19206. (= (point) (org-element-property :contents-end l)))
  19207. ;; Return value.
  19208. (list (org-element-property :begin l)
  19209. (org-element-property :end l)
  19210. (org-element-property :parent l)))))
  19211. (t nil)))) ;no triplet: return element
  19212. (pcase triplet
  19213. (`(,b ,e ,p)
  19214. (org-element-create
  19215. 'pseudo-paragraph
  19216. (list :begin b :end e :parent p :post-blank 0 :post-affiliated b)))
  19217. (_ e))))
  19218. (defun org--forward-paragraph-once ()
  19219. "Move forward to end of paragraph or equivalent, once.
  19220. See `org-forward-paragraph'."
  19221. (interactive)
  19222. (save-restriction
  19223. (widen)
  19224. (skip-chars-forward " \t\n")
  19225. (cond
  19226. ((eobp) nil)
  19227. ;; When inside a folded part, move out of it.
  19228. ((pcase (get-char-property-and-overlay (point) 'invisible)
  19229. (`(,(or `outline `org-hide-block) . ,o)
  19230. (goto-char (overlay-end o))
  19231. (forward-line)
  19232. t)
  19233. (_ nil)))
  19234. (t
  19235. (let* ((element (org--paragraph-at-point))
  19236. (type (org-element-type element))
  19237. (contents-begin (org-element-property :contents-begin element))
  19238. (end (org-element-property :end element))
  19239. (post-affiliated (org-element-property :post-affiliated element)))
  19240. (cond
  19241. ((eq type 'plain-list)
  19242. (forward-char)
  19243. (org--forward-paragraph-once))
  19244. ;; If the element is folded, skip it altogether.
  19245. ((pcase (org-with-point-at post-affiliated
  19246. (get-char-property-and-overlay (line-end-position)
  19247. 'invisible))
  19248. (`(,(or `outline `org-hide-block) . ,o)
  19249. (goto-char (overlay-end o))
  19250. (forward-line)
  19251. t)
  19252. (_ nil)))
  19253. ;; At a greater element, move inside.
  19254. ((and contents-begin
  19255. (> contents-begin (point))
  19256. (not (eq type 'paragraph)))
  19257. (goto-char contents-begin)
  19258. ;; Items and footnote definitions contents may not start at
  19259. ;; the beginning of the line. In this case, skip until the
  19260. ;; next paragraph.
  19261. (cond
  19262. ((not (bolp)) (org--forward-paragraph-once))
  19263. ((org-previous-line-empty-p) (forward-line -1))
  19264. (t nil)))
  19265. ;; Move between empty lines in some blocks.
  19266. ((memq type '(comment-block example-block export-block src-block
  19267. verse-block))
  19268. (let ((contents-start
  19269. (org-with-point-at post-affiliated
  19270. (line-beginning-position 2))))
  19271. (if (< (point) contents-start)
  19272. (goto-char contents-start)
  19273. (let ((contents-end
  19274. (org-with-point-at end
  19275. (skip-chars-backward " \t\n")
  19276. (line-beginning-position))))
  19277. (cond
  19278. ((>= (point) contents-end)
  19279. (goto-char end)
  19280. (skip-chars-backward " \t\n")
  19281. (forward-line))
  19282. ((re-search-forward "^[ \t]*\n" contents-end :move)
  19283. (forward-line -1))
  19284. (t nil))))))
  19285. (t
  19286. ;; Move to element's end.
  19287. (goto-char end)
  19288. (skip-chars-backward " \t\n")
  19289. (forward-line))))))))
  19290. (defun org--backward-paragraph-once ()
  19291. "Move backward to start of paragraph or equivalent, once.
  19292. See `org-backward-paragraph'."
  19293. (interactive)
  19294. (save-restriction
  19295. (widen)
  19296. (cond
  19297. ((bobp) nil)
  19298. ;; Blank lines at the beginning of the buffer.
  19299. ((and (org-match-line "^[ \t]*$")
  19300. (save-excursion (skip-chars-backward " \t\n") (bobp)))
  19301. (goto-char (point-min)))
  19302. ;; When inside a folded part, move out of it.
  19303. ((pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  19304. (`(,(or `outline `org-hide-block) . ,o)
  19305. (goto-char (1- (overlay-start o)))
  19306. (org--backward-paragraph-once)
  19307. t)
  19308. (_ nil)))
  19309. (t
  19310. (let* ((element (org--paragraph-at-point))
  19311. (type (org-element-type element))
  19312. (begin (org-element-property :begin element))
  19313. (post-affiliated (org-element-property :post-affiliated element))
  19314. (contents-end (org-element-property :contents-end element))
  19315. (end (org-element-property :end element))
  19316. (parent (org-element-property :parent element))
  19317. (reach
  19318. ;; Move to the visible empty line above position P, or
  19319. ;; to position P. Return t.
  19320. (lambda (p)
  19321. (goto-char p)
  19322. (when (and (org-previous-line-empty-p)
  19323. (let ((end (line-end-position 0)))
  19324. (or (= end (point-min))
  19325. (not (org-invisible-p (1- end))))))
  19326. (forward-line -1))
  19327. t)))
  19328. (cond
  19329. ;; Already at the beginning of an element.
  19330. ((= begin (point))
  19331. (cond
  19332. ;; There is a blank line above. Move there.
  19333. ((and (org-previous-line-empty-p)
  19334. (let ((lep (line-end-position 0)))
  19335. ;; When the first headline start at point 2, don't choke while
  19336. ;; checking with `org-invisible-p'.
  19337. (or (= lep 1)
  19338. (not (org-invisible-p (1- (line-end-position 0)))))))
  19339. (forward-line -1))
  19340. ;; At the beginning of the first element within a greater
  19341. ;; element. Move to the beginning of the greater element.
  19342. ((and parent (= begin (org-element-property :contents-begin parent)))
  19343. (funcall reach (org-element-property :begin parent)))
  19344. ;; Since we have to move anyway, find the beginning
  19345. ;; position of the element above.
  19346. (t
  19347. (forward-char -1)
  19348. (org--backward-paragraph-once))))
  19349. ;; Skip paragraphs at the very beginning of footnote
  19350. ;; definitions or items.
  19351. ((and (eq type 'paragraph)
  19352. (org-with-point-at begin (not (bolp))))
  19353. (funcall reach (progn (goto-char begin) (line-beginning-position))))
  19354. ;; If the element is folded, skip it altogether.
  19355. ((org-with-point-at post-affiliated
  19356. (org-invisible-p (line-end-position) t))
  19357. (funcall reach begin))
  19358. ;; At the end of a greater element, move inside.
  19359. ((and contents-end
  19360. (<= contents-end (point))
  19361. (not (eq type 'paragraph)))
  19362. (cond
  19363. ((memq type '(footnote-definition plain-list))
  19364. (skip-chars-backward " \t\n")
  19365. (org--backward-paragraph-once))
  19366. ((= contents-end (point))
  19367. (forward-char -1)
  19368. (org--backward-paragraph-once))
  19369. (t
  19370. (goto-char contents-end))))
  19371. ;; Move between empty lines in some blocks.
  19372. ((and (memq type '(comment-block example-block export-block src-block
  19373. verse-block))
  19374. (let ((contents-start
  19375. (org-with-point-at post-affiliated
  19376. (line-beginning-position 2))))
  19377. (when (> (point) contents-start)
  19378. (let ((contents-end
  19379. (org-with-point-at end
  19380. (skip-chars-backward " \t\n")
  19381. (line-beginning-position))))
  19382. (if (> (point) contents-end)
  19383. (progn (goto-char contents-end) t)
  19384. (skip-chars-backward " \t\n" begin)
  19385. (re-search-backward "^[ \t]*\n" contents-start :move)
  19386. t))))))
  19387. ;; Move to element's start.
  19388. (t
  19389. (funcall reach begin))))))))
  19390. (defun org-forward-element ()
  19391. "Move forward by one element.
  19392. Move to the next element at the same level, when possible."
  19393. (interactive)
  19394. (cond ((eobp) (user-error "Cannot move further down"))
  19395. ((org-with-limited-levels (org-at-heading-p))
  19396. (let ((origin (point)))
  19397. (goto-char (org-end-of-subtree nil t))
  19398. (unless (org-with-limited-levels (org-at-heading-p))
  19399. (goto-char origin)
  19400. (user-error "Cannot move further down"))))
  19401. (t
  19402. (let* ((elem (org-element-at-point))
  19403. (end (org-element-property :end elem))
  19404. (parent (org-element-property :parent elem)))
  19405. (cond ((and parent (= (org-element-property :contents-end parent) end))
  19406. (goto-char (org-element-property :end parent)))
  19407. ((integer-or-marker-p end) (goto-char end))
  19408. (t (message "No element at point")))))))
  19409. (defun org-backward-element ()
  19410. "Move backward by one element.
  19411. Move to the previous element at the same level, when possible."
  19412. (interactive)
  19413. (cond ((bobp) (user-error "Cannot move further up"))
  19414. ((org-with-limited-levels (org-at-heading-p))
  19415. ;; At a headline, move to the previous one, if any, or stay
  19416. ;; here.
  19417. (let ((origin (point)))
  19418. (org-with-limited-levels (org-backward-heading-same-level 1))
  19419. ;; When current headline has no sibling above, move to its
  19420. ;; parent.
  19421. (when (= (point) origin)
  19422. (or (org-with-limited-levels (org-up-heading-safe))
  19423. (progn (goto-char origin)
  19424. (user-error "Cannot move further up"))))))
  19425. (t
  19426. (let* ((elem (org-element-at-point))
  19427. (beg (org-element-property :begin elem)))
  19428. (cond
  19429. ;; Move to beginning of current element if point isn't
  19430. ;; there already.
  19431. ((null beg) (message "No element at point"))
  19432. ((/= (point) beg) (goto-char beg))
  19433. (t (goto-char beg)
  19434. (skip-chars-backward " \r\t\n")
  19435. (unless (bobp)
  19436. (let ((prev (org-element-at-point)))
  19437. (goto-char (org-element-property :begin prev))
  19438. (while (and (setq prev (org-element-property :parent prev))
  19439. (<= (org-element-property :end prev) beg))
  19440. (goto-char (org-element-property :begin prev)))))))))))
  19441. (defun org-up-element ()
  19442. "Move to upper element."
  19443. (interactive)
  19444. (if (org-with-limited-levels (org-at-heading-p))
  19445. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  19446. (let* ((elem (org-element-at-point))
  19447. (parent (org-element-property :parent elem)))
  19448. (if parent (goto-char (org-element-property :begin parent))
  19449. (if (org-with-limited-levels (org-before-first-heading-p))
  19450. (user-error "No surrounding element")
  19451. (org-with-limited-levels (org-back-to-heading)))))))
  19452. (defun org-down-element ()
  19453. "Move to inner element."
  19454. (interactive)
  19455. (let ((element (org-element-at-point)))
  19456. (cond
  19457. ((memq (org-element-type element) '(plain-list table))
  19458. (goto-char (org-element-property :contents-begin element))
  19459. (forward-char))
  19460. ((memq (org-element-type element) org-element-greater-elements)
  19461. ;; If contents are hidden, first disclose them.
  19462. (when (org-invisible-p (line-end-position)) (org-cycle))
  19463. (goto-char (or (org-element-property :contents-begin element)
  19464. (user-error "No content for this element"))))
  19465. (t (user-error "No inner element")))))
  19466. (defun org-drag-element-backward ()
  19467. "Move backward element at point."
  19468. (interactive)
  19469. (let ((elem (or (org-element-at-point)
  19470. (user-error "No element at point"))))
  19471. (if (eq (org-element-type elem) 'headline)
  19472. ;; Preserve point when moving a whole tree, even if point was
  19473. ;; on blank lines below the headline.
  19474. (let ((offset (skip-chars-backward " \t\n")))
  19475. (unwind-protect (org-move-subtree-up)
  19476. (forward-char (- offset))))
  19477. (let ((prev-elem
  19478. (save-excursion
  19479. (goto-char (org-element-property :begin elem))
  19480. (skip-chars-backward " \r\t\n")
  19481. (unless (bobp)
  19482. (let* ((beg (org-element-property :begin elem))
  19483. (prev (org-element-at-point))
  19484. (up prev))
  19485. (while (and (setq up (org-element-property :parent up))
  19486. (<= (org-element-property :end up) beg))
  19487. (setq prev up))
  19488. prev)))))
  19489. ;; Error out if no previous element or previous element is
  19490. ;; a parent of the current one.
  19491. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  19492. (user-error "Cannot drag element backward")
  19493. (let ((pos (point)))
  19494. (org-element-swap-A-B prev-elem elem)
  19495. (goto-char (+ (org-element-property :begin prev-elem)
  19496. (- pos (org-element-property :begin elem))))))))))
  19497. (defun org-drag-element-forward ()
  19498. "Move forward element at point."
  19499. (interactive)
  19500. (let* ((pos (point))
  19501. (elem (or (org-element-at-point)
  19502. (user-error "No element at point"))))
  19503. (when (= (point-max) (org-element-property :end elem))
  19504. (user-error "Cannot drag element forward"))
  19505. (goto-char (org-element-property :end elem))
  19506. (let ((next-elem (org-element-at-point)))
  19507. (when (or (org-element-nested-p elem next-elem)
  19508. (and (eq (org-element-type next-elem) 'headline)
  19509. (not (eq (org-element-type elem) 'headline))))
  19510. (goto-char pos)
  19511. (user-error "Cannot drag element forward"))
  19512. ;; Compute new position of point: it's shifted by NEXT-ELEM
  19513. ;; body's length (without final blanks) and by the length of
  19514. ;; blanks between ELEM and NEXT-ELEM.
  19515. (let ((size-next (- (save-excursion
  19516. (goto-char (org-element-property :end next-elem))
  19517. (skip-chars-backward " \r\t\n")
  19518. (forward-line)
  19519. ;; Small correction if buffer doesn't end
  19520. ;; with a newline character.
  19521. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  19522. (org-element-property :begin next-elem)))
  19523. (size-blank (- (org-element-property :end elem)
  19524. (save-excursion
  19525. (goto-char (org-element-property :end elem))
  19526. (skip-chars-backward " \r\t\n")
  19527. (forward-line)
  19528. (point)))))
  19529. (org-element-swap-A-B elem next-elem)
  19530. (goto-char (+ pos size-next size-blank))))))
  19531. (defun org-drag-line-forward (arg)
  19532. "Drag the line at point ARG lines forward."
  19533. (interactive "p")
  19534. (dotimes (_ (abs arg))
  19535. (let ((c (current-column)))
  19536. (if (< 0 arg)
  19537. (progn
  19538. (beginning-of-line 2)
  19539. (transpose-lines 1)
  19540. (beginning-of-line 0))
  19541. (transpose-lines 1)
  19542. (beginning-of-line -1))
  19543. (org-move-to-column c))))
  19544. (defun org-drag-line-backward (arg)
  19545. "Drag the line at point ARG lines backward."
  19546. (interactive "p")
  19547. (org-drag-line-forward (- arg)))
  19548. (defun org-mark-element ()
  19549. "Put point at beginning of this element, mark at end.
  19550. Interactively, if this command is repeated or (in Transient Mark
  19551. mode) if the mark is active, it marks the next element after the
  19552. ones already marked."
  19553. (interactive)
  19554. (let (deactivate-mark)
  19555. (if (and (called-interactively-p 'any)
  19556. (or (and (eq last-command this-command) (mark t))
  19557. (and transient-mark-mode mark-active)))
  19558. (set-mark
  19559. (save-excursion
  19560. (goto-char (mark))
  19561. (goto-char (org-element-property :end (org-element-at-point)))
  19562. (point)))
  19563. (let ((element (org-element-at-point)))
  19564. (end-of-line)
  19565. (push-mark (min (point-max) (org-element-property :end element)) t t)
  19566. (goto-char (org-element-property :begin element))))))
  19567. (defun org-narrow-to-element ()
  19568. "Narrow buffer to current element."
  19569. (interactive)
  19570. (let ((elem (org-element-at-point)))
  19571. (cond
  19572. ((eq (car elem) 'headline)
  19573. (narrow-to-region
  19574. (org-element-property :begin elem)
  19575. (org-element-property :end elem)))
  19576. ((memq (car elem) org-element-greater-elements)
  19577. (narrow-to-region
  19578. (org-element-property :contents-begin elem)
  19579. (org-element-property :contents-end elem)))
  19580. (t
  19581. (narrow-to-region
  19582. (org-element-property :begin elem)
  19583. (org-element-property :end elem))))))
  19584. (defun org-transpose-element ()
  19585. "Transpose current and previous elements, keeping blank lines between.
  19586. Point is moved after both elements."
  19587. (interactive)
  19588. (org-skip-whitespace)
  19589. (let ((end (org-element-property :end (org-element-at-point))))
  19590. (org-drag-element-backward)
  19591. (goto-char end)))
  19592. (defun org-unindent-buffer ()
  19593. "Un-indent the visible part of the buffer.
  19594. Relative indentation (between items, inside blocks, etc.) isn't
  19595. modified."
  19596. (interactive)
  19597. (unless (eq major-mode 'org-mode)
  19598. (user-error "Cannot un-indent a buffer not in Org mode"))
  19599. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  19600. (unindent-tree
  19601. (lambda (contents)
  19602. (dolist (element (reverse contents))
  19603. (if (memq (org-element-type element) '(headline section))
  19604. (funcall unindent-tree (org-element-contents element))
  19605. (save-excursion
  19606. (save-restriction
  19607. (narrow-to-region
  19608. (org-element-property :begin element)
  19609. (org-element-property :end element))
  19610. (org-do-remove-indentation))))))))
  19611. (funcall unindent-tree (org-element-contents parse-tree))))
  19612. (defun org-make-options-regexp (kwds &optional extra)
  19613. "Make a regular expression for keyword lines.
  19614. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  19615. when non-nil, is a regexp matching keywords names."
  19616. (concat "^[ \t]*#\\+\\("
  19617. (regexp-opt kwds)
  19618. (and extra (concat (and kwds "\\|") extra))
  19619. "\\):[ \t]*\\(.*\\)"))
  19620. ;;; Conveniently switch to Info nodes
  19621. (defun org-info-find-node (&optional nodename)
  19622. "Find Info documentation NODENAME or Org documentation according context.
  19623. Started from `gnus-info-find-node'."
  19624. (interactive)
  19625. (Info-goto-node
  19626. (or nodename
  19627. (let ((default-org-info-node "(org) Top"))
  19628. (cond
  19629. ((eq 'org-agenda-mode major-mode) "(org) Agenda Views")
  19630. ((eq 'org-mode major-mode)
  19631. (let* ((context (org-element-at-point))
  19632. (element-info-nodes ; compare to `org-element-all-elements'.
  19633. `((babel-call . "(org) Evaluating Code Blocks")
  19634. (center-block . "(org) Paragraphs")
  19635. (clock . ,default-org-info-node)
  19636. (comment . "(org) Comment Lines")
  19637. (comment-block . "(org) Comment Lines")
  19638. (diary-sexp . ,default-org-info-node)
  19639. (drawer . "(org) Drawers")
  19640. (dynamic-block . "(org) Dynamic Blocks")
  19641. (example-block . "(org) Literal Examples")
  19642. (export-block . "(org) ASCII/Latin-1/UTF-8 export")
  19643. (fixed-width . ,default-org-info-node)
  19644. (footnote-definition . "(org) Creating Footnotes")
  19645. (headline . "(org) Document Structure")
  19646. (horizontal-rule . "(org) Built-in Table Editor")
  19647. (inlinetask . ,default-org-info-node)
  19648. (item . "(org) Plain Lists")
  19649. (keyword . "(org) Per-file keywords")
  19650. (latex-environment . "(org) LaTeX Export")
  19651. (node-property . "(org) Properties and Columns")
  19652. (paragraph . "(org) Paragraphs")
  19653. (plain-list . "(org) Plain Lists")
  19654. (planning . "(org) Deadlines and Scheduling")
  19655. (property-drawer . "(org) Properties and Columns")
  19656. (quote-block . "(org) Paragraphs")
  19657. (section . ,default-org-info-node)
  19658. (special-block . ,default-org-info-node)
  19659. (src-block . "(org) Working with Source Code")
  19660. (table . "(org) Tables")
  19661. (table-row . "(org) Tables")
  19662. (verse-block . "(org) Paragraphs"))))
  19663. (or (cdr (assoc (car context) element-info-nodes))
  19664. default-org-info-node)))
  19665. (t default-org-info-node))))))
  19666. ;;; Finish up
  19667. (add-hook 'org-mode-hook ;remove overlays when changing major mode
  19668. (lambda () (add-hook 'change-major-mode-hook
  19669. 'org-show-all 'append 'local)))
  19670. (provide 'org)
  19671. (run-hooks 'org-load-hook)
  19672. ;;; org.el ends here