org.el 791 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892
  1. ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
  2. ;; Carstens outline-mode for keeping track of everything.
  3. ;; Copyright (C) 2004-2020 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  6. ;; Maintainer: Bastien Guerry <bzg@gnu.org>
  7. ;; Keywords: outlines, hypermedia, calendar, wp
  8. ;; Homepage: https://orgmode.org
  9. ;; Version: 9.4-dev
  10. ;; This file is part of GNU Emacs.
  11. ;;
  12. ;; GNU Emacs is free software: you can redistribute it and/or modify
  13. ;; it under the terms of the GNU General Public License as published by
  14. ;; the Free Software Foundation, either version 3 of the License, or
  15. ;; (at your option) any later version.
  16. ;; GNU Emacs is distributed in the hope that it will be useful,
  17. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. ;; GNU General Public License for more details.
  20. ;; You should have received a copy of the GNU General Public License
  21. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  22. ;;
  23. ;;; Commentary:
  24. ;;
  25. ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
  26. ;; project planning with a fast and effective plain-text system.
  27. ;;
  28. ;; Org mode develops organizational tasks around NOTES files that
  29. ;; contain information about projects as plain text. Org mode is
  30. ;; implemented on top of outline-mode, which makes it possible to keep
  31. ;; the content of large files well structured. Visibility cycling and
  32. ;; structure editing help to work with the tree. Tables are easily
  33. ;; created with a built-in table editor. Org mode supports ToDo
  34. ;; items, deadlines, time stamps, and scheduling. It dynamically
  35. ;; compiles entries into an agenda that utilizes and smoothly
  36. ;; integrates much of the Emacs calendar and diary. Plain text
  37. ;; URL-like links connect to websites, emails, Usenet messages, BBDB
  38. ;; entries, and any files related to the projects. For printing and
  39. ;; sharing of notes, an Org file can be exported as a structured ASCII
  40. ;; file, as HTML, or (todo and agenda items only) as an iCalendar
  41. ;; file. It can also serve as a publishing tool for a set of linked
  42. ;; webpages.
  43. ;;
  44. ;; Installation and Activation
  45. ;; ---------------------------
  46. ;; See the corresponding sections in the manual at
  47. ;;
  48. ;; https://orgmode.org/org.html#Installation
  49. ;;
  50. ;; Documentation
  51. ;; -------------
  52. ;; The documentation of Org mode can be found in the TeXInfo file. The
  53. ;; distribution also contains a PDF version of it. At the homepage of
  54. ;; Org mode, you can read the same text online as HTML. There is also an
  55. ;; excellent reference card made by Philip Rooke. This card can be found
  56. ;; in the doc/ directory.
  57. ;;
  58. ;; A list of recent changes can be found at
  59. ;; https://orgmode.org/Changes.html
  60. ;;
  61. ;;; Code:
  62. (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
  63. (defvar org-inlinetask-min-level)
  64. ;;;; Require other packages
  65. (require 'cl-lib)
  66. (eval-when-compile (require 'gnus-sum))
  67. (require 'calendar)
  68. (require 'find-func)
  69. (require 'format-spec)
  70. (or (eq this-command 'eval-buffer)
  71. (condition-case nil
  72. (load (concat (file-name-directory load-file-name)
  73. "org-loaddefs.el")
  74. nil t t t)
  75. (error
  76. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  77. (sit-for 3)
  78. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  79. (sit-for 3))))
  80. (eval-and-compile (require 'org-macs))
  81. (require 'org-compat)
  82. (require 'org-keys)
  83. (require 'ol)
  84. (require 'org-table)
  85. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  86. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  87. (defvar org-outline-regexp "\\*+ "
  88. "Regexp to match Org headlines.")
  89. (defvar org-outline-regexp-bol "^\\*+ "
  90. "Regexp to match Org headlines.
  91. This is similar to `org-outline-regexp' but additionally makes
  92. sure that we are at the beginning of the line.")
  93. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  94. "Matches a headline, putting stars and text into groups.
  95. Stars are put in group 1 and the trimmed body in group 2.")
  96. (declare-function calendar-check-holidays "holidays" (date))
  97. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  98. (declare-function cdlatex-math-symbol "ext:cdlatex")
  99. (declare-function Info-goto-node "info" (nodename &optional fork strict-case))
  100. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  101. (declare-function org-add-archive-files "org-archive" (files))
  102. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  103. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
  104. (declare-function org-agenda-redo "org-agenda" (&optional all))
  105. (declare-function org-agenda-remove-restriction-lock "org-agenda" (&optional noupdate))
  106. (declare-function org-archive-subtree "org-archive" (&optional find-done))
  107. (declare-function org-archive-subtree-default "org-archive" ())
  108. (declare-function org-archive-to-archive-sibling "org-archive" ())
  109. (declare-function org-attach "org-attach" ())
  110. (declare-function org-attach-dir "org-attach"
  111. (&optional create-if-not-exists-p no-fs-check))
  112. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  113. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  114. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  115. (declare-function org-clock-auto-clockout "org-clock" ())
  116. (declare-function org-clock-cancel "org-clock" ())
  117. (declare-function org-clock-display "org-clock" (&optional arg))
  118. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  119. (declare-function org-clock-goto "org-clock" (&optional select))
  120. (declare-function org-clock-in "org-clock" (&optional select start-time))
  121. (declare-function org-clock-in-last "org-clock" (&optional arg))
  122. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  123. (declare-function org-clock-out-if-current "org-clock" ())
  124. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  125. (declare-function org-clock-report "org-clock" (&optional arg))
  126. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  127. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  128. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  129. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  130. (declare-function org-clock-update-time-maybe "org-clock" ())
  131. (declare-function org-clocking-buffer "org-clock" ())
  132. (declare-function org-clocktable-shift "org-clock" (dir n))
  133. (declare-function org-columns-quit "org-colview" ())
  134. (declare-function org-columns-insert-dblock "org-colview" ())
  135. (declare-function org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  136. (declare-function org-element-at-point "org-element" ())
  137. (declare-function org-element-cache-refresh "org-element" (pos))
  138. (declare-function org-element-cache-reset "org-element" (&optional all))
  139. (declare-function org-element-contents "org-element" (element))
  140. (declare-function org-element-context "org-element" (&optional element))
  141. (declare-function org-element-copy "org-element" (datum))
  142. (declare-function org-element-create "org-element" (type &optional props &rest children))
  143. (declare-function org-element-interpret-data "org-element" (data))
  144. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  145. (declare-function org-element-link-parser "org-element" ())
  146. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  147. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  148. (declare-function org-element-property "org-element" (property element))
  149. (declare-function org-element-put-property "org-element" (element property value))
  150. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  151. (declare-function org-element-timestamp-parser "org-element" ())
  152. (declare-function org-element-type "org-element" (element))
  153. (declare-function org-export-dispatch "ox" (&optional arg))
  154. (declare-function org-export-get-backend "ox" (name))
  155. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  156. (declare-function org-feed-goto-inbox "org-feed" (feed))
  157. (declare-function org-feed-update-all "org-feed" ())
  158. (declare-function org-goto "org-goto" (&optional alternative-interface))
  159. (declare-function org-id-find-id-file "org-id" (id))
  160. (declare-function org-id-get-create "org-id" (&optional force))
  161. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  162. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  163. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  164. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  165. (declare-function org-num-mode "org-num" (&optional arg))
  166. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  167. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  168. (declare-function org-timer "org-timer" (&optional restart no-insert))
  169. (declare-function org-timer-item "org-timer" (&optional arg))
  170. (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
  171. (declare-function org-timer-set-timer "org-timer" (&optional opt))
  172. (declare-function org-timer-start "org-timer" (&optional offset))
  173. (declare-function org-timer-stop "org-timer" ())
  174. (declare-function org-toggle-archive-tag "org-archive" (&optional find-done))
  175. (declare-function org-update-radio-target-regexp "ol" ())
  176. (defvar ffap-url-regexp)
  177. (defvar org-element-paragraph-separate)
  178. (defvar org-indent-indentation-per-level)
  179. (defvar org-radio-target-regexp)
  180. (defvar org-target-link-regexp)
  181. (defvar org-target-regexp)
  182. (defvar org-id-overriding-file-name)
  183. ;; load languages based on value of `org-babel-load-languages'
  184. (defvar org-babel-load-languages)
  185. ;;;###autoload
  186. (defun org-babel-do-load-languages (sym value)
  187. "Load the languages defined in `org-babel-load-languages'."
  188. (set-default sym value)
  189. (dolist (pair org-babel-load-languages)
  190. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  191. (if active
  192. (require (intern (concat "ob-" lang)))
  193. (fmakunbound
  194. (intern (concat "org-babel-execute:" lang)))
  195. (fmakunbound
  196. (intern (concat "org-babel-expand-body:" lang)))))))
  197. ;;;###autoload
  198. (defun org-babel-load-file (file &optional compile)
  199. "Load Emacs Lisp source code blocks in the Org FILE.
  200. This function exports the source code using `org-babel-tangle'
  201. and then loads the resulting file using `load-file'. With
  202. optional prefix argument COMPILE, the tangled Emacs Lisp file is
  203. byte-compiled before it is loaded."
  204. (interactive "fFile to load: \nP")
  205. (let ((tangled-file (concat (file-name-sans-extension file) ".el")))
  206. ;; Tangle only if the Org file is newer than the Elisp file.
  207. (unless (org-file-newer-than-p
  208. tangled-file
  209. (file-attribute-modification-time
  210. (file-attributes (file-truename file))))
  211. (org-babel-tangle-file file tangled-file "emacs-lisp\\|elisp"))
  212. (if compile
  213. (progn
  214. (byte-compile-file tangled-file 'load)
  215. (message "Compiled and loaded %s" tangled-file))
  216. (load-file tangled-file)
  217. (message "Loaded %s" tangled-file))))
  218. (defcustom org-babel-load-languages '((emacs-lisp . t))
  219. "Languages which can be evaluated in Org buffers.
  220. \\<org-mode-map>
  221. This list can be used to load support for any of the languages
  222. below. Each language will depend on a different set of system
  223. executables and/or Emacs modes.
  224. When a language is \"loaded\", code blocks in that language can
  225. be evaluated with `org-babel-execute-src-block', which is bound
  226. by default to \\[org-ctrl-c-ctrl-c].
  227. The `org-babel-no-eval-on-ctrl-c-ctrl-c' option can be set to
  228. remove code block evaluation from \\[org-ctrl-c-ctrl-c]. By
  229. default, only Emacs Lisp is loaded, since it has no specific
  230. requirement."
  231. :group 'org-babel
  232. :set 'org-babel-do-load-languages
  233. :version "24.1"
  234. :type '(alist :tag "Babel Languages"
  235. :key-type
  236. (choice
  237. (const :tag "Awk" awk)
  238. (const :tag "C" C)
  239. (const :tag "R" R)
  240. (const :tag "Asymptote" asymptote)
  241. (const :tag "Calc" calc)
  242. (const :tag "Clojure" clojure)
  243. (const :tag "CSS" css)
  244. (const :tag "Ditaa" ditaa)
  245. (const :tag "Dot" dot)
  246. (const :tag "Ebnf2ps" ebnf2ps)
  247. (const :tag "Emacs Lisp" emacs-lisp)
  248. (const :tag "Forth" forth)
  249. (const :tag "Fortran" fortran)
  250. (const :tag "Gnuplot" gnuplot)
  251. (const :tag "Haskell" haskell)
  252. (const :tag "hledger" hledger)
  253. (const :tag "IO" io)
  254. (const :tag "J" J)
  255. (const :tag "Java" java)
  256. (const :tag "Javascript" js)
  257. (const :tag "LaTeX" latex)
  258. (const :tag "Ledger" ledger)
  259. (const :tag "Lilypond" lilypond)
  260. (const :tag "Lisp" lisp)
  261. (const :tag "Makefile" makefile)
  262. (const :tag "Maxima" maxima)
  263. (const :tag "Matlab" matlab)
  264. (const :tag "Mscgen" mscgen)
  265. (const :tag "Ocaml" ocaml)
  266. (const :tag "Octave" octave)
  267. (const :tag "Org" org)
  268. (const :tag "Perl" perl)
  269. (const :tag "Pico Lisp" picolisp)
  270. (const :tag "PlantUML" plantuml)
  271. (const :tag "Python" python)
  272. (const :tag "Ruby" ruby)
  273. (const :tag "Sass" sass)
  274. (const :tag "Scala" scala)
  275. (const :tag "Scheme" scheme)
  276. (const :tag "Screen" screen)
  277. (const :tag "Shell Script" shell)
  278. (const :tag "Shen" shen)
  279. (const :tag "Sql" sql)
  280. (const :tag "Sqlite" sqlite)
  281. (const :tag "Stan" stan)
  282. (const :tag "Vala" vala))
  283. :value-type (boolean :tag "Activate" :value t)))
  284. ;;;; Customization variables
  285. (defcustom org-clone-delete-id nil
  286. "Remove ID property of clones of a subtree.
  287. When non-nil, clones of a subtree don't inherit the ID property.
  288. Otherwise they inherit the ID property with a new unique
  289. identifier."
  290. :type 'boolean
  291. :version "24.1"
  292. :group 'org-id)
  293. ;;; Version
  294. (org-check-version)
  295. ;;;###autoload
  296. (defun org-version (&optional here full message)
  297. "Show the Org version.
  298. Interactively, or when MESSAGE is non-nil, show it in echo area.
  299. With prefix argument, or when HERE is non-nil, insert it at point.
  300. In non-interactive uses, a reduced version string is output unless
  301. FULL is given."
  302. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  303. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  304. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  305. (load-suffixes (list ".el"))
  306. (org-install-dir
  307. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  308. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  309. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  310. (let* ((load-suffixes save-load-suffixes)
  311. (release (org-release))
  312. (git-version (org-git-version))
  313. (version (format "Org mode version %s (%s @ %s)"
  314. release
  315. git-version
  316. (if org-install-dir
  317. (if (string= org-dir org-install-dir)
  318. org-install-dir
  319. (concat "mixed installation! "
  320. org-install-dir
  321. " and "
  322. org-dir))
  323. "org-loaddefs.el can not be found!")))
  324. (version1 (if full version release)))
  325. (when here (insert version1))
  326. (when message (message "%s" version1))
  327. version1)))
  328. (defconst org-version (org-version))
  329. ;;; Syntax Constants
  330. ;;;; Keyword
  331. (defconst org-keyword-regexp "^[ \t]*#\\+\\(\\S-+?\\):[ \t]*\\(.*\\)$"
  332. "Regular expression for keyword-lines")
  333. ;;;; Block
  334. (defconst org-block-regexp
  335. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  336. "Regular expression for hiding blocks.")
  337. (defconst org-dblock-start-re
  338. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  339. "Matches the start line of a dynamic block, with parameters.")
  340. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  341. "Matches the end of a dynamic block.")
  342. ;;;; Timestamp
  343. (defconst org-ts--internal-regexp
  344. (rx (seq
  345. (= 4 digit) "-" (= 2 digit) "-" (= 2 digit)
  346. (optional " " (*? nonl))))
  347. "Regular expression matching the innards of a time stamp.")
  348. (defconst org-ts-regexp (format "<\\(%s\\)>" org-ts--internal-regexp)
  349. "Regular expression for fast time stamp matching.")
  350. (defconst org-ts-regexp-inactive
  351. (format "\\[\\(%s\\)\\]" org-ts--internal-regexp)
  352. "Regular expression for fast inactive time stamp matching.")
  353. (defconst org-ts-regexp-both (format "[[<]\\(%s\\)[]>]" org-ts--internal-regexp)
  354. "Regular expression for fast time stamp matching.")
  355. (defconst org-ts-regexp0
  356. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  357. "Regular expression matching time strings for analysis.
  358. This one does not require the space after the date, so it can be used
  359. on a string that terminates immediately after the date.")
  360. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  361. "Regular expression matching time strings for analysis.")
  362. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  363. "Regular expression matching time stamps, with groups.")
  364. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  365. "Regular expression matching time stamps (also [..]), with groups.")
  366. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  367. "Regular expression matching a time stamp range.")
  368. (defconst org-tr-regexp-both
  369. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  370. "Regular expression matching a time stamp range.")
  371. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  372. org-ts-regexp "\\)?")
  373. "Regular expression matching a time stamp or time stamp range.")
  374. (defconst org-tsr-regexp-both
  375. (concat org-ts-regexp-both "\\(--?-?"
  376. org-ts-regexp-both "\\)?")
  377. "Regular expression matching a time stamp or time stamp range.
  378. The time stamps may be either active or inactive.")
  379. (defconst org-repeat-re
  380. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\
  381. \\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  382. "Regular expression for specifying repeated events.
  383. After a match, group 1 contains the repeat expression.")
  384. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  385. "Formats for `format-time-string' which are used for time stamps.")
  386. ;;;; Clock and Planning
  387. (defconst org-clock-string "CLOCK:"
  388. "String used as prefix for timestamps clocking work hours on an item.")
  389. (defvar org-closed-string "CLOSED:"
  390. "String used as the prefix for timestamps logging closing a TODO entry.")
  391. (defvar org-deadline-string "DEADLINE:"
  392. "String to mark deadline entries.
  393. \\<org-mode-map>
  394. A deadline is this string, followed by a time stamp. It must be
  395. a word, terminated by a colon. You can insert a schedule keyword
  396. and a timestamp with `\\[org-deadline]'.")
  397. (defvar org-scheduled-string "SCHEDULED:"
  398. "String to mark scheduled TODO entries.
  399. \\<org-mode-map>
  400. A schedule is this string, followed by a time stamp. It must be
  401. a word, terminated by a colon. You can insert a schedule keyword
  402. and a timestamp with `\\[org-schedule]'.")
  403. (defconst org-ds-keyword-length
  404. (+ 2
  405. (apply #'max
  406. (mapcar #'length
  407. (list org-deadline-string org-scheduled-string
  408. org-clock-string org-closed-string))))
  409. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  410. (defconst org-planning-line-re
  411. (concat "^[ \t]*"
  412. (regexp-opt
  413. (list org-closed-string org-deadline-string org-scheduled-string)
  414. t))
  415. "Matches a line with planning info.
  416. Matched keyword is in group 1.")
  417. (defconst org-clock-line-re
  418. (concat "^[ \t]*" org-clock-string)
  419. "Matches a line with clock info.")
  420. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  421. "Matches the DEADLINE keyword.")
  422. (defconst org-deadline-time-regexp
  423. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  424. "Matches the DEADLINE keyword together with a time stamp.")
  425. (defconst org-deadline-time-hour-regexp
  426. (concat "\\<" org-deadline-string
  427. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
  428. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  429. (defconst org-deadline-line-regexp
  430. (concat "\\<\\(" org-deadline-string "\\).*")
  431. "Matches the DEADLINE keyword and the rest of the line.")
  432. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  433. "Matches the SCHEDULED keyword.")
  434. (defconst org-scheduled-time-regexp
  435. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  436. "Matches the SCHEDULED keyword together with a time stamp.")
  437. (defconst org-scheduled-time-hour-regexp
  438. (concat "\\<" org-scheduled-string
  439. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
  440. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  441. (defconst org-closed-time-regexp
  442. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  443. "Matches the CLOSED keyword together with a time stamp.")
  444. (defconst org-keyword-time-regexp
  445. (concat "\\<"
  446. (regexp-opt
  447. (list org-scheduled-string org-deadline-string org-closed-string
  448. org-clock-string)
  449. t)
  450. " *[[<]\\([^]>]+\\)[]>]")
  451. "Matches any of the 4 keywords, together with the time stamp.")
  452. (defconst org-keyword-time-not-clock-regexp
  453. (concat
  454. "\\<"
  455. (regexp-opt
  456. (list org-scheduled-string org-deadline-string org-closed-string) t)
  457. " *[[<]\\([^]>]+\\)[]>]")
  458. "Matches any of the 3 keywords, together with the time stamp.")
  459. (defconst org-all-time-keywords
  460. (mapcar (lambda (w) (substring w 0 -1))
  461. (list org-scheduled-string org-deadline-string
  462. org-clock-string org-closed-string))
  463. "List of time keywords.")
  464. ;;;; Drawer
  465. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  466. "Matches first or last line of a hidden block.
  467. Group 1 contains drawer's name or \"END\".")
  468. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  469. "Regular expression matching the first line of a property drawer.")
  470. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  471. "Regular expression matching the last line of a property drawer.")
  472. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  473. "Regular expression matching the first line of a clock drawer.")
  474. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  475. "Regular expression matching the last line of a clock drawer.")
  476. (defconst org-logbook-drawer-re
  477. (rx (seq bol (0+ (any "\t ")) ":LOGBOOK:" (0+ (any "\t ")) "\n"
  478. (*? (0+ nonl) "\n")
  479. (0+ (any "\t ")) ":END:" (0+ (any "\t ")) eol))
  480. "Matches an entire LOGBOOK drawer.")
  481. (defconst org-property-drawer-re
  482. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  483. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  484. "[ \t]*:END:[ \t]*$")
  485. "Matches an entire property drawer.")
  486. (defconst org-clock-drawer-re
  487. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  488. org-clock-drawer-end-re "\\)\n?")
  489. "Matches an entire clock drawer.")
  490. ;;;; Headline
  491. (defconst org-heading-keyword-regexp-format
  492. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  493. "Printf format for a regexp matching a headline with some keyword.
  494. This regexp will match the headline of any node which has the
  495. exact keyword that is put into the format. The keyword isn't in
  496. any group by default, but the stars and the body are.")
  497. (defconst org-heading-keyword-maybe-regexp-format
  498. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  499. "Printf format for a regexp matching a headline, possibly with some keyword.
  500. This regexp can match any headline with the specified keyword, or
  501. without a keyword. The keyword isn't in any group by default,
  502. but the stars and the body are.")
  503. (defconst org-archive-tag "ARCHIVE"
  504. "The tag that marks a subtree as archived.
  505. An archived subtree does not open during visibility cycling, and does
  506. not contribute to the agenda listings.")
  507. (defconst org-tag-re "[[:alnum:]_@#%]+"
  508. "Regexp matching a single tag.")
  509. (defconst org-tag-group-re "[ \t]+\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  510. "Regexp matching the tag group at the end of a line, with leading spaces.
  511. Tags are stored in match group 1. Match group 2 stores the tags
  512. without the enclosing colons.")
  513. (defconst org-tag-line-re
  514. "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  515. "Regexp matching tags in a headline.
  516. Tags are stored in match group 1. Match group 2 stores the tags
  517. without the enclosing colons.")
  518. (eval-and-compile
  519. (defconst org-comment-string "COMMENT"
  520. "Entries starting with this keyword will never be exported.
  521. \\<org-mode-map>
  522. An entry can be toggled between COMMENT and normal with
  523. `\\[org-toggle-comment]'."))
  524. ;;;; LaTeX Environments and Fragments
  525. (defconst org-latex-regexps
  526. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  527. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  528. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  529. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  530. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  531. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  532. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  533. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  534. "Regular expressions for matching embedded LaTeX.")
  535. ;;;; Node Property
  536. (defconst org-effort-property "Effort"
  537. "The property that is being used to keep track of effort estimates.
  538. Effort estimates given in this property need to be in the format
  539. defined in org-duration.el.")
  540. ;;; The custom variables
  541. (defgroup org nil
  542. "Outline-based notes management and organizer."
  543. :tag "Org"
  544. :group 'outlines
  545. :group 'calendar)
  546. (defcustom org-mode-hook nil
  547. "Mode hook for Org mode, run after the mode was turned on."
  548. :group 'org
  549. :type 'hook)
  550. (defcustom org-load-hook nil
  551. "Hook that is run after org.el has been loaded."
  552. :group 'org
  553. :type 'hook)
  554. (defcustom org-log-buffer-setup-hook nil
  555. "Hook that is run after an Org log buffer is created."
  556. :group 'org
  557. :version "24.1"
  558. :type 'hook)
  559. (defvar org-modules) ; defined below
  560. (defvar org-modules-loaded nil
  561. "Have the modules been loaded already?")
  562. (defun org-load-modules-maybe (&optional force)
  563. "Load all extensions listed in `org-modules'."
  564. (when (or force (not org-modules-loaded))
  565. (dolist (ext org-modules)
  566. (condition-case nil (require ext)
  567. (error (message "Problems while trying to load feature `%s'" ext))))
  568. (setq org-modules-loaded t)))
  569. (defun org-set-modules (var value)
  570. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  571. (set var value)
  572. (when (featurep 'org)
  573. (org-load-modules-maybe 'force)
  574. (org-element-cache-reset 'all)))
  575. (defcustom org-modules '(ol-w3m ol-bbdb ol-bibtex ol-docview ol-gnus ol-info ol-irc ol-mhe ol-rmail ol-eww)
  576. "Modules that should always be loaded together with org.el.
  577. If a description starts with <C>, the file is not part of Emacs
  578. and loading it will require that you have downloaded and properly
  579. installed the Org mode distribution.
  580. You can also use this system to load external packages (i.e. neither Org
  581. core modules, nor modules from the CONTRIB directory). Just add symbols
  582. to the end of the list. If the package is called org-xyz.el, then you need
  583. to add the symbol `xyz', and the package must have a call to:
  584. (provide \\='org-xyz)
  585. For export specific modules, see also `org-export-backends'."
  586. :group 'org
  587. :set 'org-set-modules
  588. :version "26.1"
  589. :package-version '(Org . "9.2")
  590. :type
  591. '(set :greedy t
  592. (const :tag " bbdb: Links to BBDB entries" ol-bbdb)
  593. (const :tag " bibtex: Links to BibTeX entries" ol-bibtex)
  594. (const :tag " crypt: Encryption of subtrees" org-crypt)
  595. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  596. (const :tag " docview: Links to Docview buffers" ol-docview)
  597. (const :tag " eww: Store link to URL of Eww" ol-eww)
  598. (const :tag " gnus: Links to GNUS folders/messages" ol-gnus)
  599. (const :tag " habit: Track your consistency with habits" org-habit)
  600. (const :tag " id: Global IDs for identifying entries" org-id)
  601. (const :tag " info: Links to Info nodes" ol-info)
  602. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  603. (const :tag " irc: Links to IRC/ERC chat sessions" ol-irc)
  604. (const :tag " mhe: Links to MHE folders/messages" ol-mhe)
  605. (const :tag " mouse: Additional mouse support" org-mouse)
  606. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  607. (const :tag " rmail: Links to RMAIL folders/messages" ol-rmail)
  608. (const :tag " tempo: Fast completion for structures" org-tempo)
  609. (const :tag " w3m: Special cut/paste from w3m to Org mode." ol-w3m)
  610. (const :tag " eshell: Links to working directories in Eshell" ol-eshell)
  611. (const :tag "C annotate-file: Annotate a file with Org syntax" org-annotate-file)
  612. (const :tag "C bookmark: Links to bookmarks" ol-bookmark)
  613. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  614. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  615. (const :tag "C collector: Collect properties into tables" org-collector)
  616. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  617. (const :tag "C elisp-symbol: Links to emacs-lisp symbols" ol-elisp-symbol)
  618. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  619. (const :tag "C eval: Include command output as text" org-eval)
  620. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  621. (const :tag "C git-link: Links to specific file version" ol-git-link)
  622. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  623. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  624. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  625. (const :tag "C mac-iCal: Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  626. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  627. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  628. (const :tag "C man: Links to man pages in Org mode" ol-man)
  629. (const :tag "C mew: Links to Mew folders/messages" ol-mew)
  630. (const :tag "C notify: Notifications for Org mode" org-notify)
  631. (const :tag "C notmuch: Provide Org links to notmuch searches or messages" ol-notmuch)
  632. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  633. (const :tag "C registry: A registry for Org links" org-registry)
  634. (const :tag "C screen: Visit screen sessions through links" org-screen)
  635. (const :tag "C screenshot: Take and manage screenshots in Org files" org-screenshot)
  636. (const :tag "C secretary: Team management with Org" org-secretary)
  637. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  638. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  639. (const :tag "C track: Keep up with Org mode development" org-track)
  640. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  641. (const :tag "C vm: Links to VM folders/messages" ol-vm)
  642. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  643. (const :tag "C wl: Links to Wanderlust folders/messages" ol-wl)
  644. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  645. (defvar org-export-registered-backends) ; From ox.el.
  646. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  647. (declare-function org-export-backend-name "ox" (backend) t)
  648. (defcustom org-export-backends '(ascii html icalendar latex odt)
  649. "List of export back-ends that should be always available.
  650. If a description starts with <C>, the file is not part of Emacs
  651. and loading it will require that you have downloaded and properly
  652. installed the Org mode distribution.
  653. Unlike to `org-modules', libraries in this list will not be
  654. loaded along with Org, but only once the export framework is
  655. needed.
  656. This variable needs to be set before org.el is loaded. If you
  657. need to make a change while Emacs is running, use the customize
  658. interface or run the following code, where VAL stands for the new
  659. value of the variable, after updating it:
  660. (progn
  661. (setq org-export-registered-backends
  662. (cl-remove-if-not
  663. (lambda (backend)
  664. (let ((name (org-export-backend-name backend)))
  665. (or (memq name val)
  666. (catch \\='parentp
  667. (dolist (b val)
  668. (and (org-export-derived-backend-p b name)
  669. (throw \\='parentp t)))))))
  670. org-export-registered-backends))
  671. (let ((new-list (mapcar #\\='org-export-backend-name
  672. org-export-registered-backends)))
  673. (dolist (backend val)
  674. (cond
  675. ((not (load (format \"ox-%s\" backend) t t))
  676. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  677. backend))
  678. ((not (memq backend new-list)) (push backend new-list))))
  679. (set-default \\='org-export-backends new-list)))
  680. Adding a back-end to this list will also pull the back-end it
  681. depends on, if any."
  682. :group 'org
  683. :group 'org-export
  684. :version "26.1"
  685. :package-version '(Org . "9.0")
  686. :initialize 'custom-initialize-set
  687. :set (lambda (var val)
  688. (if (not (featurep 'ox)) (set-default var val)
  689. ;; Any back-end not required anymore (not present in VAL and not
  690. ;; a parent of any back-end in the new value) is removed from the
  691. ;; list of registered back-ends.
  692. (setq org-export-registered-backends
  693. (cl-remove-if-not
  694. (lambda (backend)
  695. (let ((name (org-export-backend-name backend)))
  696. (or (memq name val)
  697. (catch 'parentp
  698. (dolist (b val)
  699. (and (org-export-derived-backend-p b name)
  700. (throw 'parentp t)))))))
  701. org-export-registered-backends))
  702. ;; Now build NEW-LIST of both new back-ends and required
  703. ;; parents.
  704. (let ((new-list (mapcar #'org-export-backend-name
  705. org-export-registered-backends)))
  706. (dolist (backend val)
  707. (cond
  708. ((not (load (format "ox-%s" backend) t t))
  709. (message "Problems while trying to load export back-end `%s'"
  710. backend))
  711. ((not (memq backend new-list)) (push backend new-list))))
  712. ;; Set VAR to that list with fixed dependencies.
  713. (set-default var new-list))))
  714. :type '(set :greedy t
  715. (const :tag " ascii Export buffer to ASCII format" ascii)
  716. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  717. (const :tag " html Export buffer to HTML format" html)
  718. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  719. (const :tag " latex Export buffer to LaTeX format" latex)
  720. (const :tag " man Export buffer to MAN format" man)
  721. (const :tag " md Export buffer to Markdown format" md)
  722. (const :tag " odt Export buffer to ODT format" odt)
  723. (const :tag " org Export buffer to Org format" org)
  724. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  725. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  726. (const :tag "C deck Export buffer to deck.js presentations" deck)
  727. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  728. (const :tag "C groff Export buffer to Groff format" groff)
  729. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  730. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  731. (const :tag "C s5 Export buffer to s5 presentations" s5)
  732. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  733. (eval-after-load 'ox
  734. '(dolist (backend org-export-backends)
  735. (condition-case nil (require (intern (format "ox-%s" backend)))
  736. (error (message "Problems while trying to load export back-end `%s'"
  737. backend)))))
  738. (defcustom org-support-shift-select nil
  739. "Non-nil means make shift-cursor commands select text when possible.
  740. \\<org-mode-map>
  741. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  742. start selecting a region, or enlarge regions started in this way.
  743. In Org mode, in special contexts, these same keys are used for
  744. other purposes, important enough to compete with shift selection.
  745. Org tries to balance these needs by supporting `shift-select-mode'
  746. outside these special contexts, under control of this variable.
  747. The default of this variable is nil, to avoid confusing behavior. Shifted
  748. cursor keys will then execute Org commands in the following contexts:
  749. - on a headline, changing TODO state (left/right) and priority (up/down)
  750. - on a time stamp, changing the time
  751. - in a plain list item, changing the bullet type
  752. - in a property definition line, switching between allowed values
  753. - in the BEGIN line of a clock table (changing the time block).
  754. - in a table, moving the cell in the specified direction.
  755. Outside these contexts, the commands will throw an error.
  756. When this variable is t and the cursor is not in a special
  757. context, Org mode will support shift-selection for making and
  758. enlarging regions. To make this more effective, the bullet
  759. cycling will no longer happen anywhere in an item line, but only
  760. if the cursor is exactly on the bullet.
  761. If you set this variable to the symbol `always', then the keys
  762. will not be special in headlines, property lines, item lines, and
  763. table cells, to make shift selection work there as well. If this is
  764. what you want, you can use the following alternative commands:
  765. `\\[org-todo]' and `\\[org-priority]' \
  766. to change TODO state and priority,
  767. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  768. can be used to switch TODO sets,
  769. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  770. and properties can be edited by hand or in column view.
  771. However, when the cursor is on a timestamp, shift-cursor commands
  772. will still edit the time stamp - this is just too good to give up."
  773. :group 'org
  774. :type '(choice
  775. (const :tag "Never" nil)
  776. (const :tag "When outside special context" t)
  777. (const :tag "Everywhere except timestamps" always)))
  778. (defcustom org-loop-over-headlines-in-active-region t
  779. "Shall some commands act upon headlines in the active region?
  780. When set to t, some commands will be performed in all headlines
  781. within the active region.
  782. When set to `start-level', some commands will be performed in all
  783. headlines within the active region, provided that these headlines
  784. are of the same level than the first one.
  785. When set to a string, those commands will be performed on the
  786. matching headlines within the active region. Such string must be
  787. a tags/property/todo match as it is used in the agenda tags view.
  788. The list of commands is: `org-schedule', `org-deadline',
  789. `org-todo', `org-set-tags-command', `org-archive-subtree',
  790. `org-archive-set-tag', `org-toggle-archive-tag' and
  791. `org-archive-to-archive-sibling'. The archiving commands skip
  792. already archived entries.
  793. See `org-agenda-loop-over-headlines-in-active-region' for the
  794. equivalent option for agenda views."
  795. :type '(choice (const :tag "Don't loop" nil)
  796. (const :tag "All headlines in active region" t)
  797. (const :tag "In active region, headlines at the same level than the first one" start-level)
  798. (string :tag "Tags/Property/Todo matcher"))
  799. :version "27.1"
  800. :package-version "9.4"
  801. :group 'org-todo
  802. :group 'org-archive)
  803. (defcustom org-startup-folded t
  804. "Non-nil means entering Org mode will switch to OVERVIEW.
  805. This can also be configured on a per-file basis by adding one of
  806. the following lines anywhere in the buffer:
  807. #+STARTUP: fold (or `overview', this is equivalent)
  808. #+STARTUP: nofold (or `showall', this is equivalent)
  809. #+STARTUP: content
  810. #+STARTUP: showeverything
  811. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  812. to ignore this option when Org opens agenda files for the first
  813. time."
  814. :group 'org-startup
  815. :type '(choice
  816. (const :tag "nofold: show all" nil)
  817. (const :tag "fold: overview" t)
  818. (const :tag "content: all headlines" content)
  819. (const :tag "show everything, even drawers" showeverything)))
  820. (defcustom org-startup-truncated t
  821. "Non-nil means entering Org mode will set `truncate-lines'.
  822. This is useful since some lines containing links can be very long and
  823. uninteresting. Also tables look terrible when wrapped.
  824. The variable `org-startup-truncated' allows to configure
  825. truncation for Org mode different to the other modes that use the
  826. variable `truncate-lines' and as a shortcut instead of putting
  827. the variable `truncate-lines' into the `org-mode-hook'. If one
  828. wants to configure truncation for Org mode not statically but
  829. dynamically e.g. in a hook like `ediff-prepare-buffer-hook' then
  830. the variable `truncate-lines' has to be used because in such a
  831. case it is too late to set the variable `org-startup-truncated'."
  832. :group 'org-startup
  833. :type 'boolean)
  834. (defcustom org-startup-indented nil
  835. "Non-nil means turn on `org-indent-mode' on startup.
  836. This can also be configured on a per-file basis by adding one of
  837. the following lines anywhere in the buffer:
  838. #+STARTUP: indent
  839. #+STARTUP: noindent"
  840. :group 'org-structure
  841. :type '(choice
  842. (const :tag "Not" nil)
  843. (const :tag "Globally (slow on startup in large files)" t)))
  844. (defcustom org-startup-numeroted nil
  845. "Non-nil means turn on `org-num-mode' on startup.
  846. This can also be configured on a per-file basis by adding one of
  847. the following lines anywhere in the buffer:
  848. #+STARTUP: num
  849. #+STARTUP: nonum"
  850. :group 'org-structure
  851. :package-version '(Org . "9.4")
  852. :type '(choice
  853. (const :tag "Not" nil)
  854. (const :tag "Globally" t)))
  855. (defcustom org-use-sub-superscripts t
  856. "Non-nil means interpret \"_\" and \"^\" for display.
  857. If you want to control how Org exports those characters, see
  858. `org-export-with-sub-superscripts'.
  859. When this option is turned on, you can use TeX-like syntax for
  860. sub- and superscripts within the buffer. Several characters after
  861. \"_\" or \"^\" will be considered as a single item - so grouping
  862. with {} is normally not needed. For example, the following things
  863. will be parsed as single sub- or superscripts:
  864. 10^24 or 10^tau several digits will be considered 1 item.
  865. 10^-12 or 10^-tau a leading sign with digits or a word
  866. x^2-y^3 will be read as x^2 - y^3, because items are
  867. terminated by almost any nonword/nondigit char.
  868. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  869. Still, ambiguity is possible. So when in doubt, use {} to enclose
  870. the sub/superscript. If you set this variable to the symbol `{}',
  871. the braces are *required* in order to trigger interpretations as
  872. sub/superscript. This can be helpful in documents that need \"_\"
  873. frequently in plain text."
  874. :group 'org-startup
  875. :version "24.4"
  876. :package-version '(Org . "8.0")
  877. :type '(choice
  878. (const :tag "Always interpret" t)
  879. (const :tag "Only with braces" {})
  880. (const :tag "Never interpret" nil)))
  881. (defcustom org-startup-with-beamer-mode nil
  882. "Non-nil means turn on `org-beamer-mode' on startup.
  883. This can also be configured on a per-file basis by adding one of
  884. the following lines anywhere in the buffer:
  885. #+STARTUP: beamer"
  886. :group 'org-startup
  887. :version "24.1"
  888. :type 'boolean)
  889. (defcustom org-startup-align-all-tables nil
  890. "Non-nil means align all tables when visiting a file.
  891. This can also be configured on a per-file basis by adding one of
  892. the following lines anywhere in the buffer:
  893. #+STARTUP: align
  894. #+STARTUP: noalign"
  895. :group 'org-startup
  896. :type 'boolean)
  897. (defcustom org-startup-shrink-all-tables nil
  898. "Non-nil means shrink all table columns with a width cookie.
  899. This can also be configured on a per-file basis by adding one of
  900. the following lines anywhere in the buffer:
  901. #+STARTUP: shrink"
  902. :group 'org-startup
  903. :type 'boolean
  904. :version "27.1"
  905. :package-version '(Org . "9.2")
  906. :safe #'booleanp)
  907. (defcustom org-startup-with-inline-images nil
  908. "Non-nil means show inline images when loading a new Org file.
  909. This can also be configured on a per-file basis by adding one of
  910. the following lines anywhere in the buffer:
  911. #+STARTUP: inlineimages
  912. #+STARTUP: noinlineimages"
  913. :group 'org-startup
  914. :version "24.1"
  915. :type 'boolean)
  916. (defcustom org-startup-with-latex-preview nil
  917. "Non-nil means preview LaTeX fragments when loading a new Org file.
  918. This can also be configured on a per-file basis by adding one of
  919. the following lines anywhere in the buffer:
  920. #+STARTUP: latexpreview
  921. #+STARTUP: nolatexpreview"
  922. :group 'org-startup
  923. :version "24.4"
  924. :package-version '(Org . "8.0")
  925. :type 'boolean)
  926. (defcustom org-insert-mode-line-in-empty-file nil
  927. "Non-nil means insert the first line setting Org mode in empty files.
  928. When the function `org-mode' is called interactively in an empty file, this
  929. normally means that the file name does not automatically trigger Org mode.
  930. To ensure that the file will always be in Org mode in the future, a
  931. line enforcing Org mode will be inserted into the buffer, if this option
  932. has been set."
  933. :group 'org-startup
  934. :type 'boolean)
  935. (defcustom org-ellipsis nil
  936. "The ellipsis to use in the Org mode outline.
  937. When nil, just use the standard three dots. When a non-empty string,
  938. use that string instead.
  939. The change affects only Org mode (which will then use its own display table).
  940. Changing this requires executing `\\[org-mode]' in a buffer to become
  941. effective."
  942. :group 'org-startup
  943. :type '(choice (const :tag "Default" nil)
  944. (string :tag "String" :value "...#"))
  945. :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
  946. (defvar org-display-table nil
  947. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  948. (defcustom org-directory "~/org"
  949. "Directory with Org files.
  950. This is just a default location to look for Org files. There is no need
  951. at all to put your files into this directory. It is used in the
  952. following situations:
  953. 1. When a capture template specifies a target file that is not an
  954. absolute path. The path will then be interpreted relative to
  955. `org-directory'
  956. 2. When the value of variable `org-agenda-files' is a single file, any
  957. relative paths in this file will be taken as relative to
  958. `org-directory'."
  959. :group 'org-refile
  960. :group 'org-capture
  961. :type 'directory)
  962. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  963. "Default target for storing notes.
  964. Used as a fall back file for org-capture.el, for templates that
  965. do not specify a target file."
  966. :group 'org-refile
  967. :group 'org-capture
  968. :type 'file)
  969. (defcustom org-reverse-note-order nil
  970. "Non-nil means store new notes at the beginning of a file or entry.
  971. When nil, new notes will be filed to the end of a file or entry.
  972. This can also be a list with cons cells of regular expressions that
  973. are matched against file names, and values."
  974. :group 'org-capture
  975. :group 'org-refile
  976. :type '(choice
  977. (const :tag "Reverse always" t)
  978. (const :tag "Reverse never" nil)
  979. (repeat :tag "By file name regexp"
  980. (cons regexp boolean))))
  981. (defgroup org-keywords nil
  982. "Keywords in Org mode."
  983. :tag "Org Keywords"
  984. :group 'org)
  985. (defcustom org-closed-keep-when-no-todo nil
  986. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  987. :group 'org-todo
  988. :group 'org-keywords
  989. :version "24.4"
  990. :package-version '(Org . "8.0")
  991. :type 'boolean)
  992. (defgroup org-structure nil
  993. "Options concerning the general structure of Org files."
  994. :tag "Org Structure"
  995. :group 'org)
  996. (defgroup org-reveal-location nil
  997. "Options about how to make context of a location visible."
  998. :tag "Org Reveal Location"
  999. :group 'org-structure)
  1000. (defcustom org-show-context-detail '((agenda . local)
  1001. (bookmark-jump . lineage)
  1002. (isearch . lineage)
  1003. (default . ancestors))
  1004. "Alist between context and visibility span when revealing a location.
  1005. \\<org-mode-map>Some actions may move point into invisible
  1006. locations. As a consequence, Org always expose a neighborhood
  1007. around point. How much is shown depends on the initial action,
  1008. or context. Valid contexts are
  1009. agenda when exposing an entry from the agenda
  1010. org-goto when using the command `org-goto' (`\\[org-goto]')
  1011. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  1012. tags-tree when constructing a sparse tree based on tags matches
  1013. link-search when exposing search matches associated with a link
  1014. mark-goto when exposing the jump goal of a mark
  1015. bookmark-jump when exposing a bookmark location
  1016. isearch when exiting from an incremental search
  1017. default default for all contexts not set explicitly
  1018. Allowed visibility spans are
  1019. minimal show current headline; if point is not on headline,
  1020. also show entry
  1021. local show current headline, entry and next headline
  1022. ancestors show current headline and its direct ancestors; if
  1023. point is not on headline, also show entry
  1024. lineage show current headline, its direct ancestors and all
  1025. their children; if point is not on headline, also show
  1026. entry and first child
  1027. tree show current headline, its direct ancestors and all
  1028. their children; if point is not on headline, also show
  1029. entry and all children
  1030. canonical show current headline, its direct ancestors along with
  1031. their entries and children; if point is not located on
  1032. the headline, also show current entry and all children
  1033. As special cases, a nil or t value means show all contexts in
  1034. `minimal' or `canonical' view, respectively.
  1035. Some views can make displayed information very compact, but also
  1036. make it harder to edit the location of the match. In such
  1037. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  1038. more context."
  1039. :group 'org-reveal-location
  1040. :version "26.1"
  1041. :package-version '(Org . "9.0")
  1042. :type '(choice
  1043. (const :tag "Canonical" t)
  1044. (const :tag "Minimal" nil)
  1045. (repeat :greedy t :tag "Individual contexts"
  1046. (cons
  1047. (choice :tag "Context"
  1048. (const agenda)
  1049. (const org-goto)
  1050. (const occur-tree)
  1051. (const tags-tree)
  1052. (const link-search)
  1053. (const mark-goto)
  1054. (const bookmark-jump)
  1055. (const isearch)
  1056. (const default))
  1057. (choice :tag "Detail level"
  1058. (const minimal)
  1059. (const local)
  1060. (const ancestors)
  1061. (const lineage)
  1062. (const tree)
  1063. (const canonical))))))
  1064. (defcustom org-indirect-buffer-display 'other-window
  1065. "How should indirect tree buffers be displayed?
  1066. This applies to indirect buffers created with the commands
  1067. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1068. Valid values are:
  1069. current-window Display in the current window
  1070. other-window Just display in another window.
  1071. dedicated-frame Create one new frame, and re-use it each time.
  1072. new-frame Make a new frame each time. Note that in this case
  1073. previously-made indirect buffers are kept, and you need to
  1074. kill these buffers yourself."
  1075. :group 'org-structure
  1076. :group 'org-agenda-windows
  1077. :type '(choice
  1078. (const :tag "In current window" current-window)
  1079. (const :tag "In current frame, other window" other-window)
  1080. (const :tag "Each time a new frame" new-frame)
  1081. (const :tag "One dedicated frame" dedicated-frame)))
  1082. (defconst org-file-apps-gnu
  1083. '((remote . emacs)
  1084. (system . mailcap)
  1085. (t . mailcap))
  1086. "Default file applications on a UNIX or GNU/Linux system.
  1087. See `org-file-apps'.")
  1088. (defconst org-file-apps-macos
  1089. '((remote . emacs)
  1090. (system . "open %s")
  1091. ("ps.gz" . "gv %s")
  1092. ("eps.gz" . "gv %s")
  1093. ("dvi" . "xdvi %s")
  1094. ("fig" . "xfig %s")
  1095. (t . "open %s"))
  1096. "Default file applications on a macOS system.
  1097. The system \"open\" is known as a default, but we use X11 applications
  1098. for some files for which the OS does not have a good default.
  1099. See `org-file-apps'.")
  1100. (defconst org-file-apps-windowsnt
  1101. (list '(remote . emacs)
  1102. (cons 'system (lambda (file _path)
  1103. (with-no-warnings (w32-shell-execute "open" file))))
  1104. (cons t (lambda (file _path)
  1105. (with-no-warnings (w32-shell-execute "open" file)))))
  1106. "Default file applications on a Windows NT system.
  1107. The system \"open\" is used for most files.
  1108. See `org-file-apps'.")
  1109. (defcustom org-file-apps
  1110. '((auto-mode . emacs)
  1111. (directory . emacs)
  1112. ("\\.mm\\'" . default)
  1113. ("\\.x?html?\\'" . default)
  1114. ("\\.pdf\\'" . default))
  1115. "Applications for opening `file:path' items in a document.
  1116. \\<org-mode-map>
  1117. Org mode uses system defaults for different file types, but you
  1118. can use this variable to set the application for a given file
  1119. extension. The entries in this list are cons cells where the car
  1120. identifies files and the cdr the corresponding command.
  1121. Possible values for the file identifier are:
  1122. \"string\" A string as a file identifier can be interpreted in different
  1123. ways, depending on its contents:
  1124. - Alphanumeric characters only:
  1125. Match links with this file extension.
  1126. Example: (\"pdf\" . \"evince %s\")
  1127. to open PDFs with evince.
  1128. - Regular expression: Match links where the
  1129. filename matches the regexp. If you want to
  1130. use groups here, use shy groups.
  1131. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1132. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1133. to open *.html and *.xhtml with firefox.
  1134. - Regular expression which contains (non-shy) groups:
  1135. Match links where the whole link, including \"::\", and
  1136. anything after that, matches the regexp.
  1137. In a custom command string, %1, %2, etc. are replaced with
  1138. the parts of the link that were matched by the groups.
  1139. For backwards compatibility, if a command string is given
  1140. that does not use any of the group matches, this case is
  1141. handled identically to the second one (i.e. match against
  1142. file name only).
  1143. In a custom function, you can access the group matches with
  1144. (match-string n link).
  1145. Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
  1146. \"evince -p %1 %s\")
  1147. to open [[file:document.pdf::5]] with evince at page 5.
  1148. `directory' Matches a directory
  1149. `remote' Matches a remote file, accessible through tramp or efs.
  1150. Remote files most likely should be visited through Emacs
  1151. because external applications cannot handle such paths.
  1152. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1153. so all files Emacs knows how to handle. Using this with
  1154. command `emacs' will open most files in Emacs. Beware that this
  1155. will also open html files inside Emacs, unless you add
  1156. (\"html\" . default) to the list as well.
  1157. `system' The system command to open files, like `open' on Windows
  1158. and macOS, and mailcap under GNU/Linux. This is the command
  1159. that will be selected if you call `org-open-at-point' with a
  1160. double prefix argument (`\\[universal-argument] \
  1161. \\[universal-argument] \\[org-open-at-point]').
  1162. t Default for files not matched by any of the other options.
  1163. Possible values for the command are:
  1164. `emacs' The file will be visited by the current Emacs process.
  1165. `default' Use the default application for this file type, which is the
  1166. association for t in the list, most likely in the system-specific
  1167. part. This can be used to overrule an unwanted setting in the
  1168. system-specific variable.
  1169. `system' Use the system command for opening files, like \"open\".
  1170. This command is specified by the entry whose car is `system'.
  1171. Most likely, the system-specific version of this variable
  1172. does define this command, but you can overrule/replace it
  1173. here.
  1174. `mailcap' Use command specified in the mailcaps.
  1175. string A command to be executed by a shell; %s will be replaced
  1176. by the path to the file.
  1177. function A Lisp function, which will be called with two arguments:
  1178. the file path and the original link string, without the
  1179. \"file:\" prefix.
  1180. For more examples, see the system specific constants
  1181. `org-file-apps-macos'
  1182. `org-file-apps-windowsnt'
  1183. `org-file-apps-gnu'."
  1184. :group 'org
  1185. :package-version '(Org . "9.4")
  1186. :type '(repeat
  1187. (cons (choice :value ""
  1188. (string :tag "Extension")
  1189. (const :tag "System command to open files" system)
  1190. (const :tag "Default for unrecognized files" t)
  1191. (const :tag "Remote file" remote)
  1192. (const :tag "Links to a directory" directory)
  1193. (const :tag "Any files that have Emacs modes"
  1194. auto-mode))
  1195. (choice :value ""
  1196. (const :tag "Visit with Emacs" emacs)
  1197. (const :tag "Use default" default)
  1198. (const :tag "Use the system command" system)
  1199. (string :tag "Command")
  1200. (function :tag "Function")))))
  1201. (defcustom org-open-non-existing-files nil
  1202. "Non-nil means `org-open-file' opens non-existing files.
  1203. When nil, an error is thrown.
  1204. This variable applies only to external applications because they
  1205. might choke on non-existing files. If the link is to a file that
  1206. will be opened in Emacs, the variable is ignored."
  1207. :group 'org
  1208. :type 'boolean
  1209. :safe #'booleanp)
  1210. (defcustom org-open-directory-means-index-dot-org nil
  1211. "When non-nil a link to a directory really means to \"index.org\".
  1212. When nil, following a directory link runs Dired or opens
  1213. a finder/explorer window on that directory."
  1214. :group 'org
  1215. :type 'boolean
  1216. :safe #'booleanp)
  1217. (defcustom org-bookmark-names-plist
  1218. '(:last-capture "org-capture-last-stored"
  1219. :last-refile "org-refile-last-stored"
  1220. :last-capture-marker "org-capture-last-stored-marker")
  1221. "Names for bookmarks automatically set by some Org commands.
  1222. This can provide strings as names for a number of bookmarks Org sets
  1223. automatically. The following keys are currently implemented:
  1224. :last-capture
  1225. :last-capture-marker
  1226. :last-refile
  1227. When a key does not show up in the property list, the corresponding bookmark
  1228. is not set."
  1229. :group 'org-structure
  1230. :type 'plist)
  1231. (defgroup org-cycle nil
  1232. "Options concerning visibility cycling in Org mode."
  1233. :tag "Org Cycle"
  1234. :group 'org-structure)
  1235. (defcustom org-cycle-skip-children-state-if-no-children t
  1236. "Non-nil means skip CHILDREN state in entries that don't have any."
  1237. :group 'org-cycle
  1238. :type 'boolean)
  1239. (defcustom org-cycle-max-level nil
  1240. "Maximum level which should still be subject to visibility cycling.
  1241. Levels higher than this will, for cycling, be treated as text, not a headline.
  1242. When `org-odd-levels-only' is set, a value of N in this variable actually
  1243. means 2N-1 stars as the limiting headline.
  1244. When nil, cycle all levels.
  1245. Note that the limiting level of cycling is also influenced by
  1246. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1247. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1248. than its value."
  1249. :group 'org-cycle
  1250. :type '(choice
  1251. (const :tag "No limit" nil)
  1252. (integer :tag "Maximum level")))
  1253. (defcustom org-hide-block-startup nil
  1254. "Non-nil means entering Org mode will fold all blocks.
  1255. This can also be set in on a per-file basis with
  1256. #+STARTUP: hideblocks
  1257. #+STARTUP: showblocks"
  1258. :group 'org-startup
  1259. :group 'org-cycle
  1260. :type 'boolean)
  1261. (defcustom org-cycle-global-at-bob nil
  1262. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1263. This makes it possible to do global cycling without having to use `S-TAB'
  1264. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1265. line of the buffer
  1266. must not be a headline -- it may be empty or some other text.
  1267. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1268. sure the cursor stays at the beginning of the buffer.
  1269. When this option is nil, don't do anything special at the beginning of
  1270. the buffer."
  1271. :group 'org-cycle
  1272. :type 'boolean)
  1273. (defcustom org-cycle-level-after-item/entry-creation t
  1274. "Non-nil means cycle entry level or item indentation in new empty entries.
  1275. When the cursor is at the end of an empty headline, i.e., with only stars
  1276. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1277. and then all possible ancestor states, before returning to the original state.
  1278. This makes data entry extremely fast: M-RET to create a new headline,
  1279. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1280. When the cursor is at the end of an empty plain list item, one TAB will
  1281. make it a subitem, two or more tabs will back up to make this an item
  1282. higher up in the item hierarchy."
  1283. :group 'org-cycle
  1284. :type 'boolean)
  1285. (defcustom org-cycle-emulate-tab t
  1286. "Where should `org-cycle' emulate TAB.
  1287. nil Never
  1288. white Only in completely white lines
  1289. whitestart Only at the beginning of lines, before the first non-white char
  1290. t Everywhere except in headlines
  1291. exc-hl-bol Everywhere except at the start of a headline
  1292. If TAB is used in a place where it does not emulate TAB, the current subtree
  1293. visibility is cycled."
  1294. :group 'org-cycle
  1295. :type '(choice (const :tag "Never" nil)
  1296. (const :tag "Only in completely white lines" white)
  1297. (const :tag "Before first char in a line" whitestart)
  1298. (const :tag "Everywhere except in headlines" t)
  1299. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1300. (defcustom org-cycle-separator-lines 2
  1301. "Number of empty lines needed to keep an empty line between collapsed trees.
  1302. If you leave an empty line between the end of a subtree and the following
  1303. headline, this empty line is hidden when the subtree is folded.
  1304. Org mode will leave (exactly) one empty line visible if the number of
  1305. empty lines is equal or larger to the number given in this variable.
  1306. So the default 2 means at least 2 empty lines after the end of a subtree
  1307. are needed to produce free space between a collapsed subtree and the
  1308. following headline.
  1309. If the number is negative, and the number of empty lines is at least -N,
  1310. all empty lines are shown.
  1311. Special case: when 0, never leave empty lines in collapsed view."
  1312. :group 'org-cycle
  1313. :type 'integer)
  1314. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1315. (defcustom org-pre-cycle-hook nil
  1316. "Hook that is run before visibility cycling is happening.
  1317. The function(s) in this hook must accept a single argument which indicates
  1318. the new state that will be set right after running this hook. The
  1319. argument is a symbol. Before a global state change, it can have the values
  1320. `overview', `content', or `all'. Before a local state change, it can have
  1321. the values `folded', `children', or `subtree'."
  1322. :group 'org-cycle
  1323. :type 'hook)
  1324. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1325. org-cycle-show-empty-lines
  1326. org-optimize-window-after-visibility-change)
  1327. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1328. The function(s) in this hook must accept a single argument which indicates
  1329. the new state that was set by the most recent `org-cycle' command. The
  1330. argument is a symbol. After a global state change, it can have the values
  1331. `overview', `contents', or `all'. After a local state change, it can have
  1332. the values `folded', `children', or `subtree'."
  1333. :group 'org-cycle
  1334. :type 'hook
  1335. :version "26.1"
  1336. :package-version '(Org . "8.3"))
  1337. (defgroup org-edit-structure nil
  1338. "Options concerning structure editing in Org mode."
  1339. :tag "Org Edit Structure"
  1340. :group 'org-structure)
  1341. (defcustom org-odd-levels-only nil
  1342. "Non-nil means skip even levels and only use odd levels for the outline.
  1343. This has the effect that two stars are being added/taken away in
  1344. promotion/demotion commands. It also influences how levels are
  1345. handled by the exporters.
  1346. Changing it requires restart of `font-lock-mode' to become effective
  1347. for fontification also in regions already fontified.
  1348. You may also set this on a per-file basis by adding one of the following
  1349. lines to the buffer:
  1350. #+STARTUP: odd
  1351. #+STARTUP: oddeven"
  1352. :group 'org-edit-structure
  1353. :group 'org-appearance
  1354. :type 'boolean)
  1355. (defcustom org-adapt-indentation t
  1356. "Non-nil means adapt indentation to outline node level.
  1357. When this variable is set to t, Org assumes that you write
  1358. outlines by indenting text in each node to align with the
  1359. headline (after the stars).
  1360. When this variable is set to 'headline-data, only adapt the
  1361. indentation of the data lines right below the headline, such as
  1362. planning/clock lines and property/logbook drawers.
  1363. The following issues are influenced by this variable:
  1364. - The indentation is increased by one space in a demotion
  1365. command, and decreased by one in a promotion command. However,
  1366. in the latter case, if shifting some line in the entry body
  1367. would alter document structure (e.g., insert a new headline),
  1368. indentation is not changed at all.
  1369. - Property drawers and planning information is inserted indented
  1370. when this variable is set. When nil, they will not be indented.
  1371. - TAB indents a line relative to current level. The lines below
  1372. a headline will be indented when this variable is set to t.
  1373. Note that this is all about true indentation, by adding and
  1374. removing space characters. See also \"org-indent.el\" which does
  1375. level-dependent indentation in a virtual way, i.e. at display
  1376. time in Emacs."
  1377. :group 'org-edit-structure
  1378. :type '(choice
  1379. (const :tag "Adapt indentation for all lines" t)
  1380. (const :tag "Adapt indentation for headline data lines"
  1381. 'headline-data)
  1382. (const :tag "Do not adapt indentation at all" nil))
  1383. :safe #'booleanp)
  1384. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1385. (defcustom org-special-ctrl-a/e nil
  1386. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1387. When t, `C-a' will bring back the cursor to the beginning of the
  1388. headline text, i.e. after the stars and after a possible TODO
  1389. keyword. In an item, this will be the position after bullet and
  1390. check-box, if any. When the cursor is already at that position,
  1391. another `C-a' will bring it to the beginning of the line.
  1392. `C-e' will jump to the end of the headline, ignoring the presence
  1393. of tags in the headline. A second `C-e' will then jump to the
  1394. true end of the line, after any tags. This also means that, when
  1395. this variable is non-nil, `C-e' also will never jump beyond the
  1396. end of the heading of a folded section, i.e. not after the
  1397. ellipses.
  1398. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1399. normally, going to the true line boundary first. Only a directly
  1400. following, identical keypress will bring the cursor to the
  1401. special positions.
  1402. This may also be a cons cell where the behavior for `C-a' and
  1403. `C-e' is set separately."
  1404. :group 'org-edit-structure
  1405. :type '(choice
  1406. (const :tag "off" nil)
  1407. (const :tag "on: after stars/bullet and before tags first" t)
  1408. (const :tag "reversed: true line boundary first" reversed)
  1409. (cons :tag "Set C-a and C-e separately"
  1410. (choice :tag "Special C-a"
  1411. (const :tag "off" nil)
  1412. (const :tag "on: after stars/bullet first" t)
  1413. (const :tag "reversed: before stars/bullet first" reversed))
  1414. (choice :tag "Special C-e"
  1415. (const :tag "off" nil)
  1416. (const :tag "on: before tags first" t)
  1417. (const :tag "reversed: after tags first" reversed)))))
  1418. (defcustom org-special-ctrl-k nil
  1419. "Non-nil means `C-k' will behave specially in headlines.
  1420. When nil, `C-k' will call the default `kill-line' command.
  1421. When t, the following will happen while the cursor is in the headline:
  1422. - When at the beginning of a headline, kill the entire subtree.
  1423. - When in the middle of the headline text, kill the text up to the tags.
  1424. - When after the headline text and before the tags, kill all the tags."
  1425. :group 'org-edit-structure
  1426. :type 'boolean)
  1427. (defcustom org-ctrl-k-protect-subtree nil
  1428. "Non-nil means, do not delete a hidden subtree with C-k.
  1429. When set to the symbol `error', simply throw an error when C-k is
  1430. used to kill (part-of) a headline that has hidden text behind it.
  1431. Any other non-nil value will result in a query to the user, if it is
  1432. OK to kill that hidden subtree. When nil, kill without remorse."
  1433. :group 'org-edit-structure
  1434. :version "24.1"
  1435. :type '(choice
  1436. (const :tag "Do not protect hidden subtrees" nil)
  1437. (const :tag "Protect hidden subtrees with a security query" t)
  1438. (const :tag "Never kill a hidden subtree with C-k" error)))
  1439. (defcustom org-special-ctrl-o t
  1440. "Non-nil means, make `C-o' insert a row in tables."
  1441. :group 'org-edit-structure
  1442. :type 'boolean)
  1443. (defcustom org-catch-invisible-edits nil
  1444. "Check if in invisible region before inserting or deleting a character.
  1445. Valid values are:
  1446. nil Do not check, so just do invisible edits.
  1447. error Throw an error and do nothing.
  1448. show Make point visible, and do the requested edit.
  1449. show-and-error Make point visible, then throw an error and abort the edit.
  1450. smart Make point visible, and do insertion/deletion if it is
  1451. adjacent to visible text and the change feels predictable.
  1452. Never delete a previously invisible character or add in the
  1453. middle or right after an invisible region. Basically, this
  1454. allows insertion and backward-delete right before ellipses.
  1455. FIXME: maybe in this case we should not even show?"
  1456. :group 'org-edit-structure
  1457. :version "24.1"
  1458. :type '(choice
  1459. (const :tag "Do not check" nil)
  1460. (const :tag "Throw error when trying to edit" error)
  1461. (const :tag "Unhide, but do not do the edit" show-and-error)
  1462. (const :tag "Show invisible part and do the edit" show)
  1463. (const :tag "Be smart and do the right thing" smart)))
  1464. (defcustom org-yank-folded-subtrees t
  1465. "Non-nil means when yanking subtrees, fold them.
  1466. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1467. it starts with a heading and all other headings in it are either children
  1468. or siblings, then fold all the subtrees. However, do this only if no
  1469. text after the yank would be swallowed into a folded tree by this action."
  1470. :group 'org-edit-structure
  1471. :type 'boolean)
  1472. (defcustom org-yank-adjusted-subtrees nil
  1473. "Non-nil means when yanking subtrees, adjust the level.
  1474. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1475. this function for details."
  1476. :group 'org-edit-structure
  1477. :type 'boolean)
  1478. (defcustom org-M-RET-may-split-line '((default . t))
  1479. "Non-nil means M-RET will split the line at the cursor position.
  1480. When nil, it will go to the end of the line before making a
  1481. new line.
  1482. You may also set this option in a different way for different
  1483. contexts. Valid contexts are:
  1484. headline when creating a new headline
  1485. item when creating a new item
  1486. table in a table field
  1487. default the value to be used for all contexts not explicitly
  1488. customized"
  1489. :group 'org-structure
  1490. :group 'org-table
  1491. :type '(choice
  1492. (const :tag "Always" t)
  1493. (const :tag "Never" nil)
  1494. (repeat :greedy t :tag "Individual contexts"
  1495. (cons
  1496. (choice :tag "Context"
  1497. (const headline)
  1498. (const item)
  1499. (const table)
  1500. (const default))
  1501. (boolean)))))
  1502. (defcustom org-insert-heading-respect-content nil
  1503. "Non-nil means insert new headings after the current subtree.
  1504. \\<org-mode-map>
  1505. When nil, the new heading is created directly after the current line.
  1506. The commands `\\[org-insert-heading-respect-content]' and \
  1507. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1508. for the duration of the command."
  1509. :group 'org-structure
  1510. :type 'boolean)
  1511. (defcustom org-blank-before-new-entry '((heading . auto)
  1512. (plain-list-item . auto))
  1513. "Should `org-insert-heading' leave a blank line before new heading/item?
  1514. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1515. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1516. which case Org will look at the surrounding headings/items and try to
  1517. make an intelligent decision whether to insert a blank line or not."
  1518. :group 'org-edit-structure
  1519. :type '(list
  1520. (cons (const heading)
  1521. (choice (const :tag "Never" nil)
  1522. (const :tag "Always" t)
  1523. (const :tag "Auto" auto)))
  1524. (cons (const plain-list-item)
  1525. (choice (const :tag "Never" nil)
  1526. (const :tag "Always" t)
  1527. (const :tag "Auto" auto)))))
  1528. (defcustom org-insert-heading-hook nil
  1529. "Hook being run after inserting a new heading."
  1530. :group 'org-edit-structure
  1531. :type 'hook)
  1532. (defgroup org-sparse-trees nil
  1533. "Options concerning sparse trees in Org mode."
  1534. :tag "Org Sparse Trees"
  1535. :group 'org-structure)
  1536. (defcustom org-highlight-sparse-tree-matches t
  1537. "Non-nil means highlight all matches that define a sparse tree.
  1538. The highlights will automatically disappear the next time the buffer is
  1539. changed by an edit command."
  1540. :group 'org-sparse-trees
  1541. :type 'boolean)
  1542. (defcustom org-remove-highlights-with-change t
  1543. "Non-nil means any change to the buffer will remove temporary highlights.
  1544. \\<org-mode-map>\
  1545. Such highlights are created by `org-occur' and `org-clock-display'.
  1546. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1547. to get rid of the highlights.
  1548. The highlights created by `org-latex-preview' always need
  1549. `\\[org-latex-preview]' to be removed."
  1550. :group 'org-sparse-trees
  1551. :group 'org-time
  1552. :type 'boolean)
  1553. (defcustom org-occur-case-fold-search t
  1554. "Non-nil means `org-occur' should be case-insensitive.
  1555. If set to `smart' the search will be case-insensitive only if it
  1556. doesn't specify any upper case character."
  1557. :group 'org-sparse-trees
  1558. :version "26.1"
  1559. :type '(choice
  1560. (const :tag "Case-sensitive" nil)
  1561. (const :tag "Case-insensitive" t)
  1562. (const :tag "Case-insensitive for lower case searches only" smart)))
  1563. (defcustom org-occur-hook '(org-first-headline-recenter)
  1564. "Hook that is run after `org-occur' has constructed a sparse tree.
  1565. This can be used to recenter the window to show as much of the structure
  1566. as possible."
  1567. :group 'org-sparse-trees
  1568. :type 'hook)
  1569. (defcustom org-self-insert-cluster-for-undo nil
  1570. "Non-nil means cluster self-insert commands for undo when possible.
  1571. If this is set, then, like in the Emacs command loop, 20 consecutive
  1572. characters will be undone together.
  1573. This is configurable, because there is some impact on typing performance."
  1574. :group 'org-table
  1575. :type 'boolean)
  1576. (defvaralias 'org-activate-links 'org-highlight-links)
  1577. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1578. "Types of links that should be highlighted in Org files.
  1579. This is a list of symbols, each one of them leading to the
  1580. highlighting of a certain link type.
  1581. You can still open links that are not highlighted.
  1582. In principle, it does not hurt to turn on highlighting for all
  1583. link types. There may be a small gain when turning off unused
  1584. link types. The types are:
  1585. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1586. angle Links in angular brackets that may contain whitespace like
  1587. <bbdb:Carsten Dominik>.
  1588. plain Plain links in normal text, no whitespace, like http://google.com.
  1589. radio Text that is matched by a radio target, see manual for details.
  1590. tag Tag settings in a headline (link to tag search).
  1591. date Time stamps (link to calendar).
  1592. footnote Footnote labels.
  1593. If you set this variable during an Emacs session, use `org-mode-restart'
  1594. in the Org buffer so that the change takes effect."
  1595. :group 'org-appearance
  1596. :type '(set :greedy t
  1597. (const :tag "Double bracket links" bracket)
  1598. (const :tag "Angular bracket links" angle)
  1599. (const :tag "Plain text links" plain)
  1600. (const :tag "Radio target matches" radio)
  1601. (const :tag "Tags" tag)
  1602. (const :tag "Timestamps" date)
  1603. (const :tag "Footnotes" footnote)))
  1604. (defcustom org-mark-ring-length 4
  1605. "Number of different positions to be recorded in the ring.
  1606. Changing this requires a restart of Emacs to work correctly."
  1607. :group 'org-link-follow
  1608. :type 'integer)
  1609. (defgroup org-todo nil
  1610. "Options concerning TODO items in Org mode."
  1611. :tag "Org TODO"
  1612. :group 'org)
  1613. (defgroup org-progress nil
  1614. "Options concerning Progress logging in Org mode."
  1615. :tag "Org Progress"
  1616. :group 'org-time)
  1617. (defvar org-todo-interpretation-widgets
  1618. '((:tag "Sequence (cycling hits every state)" sequence)
  1619. (:tag "Type (cycling directly to DONE)" type))
  1620. "The available interpretation symbols for customizing `org-todo-keywords'.
  1621. Interested libraries should add to this list.")
  1622. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  1623. "List of TODO entry keyword sequences and their interpretation.
  1624. \\<org-mode-map>This is a list of sequences.
  1625. Each sequence starts with a symbol, either `sequence' or `type',
  1626. indicating if the keywords should be interpreted as a sequence of
  1627. action steps, or as different types of TODO items. The first
  1628. keywords are states requiring action - these states will select a headline
  1629. for inclusion into the global TODO list Org produces. If one of the
  1630. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  1631. signify that no further action is necessary. If \"|\" is not found,
  1632. the last keyword is treated as the only DONE state of the sequence.
  1633. The command `\\[org-todo]' cycles an entry through these states, and one
  1634. additional state where no keyword is present. For details about this
  1635. cycling, see the manual.
  1636. TODO keywords and interpretation can also be set on a per-file basis with
  1637. the special #+SEQ_TODO and #+TYP_TODO lines.
  1638. Each keyword can optionally specify a character for fast state selection
  1639. \(in combination with the variable `org-use-fast-todo-selection')
  1640. and specifiers for state change logging, using the same syntax that
  1641. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  1642. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  1643. indicates to record a time stamp each time this state is selected.
  1644. Each keyword may also specify if a timestamp or a note should be
  1645. recorded when entering or leaving the state, by adding additional
  1646. characters in the parenthesis after the keyword. This looks like this:
  1647. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  1648. record only the time of the state change. With X and Y being either
  1649. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  1650. Y when leaving the state if and only if the *target* state does not
  1651. define X. You may omit any of the fast-selection key or X or /Y,
  1652. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  1653. For backward compatibility, this variable may also be just a list
  1654. of keywords. In this case the interpretation (sequence or type) will be
  1655. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  1656. :group 'org-todo
  1657. :group 'org-keywords
  1658. :type '(choice
  1659. (repeat :tag "Old syntax, just keywords"
  1660. (string :tag "Keyword"))
  1661. (repeat :tag "New syntax"
  1662. (cons
  1663. (choice
  1664. :tag "Interpretation"
  1665. ;;Quick and dirty way to see
  1666. ;;`org-todo-interpretations'. This takes the
  1667. ;;place of item arguments
  1668. :convert-widget
  1669. (lambda (widget)
  1670. (widget-put widget
  1671. :args (mapcar
  1672. (lambda (x)
  1673. (widget-convert
  1674. (cons 'const x)))
  1675. org-todo-interpretation-widgets))
  1676. widget))
  1677. (repeat
  1678. (string :tag "Keyword"))))))
  1679. (defvar-local org-todo-keywords-1 nil
  1680. "All TODO and DONE keywords active in a buffer.")
  1681. (defvar org-todo-keywords-for-agenda nil)
  1682. (defvar org-done-keywords-for-agenda nil)
  1683. (defvar org-todo-keyword-alist-for-agenda nil)
  1684. (defvar org-tag-alist-for-agenda nil
  1685. "Alist of all tags from all agenda files.")
  1686. (defvar org-tag-groups-alist-for-agenda nil
  1687. "Alist of all groups tags from all current agenda files.")
  1688. (defvar-local org-tag-groups-alist nil)
  1689. (defvar org-agenda-contributing-files nil)
  1690. (defvar-local org-current-tag-alist nil
  1691. "Alist of all tag groups in current buffer.
  1692. This variable takes into consideration `org-tag-alist',
  1693. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  1694. (defvar-local org-not-done-keywords nil)
  1695. (defvar-local org-done-keywords nil)
  1696. (defvar-local org-todo-heads nil)
  1697. (defvar-local org-todo-sets nil)
  1698. (defvar-local org-todo-log-states nil)
  1699. (defvar-local org-todo-kwd-alist nil)
  1700. (defvar-local org-todo-key-alist nil)
  1701. (defvar-local org-todo-key-trigger nil)
  1702. (defcustom org-todo-interpretation 'sequence
  1703. "Controls how TODO keywords are interpreted.
  1704. This variable is in principle obsolete and is only used for
  1705. backward compatibility, if the interpretation of todo keywords is
  1706. not given already in `org-todo-keywords'. See that variable for
  1707. more information."
  1708. :group 'org-todo
  1709. :group 'org-keywords
  1710. :type '(choice (const sequence)
  1711. (const type)))
  1712. (defcustom org-use-fast-todo-selection 'auto
  1713. "\\<org-mode-map>\
  1714. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  1715. This variable describes if and under what circumstances the cycling
  1716. mechanism for TODO keywords will be replaced by a single-key, direct
  1717. selection scheme, where the choices are displayed in a little window.
  1718. When nil, fast selection is never used. This means that the command
  1719. will always switch to the next state.
  1720. When it is the symbol `auto', fast selection is whenever selection
  1721. keys have been defined.
  1722. `expert' is like `auto', but no special window with the keyword
  1723. will be shown, choices will only be listed in the prompt.
  1724. In all cases, the special interface is only used if access keys have
  1725. actually been assigned by the user, i.e. if keywords in the configuration
  1726. are followed by a letter in parenthesis, like TODO(t)."
  1727. :group 'org-todo
  1728. :set (lambda (var val)
  1729. (cond
  1730. ((eq var t) (set var 'auto))
  1731. ((eq var 'prefix) (set var nil))
  1732. (t (set var val))))
  1733. :type '(choice
  1734. (const :tag "Never" nil)
  1735. (const :tag "Automatically, when key letter have been defined" auto)
  1736. (const :tag "Automatically, but don't show the selection window" expert)))
  1737. (defcustom org-provide-todo-statistics t
  1738. "Non-nil means update todo statistics after insert and toggle.
  1739. ALL-HEADLINES means update todo statistics by including headlines
  1740. with no TODO keyword as well, counting them as not done.
  1741. A list of TODO keywords means the same, but skip keywords that are
  1742. not in this list.
  1743. When set to a list of two lists, the first list contains keywords
  1744. to consider as TODO keywords, the second list contains keywords
  1745. to consider as DONE keywords.
  1746. When this is set, todo statistics is updated in the parent of the
  1747. current entry each time a todo state is changed."
  1748. :group 'org-todo
  1749. :type '(choice
  1750. (const :tag "Yes, only for TODO entries" t)
  1751. (const :tag "Yes, including all entries" all-headlines)
  1752. (repeat :tag "Yes, for TODOs in this list"
  1753. (string :tag "TODO keyword"))
  1754. (list :tag "Yes, for TODOs and DONEs in these lists"
  1755. (repeat (string :tag "TODO keyword"))
  1756. (repeat (string :tag "DONE keyword")))
  1757. (other :tag "No TODO statistics" nil)))
  1758. (defcustom org-hierarchical-todo-statistics t
  1759. "Non-nil means TODO statistics covers just direct children.
  1760. When nil, all entries in the subtree are considered.
  1761. This has only an effect if `org-provide-todo-statistics' is set.
  1762. To set this to nil for only a single subtree, use a COOKIE_DATA
  1763. property and include the word \"recursive\" into the value."
  1764. :group 'org-todo
  1765. :type 'boolean)
  1766. (defcustom org-after-todo-state-change-hook nil
  1767. "Hook which is run after the state of a TODO item was changed.
  1768. The new state (a string with a TODO keyword, or nil) is available in the
  1769. Lisp variable `org-state'."
  1770. :group 'org-todo
  1771. :type 'hook)
  1772. (defvar org-blocker-hook nil
  1773. "Hook for functions that are allowed to block a state change.
  1774. Functions in this hook should not modify the buffer.
  1775. Each function gets as its single argument a property list,
  1776. see `org-trigger-hook' for more information about this list.
  1777. If any of the functions in this hook returns nil, the state change
  1778. is blocked.")
  1779. (defvar org-trigger-hook nil
  1780. "Hook for functions that are triggered by a state change.
  1781. Each function gets as its single argument a property list with at
  1782. least the following elements:
  1783. (:type type-of-change :position pos-at-entry-start
  1784. :from old-state :to new-state)
  1785. Depending on the type, more properties may be present.
  1786. This mechanism is currently implemented for:
  1787. TODO state changes
  1788. ------------------
  1789. :type todo-state-change
  1790. :from previous state (keyword as a string), or nil, or a symbol
  1791. `todo' or `done', to indicate the general type of state.
  1792. :to new state, like in :from")
  1793. (defcustom org-enforce-todo-dependencies nil
  1794. "Non-nil means undone TODO entries will block switching the parent to DONE.
  1795. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  1796. be blocked if any prior sibling is not yet done.
  1797. Finally, if the parent is blocked because of ordered siblings of its own,
  1798. the child will also be blocked."
  1799. :set (lambda (var val)
  1800. (set var val)
  1801. (if val
  1802. (add-hook 'org-blocker-hook
  1803. 'org-block-todo-from-children-or-siblings-or-parent)
  1804. (remove-hook 'org-blocker-hook
  1805. 'org-block-todo-from-children-or-siblings-or-parent)))
  1806. :group 'org-todo
  1807. :type 'boolean)
  1808. (defcustom org-enforce-todo-checkbox-dependencies nil
  1809. "Non-nil means unchecked boxes will block switching the parent to DONE.
  1810. When this is nil, checkboxes have no influence on switching TODO states.
  1811. When non-nil, you first need to check off all check boxes before the TODO
  1812. entry can be switched to DONE.
  1813. This variable needs to be set before org.el is loaded, and you need to
  1814. restart Emacs after a change to make the change effective. The only way
  1815. to change it while Emacs is running is through the customize interface."
  1816. :set (lambda (var val)
  1817. (set var val)
  1818. (if val
  1819. (add-hook 'org-blocker-hook
  1820. 'org-block-todo-from-checkboxes)
  1821. (remove-hook 'org-blocker-hook
  1822. 'org-block-todo-from-checkboxes)))
  1823. :group 'org-todo
  1824. :type 'boolean)
  1825. (defcustom org-treat-insert-todo-heading-as-state-change nil
  1826. "Non-nil means inserting a TODO heading is treated as state change.
  1827. So when the command `\\[org-insert-todo-heading]' is used, state change
  1828. logging will apply if appropriate. When nil, the new TODO item will
  1829. be inserted directly, and no logging will take place."
  1830. :group 'org-todo
  1831. :type 'boolean)
  1832. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  1833. "Non-nil means switching TODO states with S-cursor counts as state change.
  1834. This is the default behavior. However, setting this to nil allows a
  1835. convenient way to select a TODO state and bypass any logging associated
  1836. with that."
  1837. :group 'org-todo
  1838. :type 'boolean)
  1839. (defcustom org-todo-state-tags-triggers nil
  1840. "Tag changes that should be triggered by TODO state changes.
  1841. This is a list. Each entry is
  1842. (state-change (tag . flag) .......)
  1843. State-change can be a string with a state, and empty string to indicate the
  1844. state that has no TODO keyword, or it can be one of the symbols `todo'
  1845. or `done', meaning any not-done or done state, respectively."
  1846. :group 'org-todo
  1847. :group 'org-tags
  1848. :type '(repeat
  1849. (cons (choice :tag "When changing to"
  1850. (const :tag "Not-done state" todo)
  1851. (const :tag "Done state" done)
  1852. (string :tag "State"))
  1853. (repeat
  1854. (cons :tag "Tag action"
  1855. (string :tag "Tag")
  1856. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  1857. (defcustom org-log-done nil
  1858. "Information to record when a task moves to the DONE state.
  1859. Possible values are:
  1860. nil Don't add anything, just change the keyword
  1861. time Add a time stamp to the task
  1862. note Prompt for a note and add it with template `org-log-note-headings'
  1863. This option can also be set with on a per-file-basis with
  1864. #+STARTUP: nologdone
  1865. #+STARTUP: logdone
  1866. #+STARTUP: lognotedone
  1867. You can have local logging settings for a subtree by setting the LOGGING
  1868. property to one or more of these keywords."
  1869. :group 'org-todo
  1870. :group 'org-progress
  1871. :type '(choice
  1872. (const :tag "No logging" nil)
  1873. (const :tag "Record CLOSED timestamp" time)
  1874. (const :tag "Record CLOSED timestamp with note." note)))
  1875. ;; Normalize old uses of org-log-done.
  1876. (cond
  1877. ((eq org-log-done t) (setq org-log-done 'time))
  1878. ((and (listp org-log-done) (memq 'done org-log-done))
  1879. (setq org-log-done 'note)))
  1880. (defcustom org-log-reschedule nil
  1881. "Information to record when the scheduling date of a task is modified.
  1882. Possible values are:
  1883. nil Don't add anything, just change the date
  1884. time Add a time stamp to the task
  1885. note Prompt for a note and add it with template `org-log-note-headings'
  1886. This option can also be set with on a per-file-basis with
  1887. #+STARTUP: nologreschedule
  1888. #+STARTUP: logreschedule
  1889. #+STARTUP: lognotereschedule
  1890. You can have local logging settings for a subtree by setting the LOGGING
  1891. property to one or more of these keywords.
  1892. This variable has an effect when calling `org-schedule' or
  1893. `org-agenda-schedule' only."
  1894. :group 'org-todo
  1895. :group 'org-progress
  1896. :type '(choice
  1897. (const :tag "No logging" nil)
  1898. (const :tag "Record timestamp" time)
  1899. (const :tag "Record timestamp with note" note)))
  1900. (defcustom org-log-redeadline nil
  1901. "Information to record when the deadline 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: nologredeadline
  1908. #+STARTUP: logredeadline
  1909. #+STARTUP: lognoteredeadline
  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-deadline' or
  1913. `org-agenda-deadline' 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-note-clock-out nil
  1921. "Non-nil means record a note when clocking out of an item.
  1922. This can also be configured on a per-file basis by adding one of
  1923. the following lines anywhere in the buffer:
  1924. #+STARTUP: lognoteclock-out
  1925. #+STARTUP: nolognoteclock-out"
  1926. :group 'org-todo
  1927. :group 'org-progress
  1928. :type 'boolean)
  1929. (defcustom org-log-done-with-time t
  1930. "Non-nil means the CLOSED time stamp will contain date and time.
  1931. When nil, only the date will be recorded."
  1932. :group 'org-progress
  1933. :type 'boolean)
  1934. (defcustom org-log-note-headings
  1935. '((done . "CLOSING NOTE %t")
  1936. (state . "State %-12s from %-12S %t")
  1937. (note . "Note taken on %t")
  1938. (reschedule . "Rescheduled from %S on %t")
  1939. (delschedule . "Not scheduled, was %S on %t")
  1940. (redeadline . "New deadline from %S on %t")
  1941. (deldeadline . "Removed deadline, was %S on %t")
  1942. (refile . "Refiled on %t")
  1943. (clock-out . ""))
  1944. "Headings for notes added to entries.
  1945. The value is an alist, with the car being a symbol indicating the
  1946. note context, and the cdr is the heading to be used. The heading
  1947. may also be the empty string. The following placeholders can be
  1948. used:
  1949. %t a time stamp.
  1950. %T an active time stamp instead the default inactive one
  1951. %d a short-format time stamp.
  1952. %D an active short-format time stamp.
  1953. %s the new TODO state or time stamp (inactive), in double quotes.
  1954. %S the old TODO state or time stamp (inactive), in double quotes.
  1955. %u the user name.
  1956. %U full user name.
  1957. In fact, it is not a good idea to change the `state' entry,
  1958. because Agenda Log mode depends on the format of these entries."
  1959. :group 'org-todo
  1960. :group 'org-progress
  1961. :type '(list :greedy t
  1962. (cons (const :tag "Heading when closing an item" done) string)
  1963. (cons (const :tag
  1964. "Heading when changing todo state (todo sequence only)"
  1965. state) string)
  1966. (cons (const :tag "Heading when just taking a note" note) string)
  1967. (cons (const :tag "Heading when rescheduling" reschedule) string)
  1968. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  1969. (cons (const :tag "Heading when changing deadline" redeadline) string)
  1970. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  1971. (cons (const :tag "Heading when refiling" refile) string)
  1972. (cons (const :tag "Heading when clocking out" clock-out) string)))
  1973. (unless (assq 'note org-log-note-headings)
  1974. (push '(note . "%t") org-log-note-headings))
  1975. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  1976. (defcustom org-log-into-drawer nil
  1977. "Non-nil means insert state change notes and time stamps into a drawer.
  1978. When nil, state changes notes will be inserted after the headline and
  1979. any scheduling and clock lines, but not inside a drawer.
  1980. The value of this variable should be the name of the drawer to use.
  1981. LOGBOOK is proposed as the default drawer for this purpose, you can
  1982. also set this to a string to define the drawer of your choice.
  1983. A value of t is also allowed, representing \"LOGBOOK\".
  1984. A value of t or nil can also be set with on a per-file-basis with
  1985. #+STARTUP: logdrawer
  1986. #+STARTUP: nologdrawer
  1987. If this variable is set, `org-log-state-notes-insert-after-drawers'
  1988. will be ignored.
  1989. You can set the property LOG_INTO_DRAWER to overrule this setting for
  1990. a subtree.
  1991. Do not check directly this variable in a Lisp program. Call
  1992. function `org-log-into-drawer' instead."
  1993. :group 'org-todo
  1994. :group 'org-progress
  1995. :type '(choice
  1996. (const :tag "Not into a drawer" nil)
  1997. (const :tag "LOGBOOK" t)
  1998. (string :tag "Other")))
  1999. (defun org-log-into-drawer ()
  2000. "Name of the log drawer, as a string, or nil.
  2001. This is the value of `org-log-into-drawer'. However, if the
  2002. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2003. be used instead of the default value."
  2004. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2005. (cond ((equal p "nil") nil)
  2006. ((equal p "t") "LOGBOOK")
  2007. ((stringp p) p)
  2008. (p "LOGBOOK")
  2009. ((stringp org-log-into-drawer) org-log-into-drawer)
  2010. (org-log-into-drawer "LOGBOOK"))))
  2011. (defcustom org-log-state-notes-insert-after-drawers nil
  2012. "Non-nil means insert state change notes after any drawers in entry.
  2013. Only the drawers that *immediately* follow the headline and the
  2014. deadline/scheduled line are skipped.
  2015. When nil, insert notes right after the heading and perhaps the line
  2016. with deadline/scheduling if present.
  2017. This variable will have no effect if `org-log-into-drawer' is
  2018. set."
  2019. :group 'org-todo
  2020. :group 'org-progress
  2021. :type 'boolean)
  2022. (defcustom org-log-states-order-reversed t
  2023. "Non-nil means the latest state note will be directly after heading.
  2024. When nil, the state change notes will be ordered according to time.
  2025. This option can also be set with on a per-file-basis with
  2026. #+STARTUP: logstatesreversed
  2027. #+STARTUP: nologstatesreversed"
  2028. :group 'org-todo
  2029. :group 'org-progress
  2030. :type 'boolean)
  2031. (defcustom org-todo-repeat-to-state nil
  2032. "The TODO state to which a repeater should return the repeating task.
  2033. By default this is the first task of a TODO sequence or the
  2034. previous state of a TYPE_TODO set. But you can specify to use
  2035. the previous state in a TODO sequence or a string.
  2036. Alternatively, you can set the :REPEAT_TO_STATE: property of the
  2037. entry, which has precedence over this option."
  2038. :group 'org-todo
  2039. :version "24.1"
  2040. :type '(choice (const :tag "Use the previous TODO state" t)
  2041. (const :tag "Use the head of the TODO sequence" nil)
  2042. (string :tag "Use a specific TODO state")))
  2043. (defcustom org-log-repeat 'time
  2044. "Non-nil means record moving through the DONE state when triggering repeat.
  2045. An auto-repeating task is immediately switched back to TODO when
  2046. marked DONE. If you are not logging state changes (by adding \"@\"
  2047. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2048. record a closing note, there will be no record of the task moving
  2049. through DONE. This variable forces taking a note anyway.
  2050. nil Don't force a record
  2051. time Record a time stamp
  2052. note Prompt for a note and add it with template `org-log-note-headings'
  2053. This option can also be set with on a per-file-basis with
  2054. #+STARTUP: nologrepeat
  2055. #+STARTUP: logrepeat
  2056. #+STARTUP: lognoterepeat
  2057. You can have local logging settings for a subtree by setting the LOGGING
  2058. property to one or more of these keywords."
  2059. :group 'org-todo
  2060. :group 'org-progress
  2061. :type '(choice
  2062. (const :tag "Don't force a record" nil)
  2063. (const :tag "Force recording the DONE state" time)
  2064. (const :tag "Force recording a note with the DONE state" note)))
  2065. (defcustom org-todo-repeat-hook nil
  2066. "Hook that is run after a task has been repeated."
  2067. :package-version '(Org . "9.2")
  2068. :group 'org-todo
  2069. :type 'hook)
  2070. (defgroup org-priorities nil
  2071. "Priorities in Org mode."
  2072. :tag "Org Priorities"
  2073. :group 'org-todo)
  2074. (defvaralias 'org-enable-priority-commands 'org-priority-enable-commands)
  2075. (defcustom org-priority-enable-commands t
  2076. "Non-nil means priority commands are active.
  2077. When nil, these commands will be disabled, so that you never accidentally
  2078. set a priority."
  2079. :group 'org-priorities
  2080. :type 'boolean)
  2081. (defvaralias 'org-highest-priority 'org-priority-highest)
  2082. (defcustom org-priority-highest ?A
  2083. "The highest priority of TODO items.
  2084. A character like ?A, ?B, etc., or a numeric value like 1, 2, etc.
  2085. Must be smaller than `org-priority-lowest'."
  2086. :group 'org-priorities
  2087. :type '(choice
  2088. (character :tag "Character")
  2089. (integer :tag "Integer (< 65)")))
  2090. (defvaralias 'org-lowest-priority 'org-priority-lowest)
  2091. (defcustom org-priority-lowest ?C
  2092. "The lowest priority of TODO items.
  2093. A character like ?A, ?B, etc., or a numeric value like 1, 2, etc.
  2094. Must be higher than `org-priority-highest'."
  2095. :group 'org-priorities
  2096. :type '(choice
  2097. (character :tag "Character")
  2098. (integer :tag "Integer (< 65)")))
  2099. (defvaralias 'org-default-priority 'org-priority-default)
  2100. (defcustom org-priority-default ?B
  2101. "The default priority of TODO items.
  2102. This is the priority an item gets if no explicit priority is given.
  2103. When starting to cycle on an empty priority the first step in the cycle
  2104. depends on `org-priority-start-cycle-with-default'. The resulting first
  2105. step priority must not exceed the range from `org-priority-highest' to
  2106. `org-priority-lowest' which means that `org-priority-default' has to be
  2107. in this range exclusive or inclusive to the range boundaries. Else the
  2108. first step refuses to set the default and the second will fall back on
  2109. (depending on the command used) the highest or lowest priority."
  2110. :group 'org-priorities
  2111. :type '(choice
  2112. (character :tag "Character")
  2113. (integer :tag "Integer (< 65)")))
  2114. (defcustom org-priority-start-cycle-with-default t
  2115. "Non-nil means start with default priority when starting to cycle.
  2116. When this is nil, the first step in the cycle will be (depending on the
  2117. command used) one higher or lower than the default priority.
  2118. See also `org-priority-default'."
  2119. :group 'org-priorities
  2120. :type 'boolean)
  2121. (defvaralias 'org-get-priority-function 'org-priority-get-priority-function)
  2122. (defcustom org-priority-get-priority-function nil
  2123. "Function to extract the priority from a string.
  2124. The string is normally the headline. If this is nil, Org
  2125. computes the priority from the priority cookie like [#A] in the
  2126. headline. It returns an integer, increasing by 1000 for each
  2127. priority level.
  2128. The user can set a different function here, which should take a
  2129. string as an argument and return the numeric priority."
  2130. :group 'org-priorities
  2131. :version "24.1"
  2132. :type '(choice
  2133. (const nil)
  2134. (function)))
  2135. (defgroup org-time nil
  2136. "Options concerning time stamps and deadlines in Org mode."
  2137. :tag "Org Time"
  2138. :group 'org)
  2139. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2140. "Number of minutes to round time stamps to.
  2141. \\<org-mode-map>\
  2142. These are two values, the first applies when first creating a time stamp.
  2143. The second applies when changing it with the commands `S-up' and `S-down'.
  2144. When changing the time stamp, this means that it will change in steps
  2145. of N minutes, as given by the second value.
  2146. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2147. numbers should be factors of 60, so for example 5, 10, 15.
  2148. When this is larger than 1, you can still force an exact time stamp by using
  2149. a double prefix argument to a time stamp command like \
  2150. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2151. and by using a prefix arg to `S-up/down' to specify the exact number
  2152. of minutes to shift."
  2153. :group 'org-time
  2154. :get (lambda (var) ; Make sure both elements are there
  2155. (if (integerp (default-value var))
  2156. (list (default-value var) 5)
  2157. (default-value var)))
  2158. :type '(list
  2159. (integer :tag "when inserting times")
  2160. (integer :tag "when modifying times")))
  2161. ;; Normalize old customizations of this variable.
  2162. (when (integerp org-time-stamp-rounding-minutes)
  2163. (setq org-time-stamp-rounding-minutes
  2164. (list org-time-stamp-rounding-minutes
  2165. org-time-stamp-rounding-minutes)))
  2166. (defcustom org-display-custom-times nil
  2167. "Non-nil means overlay custom formats over all time stamps.
  2168. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2169. To turn this on on a per-file basis, insert anywhere in the file:
  2170. #+STARTUP: customtime"
  2171. :group 'org-time
  2172. :set 'set-default
  2173. :type 'sexp)
  2174. (make-variable-buffer-local 'org-display-custom-times)
  2175. (defcustom org-time-stamp-custom-formats
  2176. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2177. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2178. These are overlaid over the default ISO format if the variable
  2179. `org-display-custom-times' is set. Time like %H:%M should be at the
  2180. end of the second format. The custom formats are also honored by export
  2181. commands, if custom time display is turned on at the time of export."
  2182. :group 'org-time
  2183. :type 'sexp)
  2184. (defun org-time-stamp-format (&optional long inactive)
  2185. "Get the right format for a time string."
  2186. (let ((f (if long (cdr org-time-stamp-formats)
  2187. (car org-time-stamp-formats))))
  2188. (if inactive
  2189. (concat "[" (substring f 1 -1) "]")
  2190. f)))
  2191. (defcustom org-deadline-warning-days 14
  2192. "Number of days before expiration during which a deadline becomes active.
  2193. This variable governs the display in sparse trees and in the agenda.
  2194. When 0 or negative, it means use this number (the absolute value of it)
  2195. even if a deadline has a different individual lead time specified.
  2196. Custom commands can set this variable in the options section."
  2197. :group 'org-time
  2198. :group 'org-agenda-daily/weekly
  2199. :type 'integer)
  2200. (defcustom org-scheduled-delay-days 0
  2201. "Number of days before a scheduled item becomes active.
  2202. This variable governs the display in sparse trees and in the agenda.
  2203. The default value (i.e. 0) means: don't delay scheduled item.
  2204. When negative, it means use this number (the absolute value of it)
  2205. even if a scheduled item has a different individual delay time
  2206. specified.
  2207. Custom commands can set this variable in the options section."
  2208. :group 'org-time
  2209. :group 'org-agenda-daily/weekly
  2210. :version "24.4"
  2211. :package-version '(Org . "8.0")
  2212. :type 'integer)
  2213. (defcustom org-read-date-prefer-future t
  2214. "Non-nil means assume future for incomplete date input from user.
  2215. This affects the following situations:
  2216. 1. The user gives a month but not a year.
  2217. For example, if it is April and you enter \"feb 2\", this will be read
  2218. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2219. 2. The user gives a day, but no month.
  2220. For example, if today is the 15th, and you enter \"3\", Org will read
  2221. this as the third of *next* month. However, if you enter \"17\",
  2222. it will be considered as *this* month.
  2223. If you set this variable to the symbol `time', then also the following
  2224. will work:
  2225. 3. If the user gives a time.
  2226. If the time is before now, it will be interpreted as tomorrow.
  2227. Currently none of this works for ISO week specifications.
  2228. When this option is nil, the current day, month and year will always be
  2229. used as defaults.
  2230. See also `org-agenda-jump-prefer-future'."
  2231. :group 'org-time
  2232. :type '(choice
  2233. (const :tag "Never" nil)
  2234. (const :tag "Check month and day" t)
  2235. (const :tag "Check month, day, and time" time)))
  2236. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2237. "Should the agenda jump command prefer the future for incomplete dates?
  2238. The default is to do the same as configured in `org-read-date-prefer-future'.
  2239. But you can also set a deviating value here.
  2240. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2241. :group 'org-agenda
  2242. :group 'org-time
  2243. :version "24.1"
  2244. :type '(choice
  2245. (const :tag "Use org-read-date-prefer-future"
  2246. org-read-date-prefer-future)
  2247. (const :tag "Never" nil)
  2248. (const :tag "Always" t)))
  2249. (defcustom org-read-date-force-compatible-dates t
  2250. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2251. Depending on the system Emacs is running on, certain dates cannot
  2252. be represented with the type used internally to represent time.
  2253. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2254. correctly. Some systems allow for earlier dates, some for later,
  2255. some for both. One way to find out is to insert any date into an
  2256. Org buffer, putting the cursor on the year and hitting S-up and
  2257. S-down to test the range.
  2258. When this variable is set to t, the date/time prompt will not let
  2259. you specify dates outside the 1970-2037 range, so it is certain that
  2260. these dates will work in whatever version of Emacs you are
  2261. running, and also that you can move a file from one Emacs implementation
  2262. to another. Whenever Org is forcing the year for you, it will display
  2263. a message and beep.
  2264. When this variable is nil, Org will check if the date is
  2265. representable in the specific Emacs implementation you are using.
  2266. If not, it will force a year, usually the current year, and beep
  2267. to remind you. Currently this setting is not recommended because
  2268. the likelihood that you will open your Org files in an Emacs that
  2269. has limited date range is not negligible.
  2270. A workaround for this problem is to use diary sexp dates for time
  2271. stamps outside of this range."
  2272. :group 'org-time
  2273. :version "24.1"
  2274. :type 'boolean)
  2275. (defcustom org-read-date-display-live t
  2276. "Non-nil means display current interpretation of date prompt live.
  2277. This display will be in an overlay, in the minibuffer."
  2278. :group 'org-time
  2279. :type 'boolean)
  2280. (defvaralias 'org-popup-calendar-for-date-prompt
  2281. 'org-read-date-popup-calendar)
  2282. (defcustom org-read-date-popup-calendar t
  2283. "Non-nil means pop up a calendar when prompting for a date.
  2284. In the calendar, the date can be selected with mouse-1. However, the
  2285. minibuffer will also be active, and you can simply enter the date as well.
  2286. When nil, only the minibuffer will be available."
  2287. :group 'org-time
  2288. :type 'boolean)
  2289. (defcustom org-extend-today-until 0
  2290. "The hour when your day really ends. Must be an integer.
  2291. This has influence for the following applications:
  2292. - When switching the agenda to \"today\". If it is still earlier than
  2293. the time given here, the day recognized as TODAY is actually yesterday.
  2294. - When a date is read from the user and it is still before the time given
  2295. here, the current date and time will be assumed to be yesterday, 23:59.
  2296. Also, timestamps inserted in capture templates follow this rule.
  2297. IMPORTANT: This is a feature whose implementation is and likely will
  2298. remain incomplete. Really, it is only here because past midnight seems to
  2299. be the favorite working time of John Wiegley :-)"
  2300. :group 'org-time
  2301. :type 'integer)
  2302. (defcustom org-use-effective-time nil
  2303. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2304. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2305. \"effective time\" of any timestamps between midnight and 8am will be
  2306. 23:59 of the previous day."
  2307. :group 'org-time
  2308. :version "24.1"
  2309. :type 'boolean)
  2310. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2311. "When non-nil, use the last clock out time for `org-todo'.
  2312. Note that this option has precedence over the combined use of
  2313. `org-use-effective-time' and `org-extend-today-until'."
  2314. :group 'org-time
  2315. :version "24.4"
  2316. :package-version '(Org . "8.0")
  2317. :type 'boolean)
  2318. (defcustom org-edit-timestamp-down-means-later nil
  2319. "Non-nil means S-down will increase the time in a time stamp.
  2320. When nil, S-up will increase."
  2321. :group 'org-time
  2322. :type 'boolean)
  2323. (defcustom org-calendar-follow-timestamp-change t
  2324. "Non-nil means make the calendar window follow timestamp changes.
  2325. When a timestamp is modified and the calendar window is visible, it will be
  2326. moved to the new date."
  2327. :group 'org-time
  2328. :type 'boolean)
  2329. (defgroup org-tags nil
  2330. "Options concerning tags in Org mode."
  2331. :tag "Org Tags"
  2332. :group 'org)
  2333. (defcustom org-tag-alist nil
  2334. "Default tags available in Org files.
  2335. The value of this variable is an alist. Associations either:
  2336. (TAG)
  2337. (TAG . SELECT)
  2338. (SPECIAL)
  2339. where TAG is a tag as a string, SELECT is character, used to
  2340. select that tag through the fast tag selection interface, and
  2341. SPECIAL is one of the following keywords: `:startgroup',
  2342. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2343. `:newline'. These keywords are used to define a hierarchy of
  2344. tags. See manual for details.
  2345. When this variable is nil, Org mode bases tag input on what is
  2346. already in the buffer. The value can be overridden locally by
  2347. using a TAGS keyword, e.g.,
  2348. #+TAGS: tag1 tag2
  2349. See also `org-tag-persistent-alist' to sidestep this behavior."
  2350. :group 'org-tags
  2351. :type '(repeat
  2352. (choice
  2353. (cons :tag "Tag with key"
  2354. (string :tag "Tag name")
  2355. (character :tag "Access char"))
  2356. (list :tag "Tag" (string :tag "Tag name"))
  2357. (const :tag "Start radio group" (:startgroup))
  2358. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2359. (const :tag "Group tags delimiter" (:grouptags))
  2360. (const :tag "End radio group" (:endgroup))
  2361. (const :tag "End tag group, non distinct" (:endgrouptag))
  2362. (const :tag "New line" (:newline)))))
  2363. (defcustom org-tag-persistent-alist nil
  2364. "Tags always available in Org files.
  2365. The value of this variable is an alist. Associations either:
  2366. (TAG)
  2367. (TAG . SELECT)
  2368. (SPECIAL)
  2369. where TAG is a tag as a string, SELECT is a character, used to
  2370. select that tag through the fast tag selection interface, and
  2371. SPECIAL is one of the following keywords: `:startgroup',
  2372. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2373. `:newline'. These keywords are used to define a hierarchy of
  2374. tags. See manual for details.
  2375. Unlike to `org-tag-alist', tags defined in this variable do not
  2376. depend on a local TAGS keyword. Instead, to disable these tags
  2377. on a per-file basis, insert anywhere in the file:
  2378. #+STARTUP: noptag"
  2379. :group 'org-tags
  2380. :type '(repeat
  2381. (choice
  2382. (cons :tag "Tag with key"
  2383. (string :tag "Tag name")
  2384. (character :tag "Access char"))
  2385. (list :tag "Tag" (string :tag "Tag name"))
  2386. (const :tag "Start radio group" (:startgroup))
  2387. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2388. (const :tag "Group tags delimiter" (:grouptags))
  2389. (const :tag "End radio group" (:endgroup))
  2390. (const :tag "End tag group, non distinct" (:endgrouptag))
  2391. (const :tag "New line" (:newline)))))
  2392. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2393. "If non-nil, always offer completion for all tags of all agenda files.
  2394. Setting this variable locally allows for dynamic generation of tag
  2395. completions in capture buffers.
  2396. (add-hook \\='org-capture-mode-hook
  2397. (lambda ()
  2398. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  2399. :group 'org-tags
  2400. :version "24.1"
  2401. :type 'boolean)
  2402. (defvar org-file-tags nil
  2403. "List of tags that can be inherited by all entries in the file.
  2404. The tags will be inherited if the variable `org-use-tag-inheritance'
  2405. says they should be.
  2406. This variable is populated from #+FILETAGS lines.")
  2407. (defcustom org-use-fast-tag-selection 'auto
  2408. "Non-nil means use fast tag selection scheme.
  2409. This is a special interface to select and deselect tags with single keys.
  2410. When nil, fast selection is never used.
  2411. When the symbol `auto', fast selection is used if and only if selection
  2412. characters for tags have been configured, either through the variable
  2413. `org-tag-alist' or through a #+TAGS line in the buffer.
  2414. When t, fast selection is always used and selection keys are assigned
  2415. automatically if necessary."
  2416. :group 'org-tags
  2417. :type '(choice
  2418. (const :tag "Always" t)
  2419. (const :tag "Never" nil)
  2420. (const :tag "When selection characters are configured" auto)))
  2421. (defcustom org-fast-tag-selection-single-key nil
  2422. "Non-nil means fast tag selection exits after first change.
  2423. When nil, you have to press RET to exit it.
  2424. During fast tag selection, you can toggle this flag with `C-c'.
  2425. This variable can also have the value `expert'. In this case, the window
  2426. displaying the tags menu is not even shown, until you press C-c again."
  2427. :group 'org-tags
  2428. :type '(choice
  2429. (const :tag "No" nil)
  2430. (const :tag "Yes" t)
  2431. (const :tag "Expert" expert)))
  2432. (defvar org-fast-tag-selection-include-todo nil
  2433. "Non-nil means fast tags selection interface will also offer TODO states.
  2434. This is an undocumented feature, you should not rely on it.")
  2435. (defcustom org-tags-column -77
  2436. "The column to which tags should be indented in a headline.
  2437. If this number is positive, it specifies the column. If it is negative,
  2438. it means that the tags should be flushright to that column. For example,
  2439. -80 works well for a normal 80 character screen.
  2440. When 0, place tags directly after headline text, with only one space in
  2441. between."
  2442. :group 'org-tags
  2443. :type 'integer)
  2444. (defcustom org-auto-align-tags t
  2445. "Non-nil keeps tags aligned when modifying headlines.
  2446. Some operations (i.e. demoting) change the length of a headline and
  2447. therefore shift the tags around. With this option turned on, after
  2448. each such operation the tags are again aligned to `org-tags-column'."
  2449. :group 'org-tags
  2450. :type 'boolean)
  2451. (defcustom org-use-tag-inheritance t
  2452. "Non-nil means tags in levels apply also for sublevels.
  2453. When nil, only the tags directly given in a specific line apply there.
  2454. This may also be a list of tags that should be inherited, or a regexp that
  2455. matches tags that should be inherited. Additional control is possible
  2456. with the variable `org-tags-exclude-from-inheritance' which gives an
  2457. explicit list of tags to be excluded from inheritance, even if the value of
  2458. `org-use-tag-inheritance' would select it for inheritance.
  2459. If this option is t, a match early-on in a tree can lead to a large
  2460. number of matches in the subtree when constructing the agenda or creating
  2461. a sparse tree. If you only want to see the first match in a tree during
  2462. a search, check out the variable `org-tags-match-list-sublevels'."
  2463. :group 'org-tags
  2464. :type '(choice
  2465. (const :tag "Not" nil)
  2466. (const :tag "Always" t)
  2467. (repeat :tag "Specific tags" (string :tag "Tag"))
  2468. (regexp :tag "Tags matched by regexp")))
  2469. (defcustom org-tags-exclude-from-inheritance nil
  2470. "List of tags that should never be inherited.
  2471. This is a way to exclude a few tags from inheritance. For way to do
  2472. the opposite, to actively allow inheritance for selected tags,
  2473. see the variable `org-use-tag-inheritance'."
  2474. :group 'org-tags
  2475. :type '(repeat (string :tag "Tag")))
  2476. (defun org-tag-inherit-p (tag)
  2477. "Check if TAG is one that should be inherited."
  2478. (cond
  2479. ((member tag org-tags-exclude-from-inheritance) nil)
  2480. ((eq org-use-tag-inheritance t) t)
  2481. ((not org-use-tag-inheritance) nil)
  2482. ((stringp org-use-tag-inheritance)
  2483. (string-match org-use-tag-inheritance tag))
  2484. ((listp org-use-tag-inheritance)
  2485. (member tag org-use-tag-inheritance))
  2486. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  2487. (defcustom org-tags-match-list-sublevels t
  2488. "Non-nil means list also sublevels of headlines matching a search.
  2489. This variable applies to tags/property searches, and also to stuck
  2490. projects because this search is based on a tags match as well.
  2491. When set to the symbol `indented', sublevels are indented with
  2492. leading dots.
  2493. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  2494. the sublevels of a headline matching a tag search often also match
  2495. the same search. Listing all of them can create very long lists.
  2496. Setting this variable to nil causes subtrees of a match to be skipped.
  2497. This variable is semi-obsolete and probably should always be true. It
  2498. is better to limit inheritance to certain tags using the variables
  2499. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  2500. :group 'org-tags
  2501. :type '(choice
  2502. (const :tag "No, don't list them" nil)
  2503. (const :tag "Yes, do list them" t)
  2504. (const :tag "List them, indented with leading dots" indented)))
  2505. (defcustom org-tags-sort-function nil
  2506. "When set, tags are sorted using this function as a comparator."
  2507. :group 'org-tags
  2508. :type '(choice
  2509. (const :tag "No sorting" nil)
  2510. (const :tag "Alphabetical" org-string-collate-lessp)
  2511. (const :tag "Reverse alphabetical" org-string-collate-greaterp)
  2512. (function :tag "Custom function" nil)))
  2513. (defvar org-tags-history nil
  2514. "History of minibuffer reads for tags.")
  2515. (defvar org-last-tags-completion-table nil
  2516. "The last used completion table for tags.")
  2517. (defvar org-after-tags-change-hook nil
  2518. "Hook that is run after the tags in a line have changed.")
  2519. (defgroup org-properties nil
  2520. "Options concerning properties in Org mode."
  2521. :tag "Org Properties"
  2522. :group 'org)
  2523. (defcustom org-property-format "%-10s %s"
  2524. "How property key/value pairs should be formatted by `indent-line'.
  2525. When `indent-line' hits a property definition, it will format the line
  2526. according to this format, mainly to make sure that the values are
  2527. lined-up with respect to each other."
  2528. :group 'org-properties
  2529. :type 'string)
  2530. (defcustom org-properties-postprocess-alist nil
  2531. "Alist of properties and functions to adjust inserted values.
  2532. Elements of this alist must be of the form
  2533. ([string] [function])
  2534. where [string] must be a property name and [function] must be a
  2535. lambda expression: this lambda expression must take one argument,
  2536. the value to adjust, and return the new value as a string.
  2537. For example, this element will allow the property \"Remaining\"
  2538. to be updated wrt the relation between the \"Effort\" property
  2539. and the clock summary:
  2540. ((\"Remaining\" (lambda(value)
  2541. (let ((clocksum (org-clock-sum-current-item))
  2542. (effort (org-duration-to-minutes
  2543. (org-entry-get (point) \"Effort\"))))
  2544. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  2545. :group 'org-properties
  2546. :version "24.1"
  2547. :type '(alist :key-type (string :tag "Property")
  2548. :value-type (function :tag "Function")))
  2549. (defcustom org-use-property-inheritance nil
  2550. "Non-nil means properties apply also for sublevels.
  2551. This setting is chiefly used during property searches. Turning it on can
  2552. cause significant overhead when doing a search, which is why it is not
  2553. on by default.
  2554. When nil, only the properties directly given in the current entry count.
  2555. When t, every property is inherited. The value may also be a list of
  2556. properties that should have inheritance, or a regular expression matching
  2557. properties that should be inherited.
  2558. However, note that some special properties use inheritance under special
  2559. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  2560. and the properties ending in \"_ALL\" when they are used as descriptor
  2561. for valid values of a property.
  2562. Note for programmers:
  2563. When querying an entry with `org-entry-get', you can control if inheritance
  2564. should be used. By default, `org-entry-get' looks only at the local
  2565. properties. You can request inheritance by setting the inherit argument
  2566. to t (to force inheritance) or to `selective' (to respect the setting
  2567. in this variable)."
  2568. :group 'org-properties
  2569. :type '(choice
  2570. (const :tag "Not" nil)
  2571. (const :tag "Always" t)
  2572. (repeat :tag "Specific properties" (string :tag "Property"))
  2573. (regexp :tag "Properties matched by regexp")))
  2574. (defun org-property-inherit-p (property)
  2575. "Return a non-nil value if PROPERTY should be inherited."
  2576. (cond
  2577. ((eq org-use-property-inheritance t) t)
  2578. ((not org-use-property-inheritance) nil)
  2579. ((stringp org-use-property-inheritance)
  2580. (string-match org-use-property-inheritance property))
  2581. ((listp org-use-property-inheritance)
  2582. (member-ignore-case property org-use-property-inheritance))
  2583. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  2584. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  2585. "The default column format, if no other format has been defined.
  2586. This variable can be set on the per-file basis by inserting a line
  2587. #+COLUMNS: %25ITEM ....."
  2588. :group 'org-properties
  2589. :type 'string)
  2590. (defcustom org-columns-default-format-for-agenda nil
  2591. "The default column format in an agenda buffer.
  2592. This will be used for column view in the agenda unless a format has
  2593. been set by adding `org-overriding-columns-format' to the local
  2594. settings list of a custom agenda view. When nil, the columns format
  2595. for the first item in the agenda list will be used, or as a fall-back,
  2596. `org-columns-default-format'."
  2597. :group 'org-properties
  2598. :type '(choice
  2599. (const :tag "No default" nil)
  2600. (string :tag "Format string")))
  2601. (defcustom org-columns-ellipses ".."
  2602. "The ellipses to be used when a field in column view is truncated.
  2603. When this is the empty string, as many characters as possible are shown,
  2604. but then there will be no visual indication that the field has been truncated.
  2605. When this is a string of length N, the last N characters of a truncated
  2606. field are replaced by this string. If the column is narrower than the
  2607. ellipses string, only part of the ellipses string will be shown."
  2608. :group 'org-properties
  2609. :type 'string)
  2610. (defconst org-global-properties-fixed
  2611. '(("VISIBILITY_ALL" . "folded children content all")
  2612. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  2613. "List of property/value pairs that can be inherited by any entry.
  2614. These are fixed values, for the preset properties. The user variable
  2615. that can be used to add to this list is `org-global-properties'.
  2616. The entries in this list are cons cells where the car is a property
  2617. name and cdr is a string with the value. If the value represents
  2618. multiple items like an \"_ALL\" property, separate the items by
  2619. spaces.")
  2620. (defcustom org-global-properties nil
  2621. "List of property/value pairs that can be inherited by any entry.
  2622. This list will be combined with the constant `org-global-properties-fixed'.
  2623. The entries in this list are cons cells where the car is a property
  2624. name and cdr is a string with the value.
  2625. Buffer local properties are added either by a document property drawer
  2626. :PROPERTIES:
  2627. :NAME: VALUE
  2628. :END:
  2629. or by adding lines like
  2630. #+PROPERTY: NAME VALUE"
  2631. :group 'org-properties
  2632. :type '(repeat
  2633. (cons (string :tag "Property")
  2634. (string :tag "Value"))))
  2635. (defvar-local org-keyword-properties nil
  2636. "List of property/value pairs inherited by any entry.
  2637. Valid for the current buffer. This variable is populated from
  2638. PROPERTY keywords.
  2639. Note that properties are defined also in property drawers.
  2640. Properties defined there take precedence over properties defined
  2641. as keywords.")
  2642. (defgroup org-agenda nil
  2643. "Options concerning agenda views in Org mode."
  2644. :tag "Org Agenda"
  2645. :group 'org)
  2646. (defvar-local org-category nil
  2647. "Variable used by Org files to set a category for agenda display.
  2648. There are multiple ways to set the category. One way is to set
  2649. it in the document property drawer. For example:
  2650. :PROPERTIES:
  2651. :CATEGORY: ELisp
  2652. :END:
  2653. Other ways to define it is as an emacs file variable, for example
  2654. # -*- mode: org; org-category: \"ELisp\"
  2655. or for the file to contain a special line:
  2656. #+CATEGORY: ELisp
  2657. If the file does not specify a category, then file's base name
  2658. is used instead.")
  2659. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  2660. (defcustom org-agenda-files nil
  2661. "The files to be used for agenda display.
  2662. If an entry is a directory, all files in that directory that are matched
  2663. by `org-agenda-file-regexp' will be part of the file list.
  2664. If the value of the variable is not a list but a single file name, then
  2665. the list of agenda files is actually stored and maintained in that file,
  2666. one agenda file per line. In this file paths can be given relative to
  2667. `org-directory'. Tilde expansion and environment variable substitution
  2668. are also made.
  2669. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  2670. and removed with `\\[org-remove-file]'."
  2671. :group 'org-agenda
  2672. :type '(choice
  2673. (repeat :tag "List of files and directories" file)
  2674. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  2675. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  2676. "Regular expression to match files for `org-agenda-files'.
  2677. If any element in the list in that variable contains a directory instead
  2678. of a normal file, all files in that directory that are matched by this
  2679. regular expression will be included."
  2680. :group 'org-agenda
  2681. :type 'regexp)
  2682. (defvaralias 'org-agenda-multi-occur-extra-files
  2683. 'org-agenda-text-search-extra-files)
  2684. (defcustom org-agenda-text-search-extra-files nil
  2685. "List of extra files to be searched by text search commands.
  2686. These files will be searched in addition to the agenda files by the
  2687. commands `org-search-view' (`\\[org-agenda] s') \
  2688. and `org-occur-in-agenda-files'.
  2689. Note that these files will only be searched for text search commands,
  2690. not for the other agenda views like todo lists, tag searches or the weekly
  2691. agenda. This variable is intended to list notes and possibly archive files
  2692. that should also be searched by these two commands.
  2693. In fact, if the first element in the list is the symbol `agenda-archives',
  2694. then all archive files of all agenda files will be added to the search
  2695. scope."
  2696. :group 'org-agenda
  2697. :type '(set :greedy t
  2698. (const :tag "Agenda Archives" agenda-archives)
  2699. (repeat :inline t (file))))
  2700. (defcustom org-agenda-skip-unavailable-files nil
  2701. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  2702. A nil value means to remove them, after a query, from the list."
  2703. :group 'org-agenda
  2704. :type 'boolean)
  2705. (defgroup org-latex nil
  2706. "Options for embedding LaTeX code into Org mode."
  2707. :tag "Org LaTeX"
  2708. :group 'org)
  2709. (defcustom org-format-latex-options
  2710. '(:foreground default :background default :scale 1.0
  2711. :html-foreground "Black" :html-background "Transparent"
  2712. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  2713. "Options for creating images from LaTeX fragments.
  2714. This is a property list with the following properties:
  2715. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  2716. `default' means use the foreground of the default face.
  2717. `auto' means use the foreground from the text face.
  2718. :background the background color, or \"Transparent\".
  2719. `default' means use the background of the default face.
  2720. `auto' means use the background from the text face.
  2721. :scale a scaling factor for the size of the images, to get more pixels
  2722. :html-foreground, :html-background, :html-scale
  2723. the same numbers for HTML export.
  2724. :matchers a list indicating which matchers should be used to
  2725. find LaTeX fragments. Valid members of this list are:
  2726. \"begin\" find environments
  2727. \"$1\" find single characters surrounded by $.$
  2728. \"$\" find math expressions surrounded by $...$
  2729. \"$$\" find math expressions surrounded by $$....$$
  2730. \"\\(\" find math expressions surrounded by \\(...\\)
  2731. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  2732. :group 'org-latex
  2733. :type 'plist)
  2734. (defcustom org-format-latex-signal-error t
  2735. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  2736. When nil, just push out a message."
  2737. :group 'org-latex
  2738. :version "24.1"
  2739. :type 'boolean)
  2740. (defcustom org-latex-to-mathml-jar-file nil
  2741. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  2742. Use this to specify additional executable file say a jar file.
  2743. When using MathToWeb as the converter, specify the full-path to
  2744. your mathtoweb.jar file."
  2745. :group 'org-latex
  2746. :version "24.1"
  2747. :type '(choice
  2748. (const :tag "None" nil)
  2749. (file :tag "JAR file" :must-match t)))
  2750. (defcustom org-latex-to-mathml-convert-command nil
  2751. "Command to convert LaTeX fragments to MathML.
  2752. Replace format-specifiers in the command as noted below and use
  2753. `shell-command' to convert LaTeX to MathML.
  2754. %j: Executable file in fully expanded form as specified by
  2755. `org-latex-to-mathml-jar-file'.
  2756. %I: Input LaTeX file in fully expanded form.
  2757. %i: The latex fragment to be converted.
  2758. %o: Output MathML file.
  2759. This command is used by `org-create-math-formula'.
  2760. When using MathToWeb as the converter, set this option to
  2761. \"java -jar %j -unicode -force -df %o %I\".
  2762. When using LaTeXML set this option to
  2763. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  2764. :group 'org-latex
  2765. :version "24.1"
  2766. :type '(choice
  2767. (const :tag "None" nil)
  2768. (string :tag "\nShell command")))
  2769. (defcustom org-latex-to-html-convert-command nil
  2770. "Command to convert LaTeX fragments to HTML.
  2771. This command is very open-ended: the output of the command will
  2772. directly replace the LaTeX fragment in the resulting HTML.
  2773. Replace format-specifiers in the command as noted below and use
  2774. `shell-command' to convert LaTeX to HTML.
  2775. %i: The LaTeX fragment to be converted.
  2776. For example, this could be used with LaTeXML as
  2777. \"latexmlc 'literal:%i' --profile=math --preload=siunitx.sty 2>/dev/null\"."
  2778. :group 'org-latex
  2779. :package-version '(Org . "9.4")
  2780. :type '(choice
  2781. (const :tag "None" nil)
  2782. (string :tag "Shell command")))
  2783. (defcustom org-preview-latex-default-process 'dvipng
  2784. "The default process to convert LaTeX fragments to image files.
  2785. All available processes and theirs documents can be found in
  2786. `org-preview-latex-process-alist', which see."
  2787. :group 'org-latex
  2788. :version "26.1"
  2789. :package-version '(Org . "9.0")
  2790. :type 'symbol)
  2791. (defcustom org-preview-latex-process-alist
  2792. '((dvipng
  2793. :programs ("latex" "dvipng")
  2794. :description "dvi > png"
  2795. :message "you need to install the programs: latex and dvipng."
  2796. :image-input-type "dvi"
  2797. :image-output-type "png"
  2798. :image-size-adjust (1.0 . 1.0)
  2799. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2800. :image-converter ("dvipng -D %D -T tight -o %O %f"))
  2801. (dvisvgm
  2802. :programs ("latex" "dvisvgm")
  2803. :description "dvi > svg"
  2804. :message "you need to install the programs: latex and dvisvgm."
  2805. :image-input-type "dvi"
  2806. :image-output-type "svg"
  2807. :image-size-adjust (1.7 . 1.5)
  2808. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2809. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  2810. (imagemagick
  2811. :programs ("latex" "convert")
  2812. :description "pdf > png"
  2813. :message "you need to install the programs: latex and imagemagick."
  2814. :image-input-type "pdf"
  2815. :image-output-type "png"
  2816. :image-size-adjust (1.0 . 1.0)
  2817. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  2818. :image-converter
  2819. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  2820. "Definitions of external processes for LaTeX previewing.
  2821. Org mode can use some external commands to generate TeX snippet's images for
  2822. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  2823. `org-create-formula-image' how to call them.
  2824. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  2825. PROPERTIES accepts the following attributes:
  2826. :programs list of strings, required programs.
  2827. :description string, describe the process.
  2828. :message string, message it when required programs cannot be found.
  2829. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  2830. :image-output-type string, output file type of image converter (e.g., \"png\").
  2831. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  2832. image size showed in buffer and the cdr element is for
  2833. HTML file. This option is only useful for process
  2834. developers, users should use variable
  2835. `org-format-latex-options' instead.
  2836. :post-clean list of strings, files matched are to be cleaned up once
  2837. the image is generated. When nil, the files with \".dvi\",
  2838. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  2839. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  2840. be cleaned up.
  2841. :latex-header list of strings, the LaTeX header of the snippet file.
  2842. When nil, the fallback value is used instead, which is
  2843. controlled by `org-format-latex-header',
  2844. `org-latex-default-packages-alist' and
  2845. `org-latex-packages-alist', which see.
  2846. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  2847. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  2848. replaced with values defined below.
  2849. :image-converter list of image converter commands strings. Each of them is
  2850. given to the shell and supports any of the following
  2851. place-holders defined below.
  2852. Place-holders used by `:image-converter' and `:latex-compiler':
  2853. %f input file name
  2854. %b base name of input file
  2855. %o base directory of input file
  2856. %O absolute output file name
  2857. Place-holders only used by `:image-converter':
  2858. %D dpi, which is used to adjust image size by some processing commands.
  2859. %S the image size scale ratio, which is used to adjust image size by some
  2860. processing commands."
  2861. :group 'org-latex
  2862. :version "26.1"
  2863. :package-version '(Org . "9.0")
  2864. :type '(alist :tag "LaTeX to image backends"
  2865. :value-type (plist)))
  2866. (defcustom org-preview-latex-image-directory "ltximg/"
  2867. "Path to store latex preview images.
  2868. A relative path here creates many directories relative to the
  2869. processed Org files paths. An absolute path puts all preview
  2870. images at the same place."
  2871. :group 'org-latex
  2872. :version "26.1"
  2873. :package-version '(Org . "9.0")
  2874. :type 'string)
  2875. (defun org-format-latex-mathml-available-p ()
  2876. "Return t if `org-latex-to-mathml-convert-command' is usable."
  2877. (save-match-data
  2878. (when (and (boundp 'org-latex-to-mathml-convert-command)
  2879. org-latex-to-mathml-convert-command)
  2880. (let ((executable (car (split-string
  2881. org-latex-to-mathml-convert-command))))
  2882. (when (executable-find executable)
  2883. (if (string-match
  2884. "%j" org-latex-to-mathml-convert-command)
  2885. (file-readable-p org-latex-to-mathml-jar-file)
  2886. t))))))
  2887. (defcustom org-format-latex-header "\\documentclass{article}
  2888. \\usepackage[usenames]{color}
  2889. \[PACKAGES]
  2890. \[DEFAULT-PACKAGES]
  2891. \\pagestyle{empty} % do not remove
  2892. % The settings below are copied from fullpage.sty
  2893. \\setlength{\\textwidth}{\\paperwidth}
  2894. \\addtolength{\\textwidth}{-3cm}
  2895. \\setlength{\\oddsidemargin}{1.5cm}
  2896. \\addtolength{\\oddsidemargin}{-2.54cm}
  2897. \\setlength{\\evensidemargin}{\\oddsidemargin}
  2898. \\setlength{\\textheight}{\\paperheight}
  2899. \\addtolength{\\textheight}{-\\headheight}
  2900. \\addtolength{\\textheight}{-\\headsep}
  2901. \\addtolength{\\textheight}{-\\footskip}
  2902. \\addtolength{\\textheight}{-3cm}
  2903. \\setlength{\\topmargin}{1.5cm}
  2904. \\addtolength{\\topmargin}{-2.54cm}"
  2905. "The document header used for processing LaTeX fragments.
  2906. It is imperative that this header make sure that no page number
  2907. appears on the page. The package defined in the variables
  2908. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  2909. will either replace the placeholder \"[PACKAGES]\" in this
  2910. header, or they will be appended."
  2911. :group 'org-latex
  2912. :type 'string)
  2913. (defun org-set-packages-alist (var val)
  2914. "Set the packages alist and make sure it has 3 elements per entry."
  2915. (set var (mapcar (lambda (x)
  2916. (if (and (consp x) (= (length x) 2))
  2917. (list (car x) (nth 1 x) t)
  2918. x))
  2919. val)))
  2920. (defun org-get-packages-alist (var)
  2921. "Get the packages alist and make sure it has 3 elements per entry."
  2922. (mapcar (lambda (x)
  2923. (if (and (consp x) (= (length x) 2))
  2924. (list (car x) (nth 1 x) t)
  2925. x))
  2926. (default-value var)))
  2927. (defcustom org-latex-default-packages-alist
  2928. '(("AUTO" "inputenc" t ("pdflatex"))
  2929. ("T1" "fontenc" t ("pdflatex"))
  2930. ("" "graphicx" t)
  2931. ("" "grffile" t)
  2932. ("" "longtable" nil)
  2933. ("" "wrapfig" nil)
  2934. ("" "rotating" nil)
  2935. ("normalem" "ulem" t)
  2936. ("" "amsmath" t)
  2937. ("" "textcomp" t)
  2938. ("" "amssymb" t)
  2939. ("" "capt-of" nil)
  2940. ("" "hyperref" nil))
  2941. "Alist of default packages to be inserted in the header.
  2942. Change this only if one of the packages here causes an
  2943. incompatibility with another package you are using.
  2944. The packages in this list are needed by one part or another of
  2945. Org mode to function properly:
  2946. - inputenc, fontenc: for basic font and character selection
  2947. - graphicx: for including images
  2948. - grffile: allow periods and spaces in graphics file names
  2949. - longtable: For multipage tables
  2950. - wrapfig: for figure placement
  2951. - rotating: for sideways figures and tables
  2952. - ulem: for underline and strike-through
  2953. - amsmath: for subscript and superscript and math environments
  2954. - textcomp, amssymb: for various symbols used
  2955. for interpreting the entities in `org-entities'. You can skip
  2956. some of these packages if you don't use any of their symbols.
  2957. - capt-of: for captions outside of floats
  2958. - hyperref: for cross references
  2959. Therefore you should not modify this variable unless you know
  2960. what you are doing. The one reason to change it anyway is that
  2961. you might be loading some other package that conflicts with one
  2962. of the default packages. Each element is either a cell or
  2963. a string.
  2964. A cell is of the format
  2965. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  2966. If SNIPPET-FLAG is non-nil, the package also needs to be included
  2967. when compiling LaTeX snippets into images for inclusion into
  2968. non-LaTeX output.
  2969. COMPILERS is a list of compilers that should include the package,
  2970. see `org-latex-compiler'. If the document compiler is not in the
  2971. list, and the list is non-nil, the package will not be inserted
  2972. in the final document.
  2973. A string will be inserted as-is in the header of the document."
  2974. :group 'org-latex
  2975. :group 'org-export-latex
  2976. :set 'org-set-packages-alist
  2977. :get 'org-get-packages-alist
  2978. :version "26.1"
  2979. :package-version '(Org . "8.3")
  2980. :type '(repeat
  2981. (choice
  2982. (list :tag "options/package pair"
  2983. (string :tag "options")
  2984. (string :tag "package")
  2985. (boolean :tag "Snippet")
  2986. (choice
  2987. (const :tag "For all compilers" nil)
  2988. (repeat :tag "Allowed compiler" string)))
  2989. (string :tag "A line of LaTeX"))))
  2990. (defcustom org-latex-packages-alist nil
  2991. "Alist of packages to be inserted in every LaTeX header.
  2992. These will be inserted after `org-latex-default-packages-alist'.
  2993. Each element is either a cell or a string.
  2994. A cell is of the format:
  2995. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  2996. SNIPPET-FLAG, when non-nil, indicates that this package is also
  2997. needed when turning LaTeX snippets into images for inclusion into
  2998. non-LaTeX output.
  2999. COMPILERS is a list of compilers that should include the package,
  3000. see `org-latex-compiler'. If the document compiler is not in the
  3001. list, and the list is non-nil, the package will not be inserted
  3002. in the final document.
  3003. A string will be inserted as-is in the header of the document.
  3004. Make sure that you only list packages here which:
  3005. - you want in every file;
  3006. - do not conflict with the setup in `org-format-latex-header';
  3007. - do not conflict with the default packages in
  3008. `org-latex-default-packages-alist'."
  3009. :group 'org-latex
  3010. :group 'org-export-latex
  3011. :set 'org-set-packages-alist
  3012. :get 'org-get-packages-alist
  3013. :type '(repeat
  3014. (choice
  3015. (list :tag "options/package pair"
  3016. (string :tag "options")
  3017. (string :tag "package")
  3018. (boolean :tag "Snippet"))
  3019. (string :tag "A line of LaTeX"))))
  3020. (defgroup org-appearance nil
  3021. "Settings for Org mode appearance."
  3022. :tag "Org Appearance"
  3023. :group 'org)
  3024. (defcustom org-level-color-stars-only nil
  3025. "Non-nil means fontify only the stars in each headline.
  3026. When nil, the entire headline is fontified.
  3027. Changing it requires restart of `font-lock-mode' to become effective
  3028. also in regions already fontified."
  3029. :group 'org-appearance
  3030. :type 'boolean)
  3031. (defcustom org-hide-leading-stars nil
  3032. "Non-nil means hide the first N-1 stars in a headline.
  3033. This works by using the face `org-hide' for these stars. This
  3034. face is white for a light background, and black for a dark
  3035. background. You may have to customize the face `org-hide' to
  3036. make this work.
  3037. Changing it requires restart of `font-lock-mode' to become effective
  3038. also in regions already fontified.
  3039. You may also set this on a per-file basis by adding one of the following
  3040. lines to the buffer:
  3041. #+STARTUP: hidestars
  3042. #+STARTUP: showstars"
  3043. :group 'org-appearance
  3044. :type 'boolean)
  3045. (defcustom org-hidden-keywords nil
  3046. "List of symbols corresponding to keywords to be hidden in the Org buffer.
  3047. For example, a value \\='(title) for this list makes the document's title
  3048. appear in the buffer without the initial \"#+TITLE:\" part."
  3049. :group 'org-appearance
  3050. :version "24.1"
  3051. :type '(set (const :tag "#+AUTHOR" author)
  3052. (const :tag "#+DATE" date)
  3053. (const :tag "#+EMAIL" email)
  3054. (const :tag "#+TITLE" title)))
  3055. (defcustom org-custom-properties nil
  3056. "List of properties (as strings) with a special meaning.
  3057. The default use of these custom properties is to let the user
  3058. hide them with `org-toggle-custom-properties-visibility'."
  3059. :group 'org-properties
  3060. :group 'org-appearance
  3061. :version "24.3"
  3062. :type '(repeat (string :tag "Property Name")))
  3063. (defcustom org-fontify-todo-headline nil
  3064. "Non-nil means change the face of a headline if it is marked as TODO.
  3065. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3066. When this is non-nil, the headline after the keyword is set to the
  3067. `org-headline-todo' as an additional indication."
  3068. :group 'org-appearance
  3069. :package-version '(Org . "9.4")
  3070. :type 'boolean
  3071. :safe t)
  3072. (defcustom org-fontify-done-headline t
  3073. "Non-nil means change the face of a headline if it is marked DONE.
  3074. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3075. When this is non-nil, the headline after the keyword is set to the
  3076. `org-headline-done' as an additional indication."
  3077. :group 'org-appearance
  3078. :version "27.1"
  3079. :package-version "9.4"
  3080. :type 'boolean)
  3081. (defcustom org-fontify-emphasized-text t
  3082. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3083. Changing this variable requires a restart of Emacs to take effect."
  3084. :group 'org-appearance
  3085. :type 'boolean)
  3086. (defcustom org-fontify-whole-heading-line nil
  3087. "Non-nil means fontify the whole line for headings.
  3088. This is useful when setting a background color for the
  3089. org-level-* faces."
  3090. :group 'org-appearance
  3091. :type 'boolean)
  3092. (defcustom org-fontify-whole-block-delimiter-line t
  3093. "Non-nil means fontify the whole line for begin/end lines of blocks.
  3094. This is useful when setting a background color for the
  3095. org-block-begin-line and org-block-end-line faces."
  3096. :group 'org-appearance
  3097. :type 'boolean)
  3098. (defcustom org-highlight-latex-and-related nil
  3099. "Non-nil means highlight LaTeX related syntax in the buffer.
  3100. When non-nil, the value should be a list containing any of the
  3101. following symbols:
  3102. `native' Highlight LaTeX snippets and environments natively.
  3103. `latex' Highlight LaTeX snippets and environments.
  3104. `script' Highlight subscript and superscript.
  3105. `entities' Highlight entities."
  3106. :group 'org-appearance
  3107. :version "24.4"
  3108. :package-version '(Org . "8.0")
  3109. :type '(choice
  3110. (const :tag "No highlighting" nil)
  3111. (set :greedy t :tag "Highlight"
  3112. (const :tag "LaTeX snippets and environments (native)" native)
  3113. (const :tag "LaTeX snippets and environments" latex)
  3114. (const :tag "Subscript and superscript" script)
  3115. (const :tag "Entities" entities))))
  3116. (defcustom org-hide-emphasis-markers nil
  3117. "Non-nil mean font-lock should hide the emphasis marker characters."
  3118. :group 'org-appearance
  3119. :type 'boolean
  3120. :safe #'booleanp)
  3121. (defcustom org-hide-macro-markers nil
  3122. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3123. :group 'org-appearance
  3124. :type 'boolean)
  3125. (defcustom org-pretty-entities nil
  3126. "Non-nil means show entities as UTF8 characters.
  3127. When nil, the \\name form remains in the buffer."
  3128. :group 'org-appearance
  3129. :version "24.1"
  3130. :type 'boolean)
  3131. (defcustom org-pretty-entities-include-sub-superscripts t
  3132. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3133. :group 'org-appearance
  3134. :version "24.1"
  3135. :type 'boolean)
  3136. (defvar org-emph-re nil
  3137. "Regular expression for matching emphasis.
  3138. After a match, the match groups contain these elements:
  3139. 0 The match of the full regular expression, including the characters
  3140. before and after the proper match
  3141. 1 The character before the proper match, or empty at beginning of line
  3142. 2 The proper match, including the leading and trailing markers
  3143. 3 The leading marker like * or /, indicating the type of highlighting
  3144. 4 The text between the emphasis markers, not including the markers
  3145. 5 The character after the match, empty at the end of a line")
  3146. (defvar org-verbatim-re nil
  3147. "Regular expression for matching verbatim text.")
  3148. (defvar org-emphasis-regexp-components) ; defined just below
  3149. (defvar org-emphasis-alist) ; defined just below
  3150. (defun org-set-emph-re (var val)
  3151. "Set variable and compute the emphasis regular expression."
  3152. (set var val)
  3153. (when (and (boundp 'org-emphasis-alist)
  3154. (boundp 'org-emphasis-regexp-components)
  3155. org-emphasis-alist org-emphasis-regexp-components)
  3156. (pcase-let*
  3157. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3158. (body (if (<= nl 0) body
  3159. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3160. (template
  3161. (format (concat "\\([%s]\\|^\\)" ;before markers
  3162. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3163. "\\([%s]\\|$\\)") ;after markers
  3164. pre border border body border post)))
  3165. (setq org-emph-re (format template "*/_+"))
  3166. (setq org-verbatim-re (format template "=~")))))
  3167. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3168. ;; set this option proved cumbersome. See this message/thread:
  3169. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3170. (defvar org-emphasis-regexp-components
  3171. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3172. "Components used to build the regular expression for emphasis.
  3173. This is a list with five entries. Terminology: In an emphasis string
  3174. like \" *strong word* \", we call the initial space PREMATCH, the final
  3175. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3176. and \"trong wor\" is the body. The different components in this variable
  3177. specify what is allowed/forbidden in each part:
  3178. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3179. post Chars allowed as postmatch. End of line will be allowed too.
  3180. border The chars *forbidden* as border characters.
  3181. body-regexp A regexp like \".\" to match a body character. Don't use
  3182. non-shy groups here, and don't allow newline here.
  3183. newline The maximum number of newlines allowed in an emphasis exp.
  3184. You need to reload Org or to restart Emacs after setting this.")
  3185. (defcustom org-emphasis-alist
  3186. '(("*" bold)
  3187. ("/" italic)
  3188. ("_" underline)
  3189. ("=" org-verbatim verbatim)
  3190. ("~" org-code verbatim)
  3191. ("+" (:strike-through t)))
  3192. "Alist of characters and faces to emphasize text.
  3193. Text starting and ending with a special character will be emphasized,
  3194. for example *bold*, _underlined_ and /italic/. This variable sets the
  3195. marker characters and the face to be used by font-lock for highlighting
  3196. in Org buffers.
  3197. You need to reload Org or to restart Emacs after customizing this."
  3198. :group 'org-appearance
  3199. :set 'org-set-emph-re
  3200. :version "24.4"
  3201. :package-version '(Org . "8.0")
  3202. :type '(repeat
  3203. (list
  3204. (string :tag "Marker character")
  3205. (choice
  3206. (face :tag "Font-lock-face")
  3207. (plist :tag "Face property list"))
  3208. (option (const verbatim)))))
  3209. (defvar org-protecting-blocks '("src" "example" "export")
  3210. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3211. This is needed for font-lock setup.")
  3212. ;;; Functions and variables from their packages
  3213. ;; Declared here to avoid compiler warnings
  3214. (defvar mark-active)
  3215. ;; Various packages
  3216. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3217. (declare-function calendar-forward-day "cal-move" (arg))
  3218. (declare-function calendar-goto-date "cal-move" (date))
  3219. (declare-function calendar-goto-today "cal-move" ())
  3220. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3221. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3222. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3223. (declare-function cdlatex-tab "ext:cdlatex" ())
  3224. (declare-function dired-get-filename
  3225. "dired"
  3226. (&optional localp no-error-if-not-filep))
  3227. (declare-function iswitchb-read-buffer
  3228. "iswitchb"
  3229. (prompt &optional
  3230. default require-match _predicate start matches-set))
  3231. (declare-function org-agenda-change-all-lines
  3232. "org-agenda"
  3233. (newhead hdmarker &optional fixface just-this))
  3234. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3235. "org-agenda"
  3236. (&optional end))
  3237. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3238. (declare-function org-agenda-format-item
  3239. "org-agenda"
  3240. (extra txt &optional level category tags dotime
  3241. remove-re habitp))
  3242. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3243. (declare-function org-agenda-save-markers-for-cut-and-paste
  3244. "org-agenda"
  3245. (beg end))
  3246. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3247. (declare-function org-agenda-skip "org-agenda" ())
  3248. (declare-function org-attach-expand "org-attach" (file))
  3249. (declare-function org-attach-reveal "org-attach" ())
  3250. (declare-function org-attach-reveal-in-emacs "org-attach" ())
  3251. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3252. (declare-function org-indent-mode "org-indent" (&optional arg))
  3253. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3254. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3255. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3256. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3257. (declare-function parse-time-string "parse-time" (string))
  3258. (defvar align-mode-rules-list)
  3259. (defvar calc-embedded-close-formula)
  3260. (defvar calc-embedded-open-formula)
  3261. (defvar calc-embedded-open-mode)
  3262. (defvar font-lock-unfontify-region-function)
  3263. (defvar iswitchb-temp-buflist)
  3264. (defvar org-agenda-tags-todo-honor-ignore-options)
  3265. (defvar remember-data-file)
  3266. (defvar texmathp-why)
  3267. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3268. (declare-function org-clock-update-mode-line "org-clock" (&optional refresh))
  3269. (declare-function org-resolve-clocks "org-clock"
  3270. (&optional also-non-dangling-p prompt last-valid))
  3271. (defvar org-clock-start-time)
  3272. (defvar org-clock-marker (make-marker)
  3273. "Marker recording the last clock-in.")
  3274. (defvar org-clock-hd-marker (make-marker)
  3275. "Marker recording the last clock-in, but the headline position.")
  3276. (defvar org-clock-heading ""
  3277. "The heading of the current clock entry.")
  3278. (defun org-clock-is-active ()
  3279. "Return the buffer where the clock is currently running.
  3280. Return nil if no clock is running."
  3281. (marker-buffer org-clock-marker))
  3282. (defun org-check-running-clock ()
  3283. "Check if the current buffer contains the running clock.
  3284. If yes, offer to stop it and to save the buffer with the changes."
  3285. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3286. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3287. (buffer-name))))
  3288. (org-clock-out)
  3289. (when (y-or-n-p "Save changed buffer?")
  3290. (save-buffer))))
  3291. (defun org-clocktable-try-shift (dir n)
  3292. "Check if this line starts a clock table, if yes, shift the time block."
  3293. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3294. (org-clocktable-shift dir n)))
  3295. ;;;###autoload
  3296. (defun org-clock-persistence-insinuate ()
  3297. "Set up hooks for clock persistence."
  3298. (require 'org-clock)
  3299. (add-hook 'org-mode-hook 'org-clock-load)
  3300. (add-hook 'kill-emacs-hook 'org-clock-save))
  3301. (defun org-clock-auto-clockout-insinuate ()
  3302. "Set up hook for auto clocking out when Emacs is idle.
  3303. See `org-clock-auto-clockout-timer'.
  3304. This function is meant to be added to the user configuration."
  3305. (require 'org-clock)
  3306. (add-hook 'org-clock-in-hook #'org-clock-auto-clockout t))
  3307. (defgroup org-archive nil
  3308. "Options concerning archiving in Org mode."
  3309. :tag "Org Archive"
  3310. :group 'org-structure)
  3311. (defcustom org-archive-location "%s_archive::"
  3312. "The location where subtrees should be archived.
  3313. The value of this variable is a string, consisting of two parts,
  3314. separated by a double-colon. The first part is a filename and
  3315. the second part is a headline.
  3316. When the filename is omitted, archiving happens in the same file.
  3317. %s in the filename will be replaced by the current file
  3318. name (without the directory part). Archiving to a different file
  3319. is useful to keep archived entries from contributing to the
  3320. Org Agenda.
  3321. The archived entries will be filed as subtrees of the specified
  3322. headline. When the headline is omitted, the subtrees are simply
  3323. filed away at the end of the file, as top-level entries. Also in
  3324. the heading you can use %s to represent the file name, this can be
  3325. useful when using the same archive for a number of different files.
  3326. Here are a few examples:
  3327. \"%s_archive::\"
  3328. If the current file is Projects.org, archive in file
  3329. Projects.org_archive, as top-level trees. This is the default.
  3330. \"::* Archived Tasks\"
  3331. Archive in the current file, under the top-level headline
  3332. \"* Archived Tasks\".
  3333. \"~/org/archive.org::\"
  3334. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3335. \"~/org/archive.org::* From %s\"
  3336. Archive in file ~/org/archive.org (absolute path), under headlines
  3337. \"From FILENAME\" where file name is the current file name.
  3338. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3339. The \"datetree/\" string is special, signifying to archive
  3340. items to the datetree. Items are placed in either the CLOSED
  3341. date of the item, or the current date if there is no CLOSED date.
  3342. The heading will be a subentry to the current date. There doesn't
  3343. need to be a heading, but there always needs to be a slash after
  3344. datetree. For example, to store archived items directly in the
  3345. datetree, use \"~/org/datetree.org::datetree/\".
  3346. \"basement::** Finished Tasks\"
  3347. Archive in file ./basement (relative path), as level 3 trees
  3348. below the level 2 heading \"** Finished Tasks\".
  3349. You may define it locally by setting an ARCHIVE property. If
  3350. such a property is found in the file or in an entry, and anywhere
  3351. up the hierarchy, it will be used.
  3352. You can also set it for the whole file using the keyword-syntax:
  3353. #+ARCHIVE: basement::** Finished Tasks"
  3354. :group 'org-archive
  3355. :type 'string)
  3356. (defcustom org-agenda-skip-archived-trees t
  3357. "Non-nil means the agenda will skip any items located in archived trees.
  3358. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3359. variable is no longer recommended, you should leave it at the value t.
  3360. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3361. :group 'org-archive
  3362. :group 'org-agenda-skip
  3363. :type 'boolean)
  3364. (defcustom org-columns-skip-archived-trees t
  3365. "Non-nil means ignore archived trees when creating column view."
  3366. :group 'org-archive
  3367. :group 'org-properties
  3368. :type 'boolean)
  3369. (defcustom org-cycle-open-archived-trees nil
  3370. "Non-nil means `org-cycle' will open archived trees.
  3371. An archived tree is a tree marked with the tag ARCHIVE.
  3372. When nil, archived trees will stay folded. You can still open them with
  3373. normal outline commands like `show-all', but not with the cycling commands."
  3374. :group 'org-archive
  3375. :group 'org-cycle
  3376. :type 'boolean)
  3377. (defcustom org-sparse-tree-open-archived-trees nil
  3378. "Non-nil means sparse tree construction shows matches in archived trees.
  3379. When nil, matches in these trees are highlighted, but the trees are kept in
  3380. collapsed state."
  3381. :group 'org-archive
  3382. :group 'org-sparse-trees
  3383. :type 'boolean)
  3384. (defcustom org-sparse-tree-default-date-type nil
  3385. "The default date type when building a sparse tree.
  3386. When this is nil, a date is a scheduled or a deadline timestamp.
  3387. Otherwise, these types are allowed:
  3388. all: all timestamps
  3389. active: only active timestamps (<...>)
  3390. inactive: only inactive timestamps ([...])
  3391. scheduled: only scheduled timestamps
  3392. deadline: only deadline timestamps"
  3393. :type '(choice (const :tag "Scheduled or deadline" nil)
  3394. (const :tag "All timestamps" all)
  3395. (const :tag "Only active timestamps" active)
  3396. (const :tag "Only inactive timestamps" inactive)
  3397. (const :tag "Only scheduled timestamps" scheduled)
  3398. (const :tag "Only deadline timestamps" deadline)
  3399. (const :tag "Only closed timestamps" closed))
  3400. :version "26.1"
  3401. :package-version '(Org . "8.3")
  3402. :group 'org-sparse-trees)
  3403. (defun org-cycle-hide-archived-subtrees (state)
  3404. "Re-hide all archived subtrees after a visibility state change.
  3405. STATE should be one of the symbols listed in the docstring of
  3406. `org-cycle-hook'."
  3407. (when (and (not org-cycle-open-archived-trees)
  3408. (not (memq state '(overview folded))))
  3409. (save-excursion
  3410. (let* ((globalp (memq state '(contents all)))
  3411. (beg (if globalp (point-min) (point)))
  3412. (end (if globalp (point-max) (org-end-of-subtree t))))
  3413. (org-hide-archived-subtrees beg end)
  3414. (goto-char beg)
  3415. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  3416. (message "%s" (substitute-command-keys
  3417. "Subtree is archived and stays closed. Use \
  3418. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  3419. (defun org-force-cycle-archived ()
  3420. "Cycle subtree even if it is archived."
  3421. (interactive)
  3422. (setq this-command 'org-cycle)
  3423. (let ((org-cycle-open-archived-trees t))
  3424. (call-interactively 'org-cycle)))
  3425. (defun org-hide-archived-subtrees (beg end)
  3426. "Re-hide all archived subtrees after a visibility state change."
  3427. (org-with-wide-buffer
  3428. (let ((case-fold-search nil)
  3429. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  3430. (goto-char beg)
  3431. ;; Include headline point is currently on.
  3432. (beginning-of-line)
  3433. (while (and (< (point) end) (re-search-forward re end t))
  3434. (when (member org-archive-tag (org-get-tags nil t))
  3435. (org-flag-subtree t)
  3436. (org-end-of-subtree t))))))
  3437. (defun org-flag-subtree (flag)
  3438. (save-excursion
  3439. (org-back-to-heading t)
  3440. (org-flag-region (line-end-position)
  3441. (progn (org-end-of-subtree t) (point))
  3442. flag
  3443. 'outline)))
  3444. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  3445. ;; Declare Column View Code
  3446. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  3447. (declare-function org-columns-compute "org-colview" (property))
  3448. ;; Declare ID code
  3449. (declare-function org-id-store-link "org-id")
  3450. (declare-function org-id-locations-load "org-id")
  3451. (declare-function org-id-locations-save "org-id")
  3452. (defvar org-id-track-globally)
  3453. ;;; Variables for pre-computed regular expressions, all buffer local
  3454. (defvar-local org-todo-regexp nil
  3455. "Matches any of the TODO state keywords.
  3456. Since TODO keywords are case-sensitive, `case-fold-search' is
  3457. expected to be bound to nil when matching against this regexp.")
  3458. (defvar-local org-not-done-regexp nil
  3459. "Matches any of the TODO state keywords except the last one.
  3460. Since TODO keywords are case-sensitive, `case-fold-search' is
  3461. expected to be bound to nil when matching against this regexp.")
  3462. (defvar-local org-not-done-heading-regexp nil
  3463. "Matches a TODO headline that is not done.
  3464. Since TODO keywords are case-sensitive, `case-fold-search' is
  3465. expected to be bound to nil when matching against this regexp.")
  3466. (defvar-local org-todo-line-regexp nil
  3467. "Matches a headline and puts TODO state into group 2 if present.
  3468. Since TODO keywords are case-sensitive, `case-fold-search' is
  3469. expected to be bound to nil when matching against this regexp.")
  3470. (defvar-local org-complex-heading-regexp nil
  3471. "Matches a headline and puts everything into groups:
  3472. group 1: Stars
  3473. group 2: The TODO keyword, maybe
  3474. group 3: Priority cookie
  3475. group 4: True headline
  3476. group 5: Tags
  3477. Since TODO keywords are case-sensitive, `case-fold-search' is
  3478. expected to be bound to nil when matching against this regexp.")
  3479. (defvar-local org-complex-heading-regexp-format nil
  3480. "Printf format to make regexp to match an exact headline.
  3481. This regexp will match the headline of any node which has the
  3482. exact headline text that is put into the format, but may have any
  3483. TODO state, priority and tags.")
  3484. (defvar-local org-todo-line-tags-regexp nil
  3485. "Matches a headline and puts TODO state into group 2 if present.
  3486. Also put tags into group 4 if tags are present.")
  3487. (defconst org-plain-time-of-day-regexp
  3488. (concat
  3489. "\\(\\<[012]?[0-9]"
  3490. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3491. "\\(--?"
  3492. "\\(\\<[012]?[0-9]"
  3493. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3494. "\\)?")
  3495. "Regular expression to match a plain time or time range.
  3496. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3497. groups carry important information:
  3498. 0 the full match
  3499. 1 the first time, range or not
  3500. 8 the second time, if it is a range.")
  3501. (defconst org-plain-time-extension-regexp
  3502. (concat
  3503. "\\(\\<[012]?[0-9]"
  3504. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3505. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  3506. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  3507. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3508. groups carry important information:
  3509. 0 the full match
  3510. 7 hours of duration
  3511. 9 minutes of duration")
  3512. (defconst org-stamp-time-of-day-regexp
  3513. (concat
  3514. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  3515. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  3516. "\\(--?"
  3517. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  3518. "Regular expression to match a timestamp time or time range.
  3519. After a match, the following groups carry important information:
  3520. 0 the full match
  3521. 1 date plus weekday, for back referencing to make sure both times are on the same day
  3522. 2 the first time, range or not
  3523. 4 the second time, if it is a range.")
  3524. (defconst org-startup-options
  3525. '(("fold" org-startup-folded t)
  3526. ("overview" org-startup-folded t)
  3527. ("nofold" org-startup-folded nil)
  3528. ("showall" org-startup-folded nil)
  3529. ("showeverything" org-startup-folded showeverything)
  3530. ("content" org-startup-folded content)
  3531. ("indent" org-startup-indented t)
  3532. ("noindent" org-startup-indented nil)
  3533. ("num" org-startup-numeroted t)
  3534. ("nonum" org-startup-numeroted nil)
  3535. ("hidestars" org-hide-leading-stars t)
  3536. ("showstars" org-hide-leading-stars nil)
  3537. ("odd" org-odd-levels-only t)
  3538. ("oddeven" org-odd-levels-only nil)
  3539. ("align" org-startup-align-all-tables t)
  3540. ("noalign" org-startup-align-all-tables nil)
  3541. ("shrink" org-startup-shrink-all-tables t)
  3542. ("inlineimages" org-startup-with-inline-images t)
  3543. ("noinlineimages" org-startup-with-inline-images nil)
  3544. ("latexpreview" org-startup-with-latex-preview t)
  3545. ("nolatexpreview" org-startup-with-latex-preview nil)
  3546. ("customtime" org-display-custom-times t)
  3547. ("logdone" org-log-done time)
  3548. ("lognotedone" org-log-done note)
  3549. ("nologdone" org-log-done nil)
  3550. ("lognoteclock-out" org-log-note-clock-out t)
  3551. ("nolognoteclock-out" org-log-note-clock-out nil)
  3552. ("logrepeat" org-log-repeat state)
  3553. ("lognoterepeat" org-log-repeat note)
  3554. ("logdrawer" org-log-into-drawer t)
  3555. ("nologdrawer" org-log-into-drawer nil)
  3556. ("logstatesreversed" org-log-states-order-reversed t)
  3557. ("nologstatesreversed" org-log-states-order-reversed nil)
  3558. ("nologrepeat" org-log-repeat nil)
  3559. ("logreschedule" org-log-reschedule time)
  3560. ("lognotereschedule" org-log-reschedule note)
  3561. ("nologreschedule" org-log-reschedule nil)
  3562. ("logredeadline" org-log-redeadline time)
  3563. ("lognoteredeadline" org-log-redeadline note)
  3564. ("nologredeadline" org-log-redeadline nil)
  3565. ("logrefile" org-log-refile time)
  3566. ("lognoterefile" org-log-refile note)
  3567. ("nologrefile" org-log-refile nil)
  3568. ("fninline" org-footnote-define-inline t)
  3569. ("nofninline" org-footnote-define-inline nil)
  3570. ("fnlocal" org-footnote-section nil)
  3571. ("fnauto" org-footnote-auto-label t)
  3572. ("fnprompt" org-footnote-auto-label nil)
  3573. ("fnconfirm" org-footnote-auto-label confirm)
  3574. ("fnplain" org-footnote-auto-label plain)
  3575. ("fnadjust" org-footnote-auto-adjust t)
  3576. ("nofnadjust" org-footnote-auto-adjust nil)
  3577. ("constcgs" constants-unit-system cgs)
  3578. ("constSI" constants-unit-system SI)
  3579. ("noptag" org-tag-persistent-alist nil)
  3580. ("hideblocks" org-hide-block-startup t)
  3581. ("nohideblocks" org-hide-block-startup nil)
  3582. ("beamer" org-startup-with-beamer-mode t)
  3583. ("entitiespretty" org-pretty-entities t)
  3584. ("entitiesplain" org-pretty-entities nil))
  3585. "Variable associated with STARTUP options for Org.
  3586. Each element is a list of three items: the startup options (as written
  3587. in the #+STARTUP line), the corresponding variable, and the value to set
  3588. this variable to if the option is found. An optional forth element PUSH
  3589. means to push this value onto the list in the variable.")
  3590. (defcustom org-group-tags t
  3591. "When non-nil (the default), use group tags.
  3592. This can be turned on/off through `org-toggle-tags-groups'."
  3593. :group 'org-tags
  3594. :group 'org-startup
  3595. :type 'boolean)
  3596. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  3597. (defun org-toggle-tags-groups ()
  3598. "Toggle support for group tags.
  3599. Support for group tags is controlled by the option
  3600. `org-group-tags', which is non-nil by default."
  3601. (interactive)
  3602. (setq org-group-tags (not org-group-tags))
  3603. (cond ((and (derived-mode-p 'org-agenda-mode)
  3604. org-group-tags)
  3605. (org-agenda-redo))
  3606. ((derived-mode-p 'org-mode)
  3607. (let ((org-inhibit-startup t)) (org-mode))))
  3608. (message "Groups tags support has been turned %s"
  3609. (if org-group-tags "on" "off")))
  3610. (defun org--tag-add-to-alist (alist1 alist2)
  3611. "Merge tags from ALIST1 into ALIST2.
  3612. Duplicates tags outside a group are removed. Keywords and order
  3613. are preserved.
  3614. The function assumes ALIST1 and ALIST2 are proper tag alists.
  3615. See `org-tag-alist' for their structure."
  3616. (cond
  3617. ((null alist2) alist1)
  3618. ((null alist1) alist2)
  3619. (t
  3620. (let ((to-add nil)
  3621. (group-flag nil))
  3622. (dolist (tag-pair alist1)
  3623. (pcase tag-pair
  3624. (`(,(or :startgrouptag :startgroup))
  3625. (setq group-flag t)
  3626. (push tag-pair to-add))
  3627. (`(,(or :endgrouptag :endgroup))
  3628. (setq group-flag nil)
  3629. (push tag-pair to-add))
  3630. (`(,(or :grouptags :newline))
  3631. (push tag-pair to-add))
  3632. (`(,tag . ,_)
  3633. ;; Remove duplicates from ALIST1, unless they are in
  3634. ;; a group. Indeed, it makes sense to have a tag appear in
  3635. ;; multiple groups.
  3636. (when (or group-flag (not (assoc tag alist2)))
  3637. (push tag-pair to-add)))
  3638. (_ (error "Invalid association in tag alist: %S" tag-pair))))
  3639. ;; Preserve order of ALIST1.
  3640. (append (nreverse to-add) alist2)))))
  3641. (defun org-priority-to-value (s)
  3642. "Convert priority string S to its numeric value."
  3643. (or (save-match-data
  3644. (and (string-match "\\([0-9]+\\)" s)
  3645. (string-to-number (match-string 1 s))))
  3646. (string-to-char s)))
  3647. (defun org-set-regexps-and-options (&optional tags-only)
  3648. "Precompute regular expressions used in the current buffer.
  3649. When optional argument TAGS-ONLY is non-nil, only compute tags
  3650. related expressions."
  3651. (when (derived-mode-p 'org-mode)
  3652. (let ((alist (org-collect-keywords
  3653. (append '("FILETAGS" "TAGS")
  3654. (and (not tags-only)
  3655. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  3656. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  3657. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))
  3658. '("ARCHIVE" "CATEGORY" "COLUMNS" "PRIORITIES"))))
  3659. ;; Startup options. Get this early since it does change
  3660. ;; behavior for other options (e.g., tags).
  3661. (let ((startup (cl-mapcan (lambda (value) (split-string value))
  3662. (cdr (assoc "STARTUP" alist)))))
  3663. (dolist (option startup)
  3664. (pcase (assoc-string option org-startup-options t)
  3665. (`(,_ ,variable ,value t)
  3666. (unless (listp (symbol-value variable))
  3667. (set (make-local-variable variable) nil))
  3668. (add-to-list variable value))
  3669. (`(,_ ,variable ,value . ,_)
  3670. (set (make-local-variable variable) value))
  3671. (_ nil))))
  3672. (setq-local org-file-tags
  3673. (mapcar #'org-add-prop-inherited
  3674. (cl-mapcan (lambda (value)
  3675. (cl-mapcan
  3676. (lambda (k) (org-split-string k ":"))
  3677. (split-string value)))
  3678. (cdr (assoc "FILETAGS" alist)))))
  3679. (setq org-current-tag-alist
  3680. (org--tag-add-to-alist
  3681. org-tag-persistent-alist
  3682. (let ((tags (mapconcat #'identity
  3683. (cdr (assoc "TAGS" alist))
  3684. "\n")))
  3685. (if (org-string-nw-p tags) (org-tag-string-to-alist tags)
  3686. org-tag-alist))))
  3687. (setq org-tag-groups-alist
  3688. (org-tag-alist-to-groups org-current-tag-alist))
  3689. (unless tags-only
  3690. ;; Properties.
  3691. (let ((properties nil))
  3692. (dolist (value (cdr (assoc "PROPERTY" alist)))
  3693. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  3694. (setq properties (org--update-property-plist
  3695. (match-string-no-properties 1 value)
  3696. (match-string-no-properties 2 value)
  3697. properties))))
  3698. (setq-local org-keyword-properties properties))
  3699. ;; Archive location.
  3700. (let ((archive (cdr (assoc "ARCHIVE" alist))))
  3701. (when archive (setq-local org-archive-location archive)))
  3702. ;; Category.
  3703. (let ((category (cdr (assoc "CATEGORY" alist))))
  3704. (when category
  3705. (setq-local org-category (intern category))
  3706. (setq-local org-keyword-properties
  3707. (org--update-property-plist
  3708. "CATEGORY" category org-keyword-properties))))
  3709. ;; Columns.
  3710. (let ((column (cdr (assoc "COLUMNS" alist))))
  3711. (when column (setq-local org-columns-default-format column)))
  3712. ;; Constants.
  3713. (let ((store nil))
  3714. (dolist (pair (cl-mapcan #'split-string
  3715. (cdr (assoc "CONSTANTS" alist))))
  3716. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" pair)
  3717. (let* ((name (match-string 1 pair))
  3718. (value (match-string 2 pair))
  3719. (old (assoc name store)))
  3720. (if old (setcdr old value)
  3721. (push (cons name value) store)))))
  3722. (setq org-table-formula-constants-local store))
  3723. ;; Link abbreviations.
  3724. (let ((links
  3725. (delq nil
  3726. (mapcar
  3727. (lambda (value)
  3728. (and (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  3729. (cons (match-string-no-properties 1 value)
  3730. (match-string-no-properties 2 value))))
  3731. (cdr (assoc "LINK" alist))))))
  3732. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  3733. ;; Priorities.
  3734. (let ((value (cdr (assoc "PRIORITIES" alist))))
  3735. (pcase (and value (split-string value))
  3736. (`(,high ,low ,default . ,_)
  3737. (setq-local org-highest-priority (org-priority-to-value high))
  3738. (setq-local org-lowest-priority (org-priority-to-value low))
  3739. (setq-local org-default-priority (org-priority-to-value default)))))
  3740. ;; Scripts.
  3741. (let ((value (cdr (assoc "OPTIONS" alist))))
  3742. (dolist (option value)
  3743. (when (string-match "\\^:\\(t\\|nil\\|{}\\)" option)
  3744. (setq-local org-use-sub-superscripts
  3745. (read (match-string 1 option))))))
  3746. ;; TODO keywords.
  3747. (setq-local org-todo-kwd-alist nil)
  3748. (setq-local org-todo-key-alist nil)
  3749. (setq-local org-todo-key-trigger nil)
  3750. (setq-local org-todo-keywords-1 nil)
  3751. (setq-local org-done-keywords nil)
  3752. (setq-local org-todo-heads nil)
  3753. (setq-local org-todo-sets nil)
  3754. (setq-local org-todo-log-states nil)
  3755. (let ((todo-sequences
  3756. (or (append (mapcar (lambda (value)
  3757. (cons 'type (split-string value)))
  3758. (cdr (assoc "TYP_TODO" alist)))
  3759. (mapcar (lambda (value)
  3760. (cons 'sequence (split-string value)))
  3761. (append (cdr (assoc "TODO" alist))
  3762. (cdr (assoc "SEQ_TODO" alist)))))
  3763. (let ((d (default-value 'org-todo-keywords)))
  3764. (if (not (stringp (car d))) d
  3765. ;; XXX: Backward compatibility code.
  3766. (list (cons org-todo-interpretation d)))))))
  3767. (dolist (sequence todo-sequences)
  3768. (let* ((sequence (or (run-hook-with-args-until-success
  3769. 'org-todo-setup-filter-hook sequence)
  3770. sequence))
  3771. (sequence-type (car sequence))
  3772. (keywords (cdr sequence))
  3773. (sep (member "|" keywords))
  3774. names alist)
  3775. (dolist (k (remove "|" keywords))
  3776. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  3777. k)
  3778. (error "Invalid TODO keyword %s" k))
  3779. (let ((name (match-string 1 k))
  3780. (key (match-string 2 k))
  3781. (log (org-extract-log-state-settings k)))
  3782. (push name names)
  3783. (push (cons name (and key (string-to-char key))) alist)
  3784. (when log (push log org-todo-log-states))))
  3785. (let* ((names (nreverse names))
  3786. (done (if sep (org-remove-keyword-keys (cdr sep))
  3787. (last names)))
  3788. (head (car names))
  3789. (tail (list sequence-type head (car done) (org-last done))))
  3790. (add-to-list 'org-todo-heads head 'append)
  3791. (push names org-todo-sets)
  3792. (setq org-done-keywords (append org-done-keywords done nil))
  3793. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  3794. (setq org-todo-key-alist
  3795. (append org-todo-key-alist
  3796. (and alist
  3797. (append '((:startgroup))
  3798. (nreverse alist)
  3799. '((:endgroup))))))
  3800. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  3801. (setq org-todo-sets (nreverse org-todo-sets)
  3802. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  3803. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  3804. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  3805. ;; Compute the regular expressions and other local variables.
  3806. ;; Using `org-outline-regexp-bol' would complicate them much,
  3807. ;; because of the fixed white space at the end of that string.
  3808. (unless org-done-keywords
  3809. (setq org-done-keywords
  3810. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  3811. (setq org-not-done-keywords
  3812. (org-delete-all org-done-keywords
  3813. (copy-sequence org-todo-keywords-1))
  3814. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  3815. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  3816. org-not-done-heading-regexp
  3817. (format org-heading-keyword-regexp-format org-not-done-regexp)
  3818. org-todo-line-regexp
  3819. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  3820. org-complex-heading-regexp
  3821. (concat "^\\(\\*+\\)"
  3822. "\\(?: +" org-todo-regexp "\\)?"
  3823. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3824. "\\(?: +\\(.*?\\)\\)??"
  3825. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  3826. "[ \t]*$")
  3827. org-complex-heading-regexp-format
  3828. (concat "^\\(\\*+\\)"
  3829. "\\(?: +" org-todo-regexp "\\)?"
  3830. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3831. "\\(?: +"
  3832. ;; Stats cookies can be stuck to body.
  3833. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  3834. "\\(%s\\)"
  3835. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  3836. "\\)"
  3837. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  3838. "[ \t]*$")
  3839. org-todo-line-tags-regexp
  3840. (concat "^\\(\\*+\\)"
  3841. "\\(?: +" org-todo-regexp "\\)?"
  3842. "\\(?: +\\(.*?\\)\\)??"
  3843. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  3844. "[ \t]*$"))
  3845. (org-compute-latex-and-related-regexp)))))
  3846. (defun org-collect-keywords (keywords &optional unique directory)
  3847. "Return values for KEYWORDS in current buffer, as an alist.
  3848. KEYWORDS is a list of strings. Return value is a list of
  3849. elements with the pattern:
  3850. (NAME . LIST-OF-VALUES)
  3851. where NAME is the upcase name of the keyword, and LIST-OF-VALUES
  3852. is a list of non-empty values, as strings, in order of appearance
  3853. in the buffer.
  3854. When KEYWORD appears in UNIQUE list, LIST-OF-VALUE is its first
  3855. value, empty or not, appearing in the buffer, as a string.
  3856. When KEYWORD appears in DIRECTORIES, each value is a cons cell:
  3857. (VALUE . DIRECTORY)
  3858. where VALUE is the regular value, and DIRECTORY is the variable
  3859. `default-directory' for the buffer containing the keyword. This
  3860. is important for values containing relative file names, since the
  3861. function follows SETUPFILE keywords, and may change its working
  3862. directory."
  3863. (let* ((keywords (cons "SETUPFILE" (mapcar #'upcase keywords)))
  3864. (unique (mapcar #'upcase unique))
  3865. (alist (org--collect-keywords-1
  3866. keywords unique directory
  3867. (and buffer-file-name (list buffer-file-name))
  3868. nil)))
  3869. ;; Re-order results.
  3870. (dolist (entry alist)
  3871. (pcase entry
  3872. (`(,_ . ,(and value (pred consp)))
  3873. (setcdr entry (nreverse value)))))
  3874. (nreverse alist)))
  3875. (defun org--collect-keywords-1 (keywords unique directory files alist)
  3876. (org-with-point-at 1
  3877. (let ((case-fold-search t)
  3878. (regexp (org-make-options-regexp keywords)))
  3879. (while (and keywords (re-search-forward regexp nil t))
  3880. (let ((element (org-element-at-point)))
  3881. (when (eq 'keyword (org-element-type element))
  3882. (let ((value (org-element-property :value element)))
  3883. (pcase (org-element-property :key element)
  3884. ("SETUPFILE"
  3885. (when (and (org-string-nw-p value)
  3886. (not buffer-read-only)) ;FIXME: bug in Gnus?
  3887. (let* ((uri (org-strip-quotes value))
  3888. (uri-is-url (org-file-url-p uri))
  3889. (uri (if uri-is-url
  3890. uri
  3891. (expand-file-name uri))))
  3892. (unless (member uri files)
  3893. (with-temp-buffer
  3894. (unless uri-is-url
  3895. (setq default-directory (file-name-directory uri)))
  3896. (let ((contents (org-file-contents uri :noerror)))
  3897. (when contents
  3898. (insert contents)
  3899. ;; Fake Org mode: `org-element-at-point'
  3900. ;; doesn't need full set-up.
  3901. (let ((major-mode 'org-mode))
  3902. (setq alist
  3903. (org--collect-keywords-1
  3904. keywords unique directory
  3905. (cons uri files)
  3906. alist))))))))))
  3907. (keyword
  3908. (let ((entry (assoc keyword alist))
  3909. (final
  3910. (cond ((not (member keyword directory)) value)
  3911. (buffer-file-name
  3912. (cons value
  3913. (file-name-directory buffer-file-name)))
  3914. (t (cons value default-directory)))))
  3915. (cond ((member keyword unique)
  3916. (push (cons keyword final) alist)
  3917. (setq keywords (remove keyword keywords))
  3918. (setq regexp (org-make-options-regexp keywords)))
  3919. ((not (org-string-nw-p value)) nil)
  3920. ((null entry) (push (list keyword final) alist))
  3921. (t (push final (cdr entry)))))))))))
  3922. alist)))
  3923. (defun org-tag-string-to-alist (s)
  3924. "Return tag alist associated to string S.
  3925. S is a value for TAGS keyword or produced with
  3926. `org-tag-alist-to-string'. Return value is an alist suitable for
  3927. `org-tag-alist' or `org-tag-persistent-alist'."
  3928. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  3929. (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
  3930. "\\(?:(\\(.\\))\\)?\\'"))
  3931. alist group-flag)
  3932. (dolist (tokens lines (cdr (nreverse alist)))
  3933. (push '(:newline) alist)
  3934. (while tokens
  3935. (let ((token (pop tokens)))
  3936. (pcase token
  3937. ("{"
  3938. (push '(:startgroup) alist)
  3939. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3940. ("}"
  3941. (push '(:endgroup) alist)
  3942. (setq group-flag nil))
  3943. ("["
  3944. (push '(:startgrouptag) alist)
  3945. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3946. ("]"
  3947. (push '(:endgrouptag) alist)
  3948. (setq group-flag nil))
  3949. (":"
  3950. (push '(:grouptags) alist))
  3951. ((guard (string-match tag-re token))
  3952. (let ((tag (match-string 1 token))
  3953. (key (and (match-beginning 2)
  3954. (string-to-char (match-string 2 token)))))
  3955. ;; Push all tags in groups, no matter if they already
  3956. ;; appear somewhere else in the list.
  3957. (when (or group-flag (not (assoc tag alist)))
  3958. (push (cons tag key) alist))))))))))
  3959. (defun org-tag-alist-to-string (alist &optional skip-key)
  3960. "Return tag string associated to ALIST.
  3961. ALIST is an alist, as defined in `org-tag-alist' or
  3962. `org-tag-persistent-alist', or produced with
  3963. `org-tag-string-to-alist'.
  3964. Return value is a string suitable as a value for \"TAGS\"
  3965. keyword.
  3966. When optional argument SKIP-KEY is non-nil, skip selection keys
  3967. next to tags."
  3968. (mapconcat (lambda (token)
  3969. (pcase token
  3970. (`(:startgroup) "{")
  3971. (`(:endgroup) "}")
  3972. (`(:startgrouptag) "[")
  3973. (`(:endgrouptag) "]")
  3974. (`(:grouptags) ":")
  3975. (`(:newline) "\\n")
  3976. ((and
  3977. (guard (not skip-key))
  3978. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  3979. (format "%s(%c)" tag key))
  3980. (`(,(and tag (pred stringp)) . ,_) tag)
  3981. (_ (user-error "Invalid tag token: %S" token))))
  3982. alist
  3983. " "))
  3984. (defun org-tag-alist-to-groups (alist)
  3985. "Return group alist from tag ALIST.
  3986. ALIST is an alist, as defined in `org-tag-alist' or
  3987. `org-tag-persistent-alist', or produced with
  3988. `org-tag-string-to-alist'. Return value is an alist following
  3989. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  3990. a string, summarizing TAGS, as a list of strings."
  3991. (let (groups group-status current-group)
  3992. (dolist (token alist (nreverse groups))
  3993. (pcase token
  3994. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  3995. (`(,(or :endgroup :endgrouptag))
  3996. (when (eq group-status 'append)
  3997. (push (nreverse current-group) groups))
  3998. (setq group-status nil current-group nil))
  3999. (`(:grouptags) (setq group-status 'append))
  4000. ((and `(,tag . ,_) (guard group-status))
  4001. (if (eq group-status 'append) (push tag current-group)
  4002. (setq current-group (list tag))))
  4003. (_ nil)))))
  4004. (defvar org--file-cache (make-hash-table :test #'equal)
  4005. "Hash table to store contents of files referenced via a URL.
  4006. This is the cache of file URLs read using `org-file-contents'.")
  4007. (defun org-reset-file-cache ()
  4008. "Reset the cache of files downloaded by `org-file-contents'."
  4009. (clrhash org--file-cache))
  4010. (defun org-file-url-p (file)
  4011. "Non-nil if FILE is a URL."
  4012. (require 'ffap)
  4013. (string-match-p ffap-url-regexp file))
  4014. (defun org-file-contents (file &optional noerror nocache)
  4015. "Return the contents of FILE, as a string.
  4016. FILE can be a file name or URL.
  4017. If FILE is a URL, download the contents. If the URL contents are
  4018. already cached in the `org--file-cache' hash table, the download step
  4019. is skipped.
  4020. If NOERROR is non-nil, ignore the error when unable to read the FILE
  4021. from file or URL, and return nil.
  4022. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  4023. is available. This option applies only if FILE is a URL."
  4024. (let* ((is-url (org-file-url-p file))
  4025. (cache (and is-url
  4026. (not nocache)
  4027. (gethash file org--file-cache))))
  4028. (cond
  4029. (cache)
  4030. (is-url
  4031. (with-current-buffer (url-retrieve-synchronously file)
  4032. (goto-char (point-min))
  4033. ;; Move point to after the url-retrieve header.
  4034. (search-forward "\n\n" nil :move)
  4035. ;; Search for the success code only in the url-retrieve header.
  4036. (if (save-excursion
  4037. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  4038. ;; Update the cache `org--file-cache' and return contents.
  4039. (puthash file
  4040. (buffer-substring-no-properties (point) (point-max))
  4041. org--file-cache)
  4042. (funcall (if noerror #'message #'user-error)
  4043. "Unable to fetch file from %S"
  4044. file)
  4045. nil)))
  4046. (t
  4047. (with-temp-buffer
  4048. (condition-case nil
  4049. (progn
  4050. (insert-file-contents file)
  4051. (buffer-string))
  4052. (file-error
  4053. (funcall (if noerror #'message #'user-error)
  4054. "Unable to read file %S"
  4055. file)
  4056. nil)))))))
  4057. (defun org-extract-log-state-settings (x)
  4058. "Extract the log state setting from a TODO keyword string.
  4059. This will extract info from a string like \"WAIT(w@/!)\"."
  4060. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4061. (let ((kw (match-string 1 x))
  4062. (log1 (and (match-end 3) (match-string 3 x)))
  4063. (log2 (and (match-end 4) (match-string 4 x))))
  4064. (and (or log1 log2)
  4065. (list kw
  4066. (and log1 (if (equal log1 "!") 'time 'note))
  4067. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4068. (defun org-remove-keyword-keys (list)
  4069. "Remove a pair of parenthesis at the end of each string in LIST."
  4070. (mapcar (lambda (x)
  4071. (if (string-match "(.*)$" x)
  4072. (substring x 0 (match-beginning 0))
  4073. x))
  4074. list))
  4075. (defun org-assign-fast-keys (alist)
  4076. "Assign fast keys to a keyword-key alist.
  4077. Respect keys that are already there."
  4078. (let (new e (alt ?0))
  4079. (while (setq e (pop alist))
  4080. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4081. (cdr e)) ;; Key already assigned.
  4082. (push e new)
  4083. (let ((clist (string-to-list (downcase (car e))))
  4084. (used (append new alist)))
  4085. (when (= (car clist) ?@)
  4086. (pop clist))
  4087. (while (and clist (rassoc (car clist) used))
  4088. (pop clist))
  4089. (unless clist
  4090. (while (rassoc alt used)
  4091. (cl-incf alt)))
  4092. (push (cons (car e) (or (car clist) alt)) new))))
  4093. (nreverse new)))
  4094. ;;; Some variables used in various places
  4095. (defvar org-window-configuration nil
  4096. "Used in various places to store a window configuration.")
  4097. (defvar org-selected-window nil
  4098. "Used in various places to store a window configuration.")
  4099. (defvar org-finish-function nil
  4100. "Function to be called when `C-c C-c' is used.
  4101. This is for getting out of special buffers like capture.")
  4102. (defvar org-last-state)
  4103. ;; Defined somewhere in this file, but used before definition.
  4104. (defvar org-entities) ;; defined in org-entities.el
  4105. (defvar org-struct-menu)
  4106. (defvar org-org-menu)
  4107. (defvar org-tbl-menu)
  4108. ;;;; Define the Org mode
  4109. (defun org-before-change-function (_beg _end)
  4110. "Every change indicates that a table might need an update."
  4111. (setq org-table-may-need-update t))
  4112. (defvar org-mode-map)
  4113. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4114. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4115. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4116. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4117. (defvar bidi-paragraph-direction)
  4118. (defvar buffer-face-mode-face)
  4119. (require 'outline)
  4120. ;; Other stuff we need.
  4121. (require 'time-date)
  4122. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4123. (require 'easymenu)
  4124. (autoload 'easy-menu-add "easymenu")
  4125. (require 'overlay)
  4126. (require 'org-entities)
  4127. (require 'org-faces)
  4128. (require 'org-list)
  4129. (require 'org-pcomplete)
  4130. (require 'org-src)
  4131. (require 'org-footnote)
  4132. (require 'org-macro)
  4133. ;; babel
  4134. (require 'ob)
  4135. ;;;###autoload
  4136. (define-derived-mode org-mode outline-mode "Org"
  4137. "Outline-based notes management and organizer, alias
  4138. \"Carsten's outline-mode for keeping track of everything.\"
  4139. Org mode develops organizational tasks around a NOTES file which
  4140. contains information about projects as plain text. Org mode is
  4141. implemented on top of Outline mode, which is ideal to keep the content
  4142. of large files well structured. It supports ToDo items, deadlines and
  4143. time stamps, which magically appear in the diary listing of the Emacs
  4144. calendar. Tables are easily created with a built-in table editor.
  4145. Plain text URL-like links connect to websites, emails (VM), Usenet
  4146. messages (Gnus), BBDB entries, and any files related to the project.
  4147. For printing and sharing of notes, an Org file (or a part of it)
  4148. can be exported as a structured ASCII or HTML file.
  4149. The following commands are available:
  4150. \\{org-mode-map}"
  4151. (org-load-modules-maybe)
  4152. (org-install-agenda-files-menu)
  4153. (when org-link-descriptive (add-to-invisibility-spec '(org-link)))
  4154. (add-to-invisibility-spec '(org-hide-block . t))
  4155. (add-to-invisibility-spec '(org-hide-drawer . t))
  4156. (setq-local outline-regexp org-outline-regexp)
  4157. (setq-local outline-level 'org-outline-level)
  4158. (setq bidi-paragraph-direction 'left-to-right)
  4159. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4160. (unless org-display-table
  4161. (setq org-display-table (make-display-table)))
  4162. (set-display-table-slot
  4163. org-display-table 4
  4164. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4165. org-ellipsis)))
  4166. (setq buffer-display-table org-display-table))
  4167. (org-set-regexps-and-options)
  4168. (org-set-font-lock-defaults)
  4169. (when (and org-tag-faces (not org-tags-special-faces-re))
  4170. ;; tag faces set outside customize.... force initialization.
  4171. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4172. ;; Calc embedded
  4173. (setq-local calc-embedded-open-mode "# ")
  4174. ;; Modify a few syntax entries
  4175. (modify-syntax-entry ?\" "\"")
  4176. (modify-syntax-entry ?\\ "_")
  4177. (modify-syntax-entry ?~ "_")
  4178. (modify-syntax-entry ?< "(>")
  4179. (modify-syntax-entry ?> ")<")
  4180. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4181. ;; Activate before-change-function
  4182. (setq-local org-table-may-need-update t)
  4183. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4184. ;; Check for running clock before killing a buffer
  4185. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4186. ;; Initialize macros templates.
  4187. (org-macro-initialize-templates)
  4188. ;; Initialize radio targets.
  4189. (org-update-radio-target-regexp)
  4190. ;; Indentation.
  4191. (setq-local indent-line-function 'org-indent-line)
  4192. (setq-local indent-region-function 'org-indent-region)
  4193. ;; Filling and auto-filling.
  4194. (org-setup-filling)
  4195. ;; Comments.
  4196. (org-setup-comments-handling)
  4197. ;; Initialize cache.
  4198. (org-element-cache-reset)
  4199. ;; Beginning/end of defun
  4200. (setq-local beginning-of-defun-function 'org-backward-element)
  4201. (setq-local end-of-defun-function
  4202. (lambda ()
  4203. (if (not (org-at-heading-p))
  4204. (org-forward-element)
  4205. (org-forward-element)
  4206. (forward-char -1))))
  4207. ;; Next error for sparse trees
  4208. (setq-local next-error-function 'org-occur-next-match)
  4209. ;; Make commit log messages from Org documents easier.
  4210. (setq-local add-log-current-defun-function #'org-add-log-current-headline)
  4211. ;; Make sure dependence stuff works reliably, even for users who set it
  4212. ;; too late :-(
  4213. (if org-enforce-todo-dependencies
  4214. (add-hook 'org-blocker-hook
  4215. 'org-block-todo-from-children-or-siblings-or-parent)
  4216. (remove-hook 'org-blocker-hook
  4217. 'org-block-todo-from-children-or-siblings-or-parent))
  4218. (if org-enforce-todo-checkbox-dependencies
  4219. (add-hook 'org-blocker-hook
  4220. 'org-block-todo-from-checkboxes)
  4221. (remove-hook 'org-blocker-hook
  4222. 'org-block-todo-from-checkboxes))
  4223. ;; Align options lines
  4224. (setq-local
  4225. align-mode-rules-list
  4226. '((org-in-buffer-settings
  4227. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4228. (modes . '(org-mode)))))
  4229. ;; Make isearch reveal context
  4230. (setq-local outline-isearch-open-invisible-function
  4231. (lambda (&rest _) (org-show-context 'isearch)))
  4232. ;; Setup the pcomplete hooks
  4233. (setq-local pcomplete-command-completion-function #'org-pcomplete-initial)
  4234. (setq-local pcomplete-command-name-function #'org-command-at-point)
  4235. (setq-local pcomplete-default-completion-function #'ignore)
  4236. (setq-local pcomplete-parse-arguments-function #'org-parse-arguments)
  4237. (setq-local pcomplete-termination-string "")
  4238. (add-hook 'completion-at-point-functions
  4239. #'pcomplete-completions-at-point nil t)
  4240. (setq-local buffer-face-mode-face 'org-default)
  4241. ;; If empty file that did not turn on Org mode automatically, make
  4242. ;; it to.
  4243. (when (and org-insert-mode-line-in-empty-file
  4244. (called-interactively-p 'any)
  4245. (= (point-min) (point-max)))
  4246. (insert "# -*- mode: org -*-\n\n"))
  4247. (unless org-inhibit-startup
  4248. (org-unmodified
  4249. (when org-startup-with-beamer-mode (org-beamer-mode))
  4250. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4251. (org-table-map-tables
  4252. (cond ((and org-startup-align-all-tables
  4253. org-startup-shrink-all-tables)
  4254. (lambda () (org-table-align) (org-table-shrink)))
  4255. (org-startup-align-all-tables #'org-table-align)
  4256. (t #'org-table-shrink))
  4257. t))
  4258. (when org-startup-with-inline-images (org-display-inline-images))
  4259. (when org-startup-with-latex-preview (org-latex-preview '(16)))
  4260. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4261. (when org-startup-truncated (setq truncate-lines t))
  4262. (when org-startup-numeroted (require 'org-num) (org-num-mode 1))
  4263. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))))
  4264. ;; Activate `org-table-header-line-mode'
  4265. (when org-table-header-line-p
  4266. (org-table-header-line-mode 1))
  4267. ;; Try to set `org-hide' face correctly.
  4268. (let ((foreground (org-find-invisible-foreground)))
  4269. (when foreground
  4270. (set-face-foreground 'org-hide foreground))))
  4271. ;; Update `customize-package-emacs-version-alist'
  4272. (add-to-list 'customize-package-emacs-version-alist
  4273. '(Org ("8.0" . "24.4")
  4274. ("8.1" . "24.4")
  4275. ("8.2" . "24.4")
  4276. ("8.2.7" . "24.4")
  4277. ("8.3" . "26.1")
  4278. ("9.0" . "26.1")
  4279. ("9.1" . "26.1")
  4280. ("9.2" . "27.1")
  4281. ("9.3" . "27.1")
  4282. ("9.4" . "28.1")))
  4283. (defvar org-mode-transpose-word-syntax-table
  4284. (let ((st (make-syntax-table text-mode-syntax-table)))
  4285. (dolist (c org-emphasis-alist st)
  4286. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4287. (when (fboundp 'abbrev-table-put)
  4288. (abbrev-table-put org-mode-abbrev-table
  4289. :parents (list text-mode-abbrev-table)))
  4290. (defun org-find-invisible-foreground ()
  4291. (let ((candidates (remove
  4292. "unspecified-bg"
  4293. (nconc
  4294. (list (face-background 'default)
  4295. (face-background 'org-default))
  4296. (mapcar
  4297. (lambda (alist)
  4298. (when (boundp alist)
  4299. (cdr (assq 'background-color (symbol-value alist)))))
  4300. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4301. (list (face-foreground 'org-hide))))))
  4302. (car (remove nil candidates))))
  4303. (defun org-current-time (&optional rounding-minutes past)
  4304. "Current time, possibly rounded to ROUNDING-MINUTES.
  4305. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4306. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4307. the rounding returns a past time."
  4308. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4309. (car org-time-stamp-rounding-minutes)))
  4310. (now (current-time)))
  4311. (if (< r 1)
  4312. now
  4313. (let* ((time (decode-time now))
  4314. (res (apply #'encode-time 0 (* r (round (nth 1 time) r))
  4315. (nthcdr 2 time))))
  4316. (if (or (not past) (org-time-less-p res now))
  4317. res
  4318. (org-time-subtract res (* r 60)))))))
  4319. (defun org-today ()
  4320. "Return today date, considering `org-extend-today-until'."
  4321. (time-to-days
  4322. (org-time-since (* 3600 org-extend-today-until))))
  4323. ;;;; Font-Lock stuff, including the activators
  4324. (require 'font-lock)
  4325. (defconst org-match-sexp-depth 3
  4326. "Number of stacked braces for sub/superscript matching.")
  4327. (defun org-create-multibrace-regexp (left right n)
  4328. "Create a regular expression which will match a balanced sexp.
  4329. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4330. as single character strings.
  4331. The regexp returned will match the entire expression including the
  4332. delimiters. It will also define a single group which contains the
  4333. match except for the outermost delimiters. The maximum depth of
  4334. stacked delimiters is N. Escaping delimiters is not possible."
  4335. (let* ((nothing (concat "[^" left right "]*?"))
  4336. (or "\\|")
  4337. (re nothing)
  4338. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4339. (while (> n 1)
  4340. (setq n (1- n)
  4341. re (concat re or next)
  4342. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4343. (concat left "\\(" re "\\)" right)))
  4344. (defconst org-match-substring-regexp
  4345. (concat
  4346. "\\(\\S-\\)\\([_^]\\)\\("
  4347. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4348. "\\|"
  4349. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4350. "\\|"
  4351. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4352. "The regular expression matching a sub- or superscript.")
  4353. (defconst org-match-substring-with-braces-regexp
  4354. (concat
  4355. "\\(\\S-\\)\\([_^]\\)"
  4356. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4357. "The regular expression matching a sub- or superscript, forcing braces.")
  4358. (defvar org-emph-face nil)
  4359. (defun org-do-emphasis-faces (limit)
  4360. "Run through the buffer and emphasize strings."
  4361. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  4362. (car org-emphasis-regexp-components))))
  4363. (catch :exit
  4364. (while (re-search-forward quick-re limit t)
  4365. (let* ((marker (match-string 2))
  4366. (verbatim? (member marker '("~" "="))))
  4367. (when (save-excursion
  4368. (goto-char (match-beginning 0))
  4369. (and
  4370. ;; Do not match table hlines.
  4371. (not (and (equal marker "+")
  4372. (org-match-line
  4373. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  4374. ;; Do not match headline stars. Do not consider
  4375. ;; stars of a headline as closing marker for bold
  4376. ;; markup either.
  4377. (not (and (equal marker "*")
  4378. (save-excursion
  4379. (forward-char)
  4380. (skip-chars-backward "*")
  4381. (looking-at-p org-outline-regexp-bol))))
  4382. ;; Match full emphasis markup regexp.
  4383. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  4384. ;; Do not span over paragraph boundaries.
  4385. (not (string-match-p org-element-paragraph-separate
  4386. (match-string 2)))
  4387. ;; Do not span over cells in table rows.
  4388. (not (and (save-match-data (org-match-line "[ \t]*|"))
  4389. (string-match-p "|" (match-string 4))))))
  4390. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist))
  4391. (m (if org-hide-emphasis-markers 4 2)))
  4392. (font-lock-prepend-text-property
  4393. (match-beginning m) (match-end m) 'face face)
  4394. (when verbatim?
  4395. (org-remove-flyspell-overlays-in
  4396. (match-beginning 0) (match-end 0))
  4397. (remove-text-properties (match-beginning 2) (match-end 2)
  4398. '(display t invisible t intangible t)))
  4399. (add-text-properties (match-beginning 2) (match-end 2)
  4400. '(font-lock-multiline t org-emphasis t))
  4401. (when (and org-hide-emphasis-markers
  4402. (not (org-at-comment-p)))
  4403. (add-text-properties (match-end 4) (match-beginning 5)
  4404. '(invisible org-link))
  4405. (add-text-properties (match-beginning 3) (match-end 3)
  4406. '(invisible org-link)))
  4407. (throw :exit t))))))))
  4408. (defun org-emphasize (&optional char)
  4409. "Insert or change an emphasis, i.e. a font like bold or italic.
  4410. If there is an active region, change that region to a new emphasis.
  4411. If there is no region, just insert the marker characters and position
  4412. the cursor between them.
  4413. CHAR should be the marker character. If it is a space, it means to
  4414. remove the emphasis of the selected region.
  4415. If CHAR is not given (for example in an interactive call) it will be
  4416. prompted for."
  4417. (interactive)
  4418. (let ((erc org-emphasis-regexp-components)
  4419. (string "") beg end move s)
  4420. (if (org-region-active-p)
  4421. (setq beg (region-beginning)
  4422. end (region-end)
  4423. string (buffer-substring beg end))
  4424. (setq move t))
  4425. (unless char
  4426. (message "Emphasis marker or tag: [%s]"
  4427. (mapconcat #'car org-emphasis-alist ""))
  4428. (setq char (read-char-exclusive)))
  4429. (if (equal char ?\s)
  4430. (setq s ""
  4431. move nil)
  4432. (unless (assoc (char-to-string char) org-emphasis-alist)
  4433. (user-error "No such emphasis marker: \"%c\"" char))
  4434. (setq s (char-to-string char)))
  4435. (while (and (> (length string) 1)
  4436. (equal (substring string 0 1) (substring string -1))
  4437. (assoc (substring string 0 1) org-emphasis-alist))
  4438. (setq string (substring string 1 -1)))
  4439. (setq string (concat s string s))
  4440. (when beg (delete-region beg end))
  4441. (unless (or (bolp)
  4442. (string-match (concat "[" (nth 0 erc) "\n]")
  4443. (char-to-string (char-before (point)))))
  4444. (insert " "))
  4445. (unless (or (eobp)
  4446. (string-match (concat "[" (nth 1 erc) "\n]")
  4447. (char-to-string (char-after (point)))))
  4448. (insert " ") (backward-char 1))
  4449. (insert string)
  4450. (and move (backward-char 1))))
  4451. (defconst org-nonsticky-props
  4452. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  4453. (defsubst org-rear-nonsticky-at (pos)
  4454. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  4455. (defun org-activate-links (limit)
  4456. "Add link properties to links.
  4457. This includes angle, plain, and bracket links."
  4458. (catch :exit
  4459. (while (re-search-forward org-link-any-re limit t)
  4460. (let* ((start (match-beginning 0))
  4461. (end (match-end 0))
  4462. (visible-start (or (match-beginning 3) (match-beginning 2)))
  4463. (visible-end (or (match-end 3) (match-end 2)))
  4464. (style (cond ((eq ?< (char-after start)) 'angle)
  4465. ((eq ?\[ (char-after (1+ start))) 'bracket)
  4466. (t 'plain))))
  4467. (when (and (memq style org-highlight-links)
  4468. ;; Do not span over paragraph boundaries.
  4469. (not (string-match-p org-element-paragraph-separate
  4470. (match-string 0)))
  4471. ;; Do not confuse plain links with tags.
  4472. (not (and (eq style 'plain)
  4473. (let ((face (get-text-property
  4474. (max (1- start) (point-min)) 'face)))
  4475. (if (consp face) (memq 'org-tag face)
  4476. (eq 'org-tag face))))))
  4477. (let* ((link-object (save-excursion
  4478. (goto-char start)
  4479. (save-match-data (org-element-link-parser))))
  4480. (link (org-element-property :raw-link link-object))
  4481. (type (org-element-property :type link-object))
  4482. (path (org-element-property :path link-object))
  4483. (properties ;for link's visible part
  4484. (list
  4485. 'face (pcase (org-link-get-parameter type :face)
  4486. ((and (pred functionp) face) (funcall face path))
  4487. ((and (pred facep) face) face)
  4488. ((and (pred consp) face) face) ;anonymous
  4489. (_ 'org-link))
  4490. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  4491. 'highlight)
  4492. 'keymap (or (org-link-get-parameter type :keymap)
  4493. org-mouse-map)
  4494. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  4495. ((and (pred stringp) echo) echo)
  4496. ((and (pred functionp) echo) echo)
  4497. (_ (concat "LINK: " link)))
  4498. 'htmlize-link (pcase (org-link-get-parameter type
  4499. :htmlize-link)
  4500. ((and (pred functionp) f) (funcall f))
  4501. (_ `(:uri ,link)))
  4502. 'font-lock-multiline t)))
  4503. (org-remove-flyspell-overlays-in start end)
  4504. (org-rear-nonsticky-at end)
  4505. (if (not (eq 'bracket style))
  4506. (add-text-properties start end properties)
  4507. ;; Handle invisible parts in bracket links.
  4508. (remove-text-properties start end '(invisible nil))
  4509. (let ((hidden
  4510. (append `(invisible
  4511. ,(or (org-link-get-parameter type :display)
  4512. 'org-link))
  4513. properties)))
  4514. (add-text-properties start visible-start hidden)
  4515. (add-text-properties visible-start visible-end properties)
  4516. (add-text-properties visible-end end hidden)
  4517. (org-rear-nonsticky-at visible-start)
  4518. (org-rear-nonsticky-at visible-end)))
  4519. (let ((f (org-link-get-parameter type :activate-func)))
  4520. (when (functionp f)
  4521. (funcall f start end path (eq style 'bracket))))
  4522. (throw :exit t))))) ;signal success
  4523. nil))
  4524. (defun org-activate-code (limit)
  4525. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  4526. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4527. (remove-text-properties (match-beginning 0) (match-end 0)
  4528. '(display t invisible t intangible t))
  4529. t))
  4530. (defcustom org-src-fontify-natively t
  4531. "When non-nil, fontify code in code blocks.
  4532. See also the `org-block' face."
  4533. :type 'boolean
  4534. :version "26.1"
  4535. :package-version '(Org . "8.3")
  4536. :group 'org-appearance
  4537. :group 'org-babel)
  4538. (defcustom org-allow-promoting-top-level-subtree nil
  4539. "When non-nil, allow promoting a top level subtree.
  4540. The leading star of the top level headline will be replaced
  4541. by a #."
  4542. :type 'boolean
  4543. :version "24.1"
  4544. :group 'org-appearance)
  4545. (defun org-fontify-meta-lines-and-blocks (limit)
  4546. (condition-case nil
  4547. (org-fontify-meta-lines-and-blocks-1 limit)
  4548. (error (message "Org mode fontification error in %S at %d"
  4549. (current-buffer)
  4550. (line-number-at-pos)))))
  4551. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  4552. "Fontify #+ lines and blocks."
  4553. (let ((case-fold-search t))
  4554. (when (re-search-forward
  4555. (rx bol (group (zero-or-more blank) "#"
  4556. (group (group (or (seq "+" (one-or-more (any "a-zA-Z")) (optional ":"))
  4557. space
  4558. eol))
  4559. (optional (group "_" (group (one-or-more (any "a-zA-Z"))))))
  4560. (zero-or-more blank)
  4561. (group (group (zero-or-more (not (any " \t\n"))))
  4562. (zero-or-more blank)
  4563. (group (zero-or-more any)))))
  4564. limit t)
  4565. (let ((beg (match-beginning 0))
  4566. (end-of-beginline (match-end 0))
  4567. (block-start (match-end 0)) ; includes the \n at end of #+begin line
  4568. (block-end nil) ; will include \n after end of block content
  4569. (lang (match-string 7)) ; the language, if it is an src block
  4570. (bol-after-beginline (line-beginning-position 2))
  4571. (dc1 (downcase (match-string 2)))
  4572. (dc3 (downcase (match-string 3)))
  4573. (whole-blockline org-fontify-whole-block-delimiter-line)
  4574. beg-of-endline end-of-endline nl-before-endline quoting block-type)
  4575. (cond
  4576. ((and (match-end 4) (equal dc3 "+begin"))
  4577. ;; Truly a block
  4578. (setq block-type (downcase (match-string 5))
  4579. quoting (member block-type org-protecting-blocks)) ; src, example, export, maybe more
  4580. (when (re-search-forward
  4581. (rx-to-string `(group bol (or (seq (one-or-more "*") space)
  4582. (seq (zero-or-more blank)
  4583. "#+end"
  4584. ,(match-string 4)
  4585. word-end
  4586. (zero-or-more any)))))
  4587. nil t) ;; on purpose, we look further than LIMIT
  4588. ;; We do have a matching #+end line
  4589. (setq beg-of-endline (match-beginning 0)
  4590. end-of-endline (match-end 0)
  4591. nl-before-endline (1- (match-beginning 0)))
  4592. (setq block-end (match-beginning 0)) ; includes the final newline.
  4593. (when quoting
  4594. (org-remove-flyspell-overlays-in bol-after-beginline nl-before-endline)
  4595. (remove-text-properties beg end-of-endline
  4596. '(display t invisible t intangible t)))
  4597. (add-text-properties
  4598. beg end-of-endline '(font-lock-fontified t font-lock-multiline t))
  4599. (org-remove-flyspell-overlays-in beg bol-after-beginline)
  4600. (org-remove-flyspell-overlays-in nl-before-endline end-of-endline)
  4601. (cond
  4602. ((and lang (not (string= lang "")) org-src-fontify-natively)
  4603. (org-src-font-lock-fontify-block lang block-start block-end)
  4604. (add-text-properties bol-after-beginline block-end '(src-block t)))
  4605. (quoting
  4606. (add-text-properties
  4607. bol-after-beginline beg-of-endline
  4608. (list 'face
  4609. (list :inherit
  4610. (let ((face-name
  4611. (intern (format "org-block-%s" lang))))
  4612. (append (and (facep face-name) (list face-name))
  4613. '(org-block)))))))
  4614. ((not org-fontify-quote-and-verse-blocks))
  4615. ((string= block-type "quote")
  4616. (add-face-text-property
  4617. bol-after-beginline beg-of-endline 'org-quote t))
  4618. ((string= block-type "verse")
  4619. (add-face-text-property
  4620. bol-after-beginline beg-of-endline 'org-verse t)))
  4621. ;; Fontify the #+begin and #+end lines of the blocks
  4622. (add-text-properties
  4623. beg (if whole-blockline bol-after-beginline end-of-beginline)
  4624. '(face org-block-begin-line))
  4625. (unless (string-prefix-p "*" (match-string 1))
  4626. (add-text-properties
  4627. beg-of-endline
  4628. (if whole-blockline
  4629. (let ((beg-of-next-line (1+ end-of-endline)))
  4630. (min (point-max) beg-of-next-line))
  4631. (min (point-max) end-of-endline))
  4632. '(face org-block-end-line)))
  4633. t))
  4634. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  4635. (org-remove-flyspell-overlays-in
  4636. (match-beginning 0)
  4637. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  4638. (add-text-properties
  4639. beg (match-end 3)
  4640. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  4641. '(font-lock-fontified t invisible t)
  4642. '(font-lock-fontified t face org-document-info-keyword)))
  4643. (add-text-properties
  4644. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  4645. (if (string-equal dc1 "+title:")
  4646. '(font-lock-fontified t face org-document-title)
  4647. '(font-lock-fontified t face org-document-info))))
  4648. ((string-prefix-p "+caption" dc1)
  4649. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  4650. (remove-text-properties (match-beginning 0) (match-end 0)
  4651. '(display t invisible t intangible t))
  4652. ;; Handle short captions.
  4653. (save-excursion
  4654. (beginning-of-line)
  4655. (looking-at (rx (group (zero-or-more blank)
  4656. "#+caption"
  4657. (optional "[" (zero-or-more any) "]")
  4658. ":")
  4659. (zero-or-more blank))))
  4660. (add-text-properties (line-beginning-position) (match-end 1)
  4661. '(font-lock-fontified t face org-meta-line))
  4662. (add-text-properties (match-end 0) (line-end-position)
  4663. '(font-lock-fontified t face org-block))
  4664. t)
  4665. ((member dc3 '(" " ""))
  4666. ; Just a comment, the plus was not there
  4667. (org-remove-flyspell-overlays-in beg (match-end 0))
  4668. (add-text-properties
  4669. beg (match-end 0)
  4670. '(font-lock-fontified t face font-lock-comment-face)))
  4671. (t ;; just any other in-buffer setting, but not indented
  4672. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4673. (remove-text-properties (match-beginning 0) (match-end 0)
  4674. '(display t invisible t intangible t))
  4675. (add-text-properties beg (match-end 0)
  4676. '(font-lock-fontified t face org-meta-line))
  4677. t))))))
  4678. (defun org-fontify-drawers (limit)
  4679. "Fontify drawers."
  4680. (when (re-search-forward org-drawer-regexp limit t)
  4681. (add-text-properties (1- (match-beginning 1)) (1+ (match-end 1))
  4682. '(font-lock-fontified t face org-drawer))
  4683. (org-remove-flyspell-overlays-in
  4684. (line-beginning-position) (line-beginning-position 2))
  4685. t))
  4686. (defun org-fontify-macros (limit)
  4687. "Fontify macros."
  4688. (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
  4689. (let ((begin (match-beginning 0))
  4690. (opening-end (match-beginning 1)))
  4691. (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
  4692. (match-string 1))
  4693. (let ((end (match-end 1))
  4694. (closing-start (match-beginning 1)))
  4695. (add-text-properties
  4696. begin end
  4697. '(font-lock-multiline t font-lock-fontified t face org-macro))
  4698. (org-remove-flyspell-overlays-in begin end)
  4699. (when org-hide-macro-markers
  4700. (add-text-properties begin opening-end '(invisible t))
  4701. (add-text-properties closing-start end '(invisible t)))
  4702. t)))))
  4703. (defun org-fontify-extend-region (beg end _old-len)
  4704. (let ((begin-re "\\(\\\\\\[\\|\\(#\\+begin_\\|\\\\begin{\\)\\S-+\\)")
  4705. (end-re "\\(\\\\\\]\\|\\(#\\+end_\\|\\\\end{\\)\\S-+\\)")
  4706. (extend (lambda (r1 r2 dir)
  4707. (let ((re (replace-regexp-in-string "\\(begin\\|end\\)" r1
  4708. (replace-regexp-in-string "[][]" r2
  4709. (match-string-no-properties 0)))))
  4710. (re-search-forward (regexp-quote re) nil t dir)))))
  4711. (save-match-data
  4712. (save-excursion
  4713. (goto-char beg)
  4714. (back-to-indentation)
  4715. (cond ((looking-at end-re)
  4716. (cons (or (funcall extend "begin" "[" -1) beg) end))
  4717. ((looking-at begin-re)
  4718. (cons beg (or (funcall extend "end" "]" 1) end)))
  4719. (t (cons beg end)))))))
  4720. (defun org-activate-footnote-links (limit)
  4721. "Add text properties for footnotes."
  4722. (let ((fn (org-footnote-next-reference-or-definition limit)))
  4723. (when fn
  4724. (let* ((beg (nth 1 fn))
  4725. (end (nth 2 fn))
  4726. (label (car fn))
  4727. (referencep (/= (line-beginning-position) beg)))
  4728. (when (and referencep (nth 3 fn))
  4729. (save-excursion
  4730. (goto-char beg)
  4731. (search-forward (or label "fn:"))
  4732. (org-remove-flyspell-overlays-in beg (match-end 0))))
  4733. (add-text-properties beg end
  4734. (list 'mouse-face 'highlight
  4735. 'keymap org-mouse-map
  4736. 'help-echo
  4737. (if referencep "Footnote reference"
  4738. "Footnote definition")
  4739. 'font-lock-fontified t
  4740. 'font-lock-multiline t
  4741. 'face 'org-footnote))))))
  4742. (defun org-activate-dates (limit)
  4743. "Add text properties for dates."
  4744. (when (and (re-search-forward org-tsr-regexp-both limit t)
  4745. (not (equal (char-before (match-beginning 0)) 91)))
  4746. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4747. (add-text-properties (match-beginning 0) (match-end 0)
  4748. (list 'mouse-face 'highlight
  4749. 'keymap org-mouse-map))
  4750. (org-rear-nonsticky-at (match-end 0))
  4751. (when org-display-custom-times
  4752. ;; If it's a date range, activate custom time for second date.
  4753. (when (match-end 3)
  4754. (org-display-custom-time (match-beginning 3) (match-end 3)))
  4755. (org-display-custom-time (match-beginning 1) (match-end 1)))
  4756. t))
  4757. (defun org-activate-target-links (limit)
  4758. "Add text properties for target matches."
  4759. (when org-target-link-regexp
  4760. (let ((case-fold-search t))
  4761. ;; `org-target-link-regexp' matches one character before the
  4762. ;; actual target.
  4763. (unless (bolp) (forward-char -1))
  4764. (when (re-search-forward org-target-link-regexp limit t)
  4765. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4766. (add-text-properties (match-beginning 1) (match-end 1)
  4767. (list 'mouse-face 'highlight
  4768. 'keymap org-mouse-map
  4769. 'help-echo "Radio target link"
  4770. 'org-linked-text t))
  4771. (org-rear-nonsticky-at (match-end 1))
  4772. t))))
  4773. (defvar org-latex-and-related-regexp nil
  4774. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  4775. (defun org-compute-latex-and-related-regexp ()
  4776. "Compute regular expression for LaTeX, entities and sub/superscript.
  4777. Result depends on variable `org-highlight-latex-and-related'."
  4778. (let ((re-sub
  4779. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  4780. ((eq org-use-sub-superscripts '{})
  4781. (list org-match-substring-with-braces-regexp))
  4782. (org-use-sub-superscripts (list org-match-substring-regexp))))
  4783. (re-latex
  4784. (when (or (memq 'latex org-highlight-latex-and-related)
  4785. (memq 'native org-highlight-latex-and-related))
  4786. (let ((matchers (plist-get org-format-latex-options :matchers)))
  4787. (delq nil
  4788. (mapcar (lambda (x)
  4789. (and (member (car x) matchers) (nth 1 x)))
  4790. org-latex-regexps)))))
  4791. (re-entities
  4792. (when (memq 'entities org-highlight-latex-and-related)
  4793. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\
  4794. \\($\\|{}\\|[^[:alpha:]]\\)"))))
  4795. (setq-local org-latex-and-related-regexp
  4796. (mapconcat #'identity
  4797. (append re-latex re-entities re-sub)
  4798. "\\|"))))
  4799. (defun org-do-latex-and-related (limit)
  4800. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  4801. Stop at first highlighted object, if any. Return t if some
  4802. highlighting was done, nil otherwise."
  4803. (when (org-string-nw-p org-latex-and-related-regexp)
  4804. (let ((latex-prefix-re (rx (or "$" "\\(" "\\[")))
  4805. (blank-line-re (rx (and "\n" (zero-or-more (or " " "\t")) "\n"))))
  4806. (catch 'found
  4807. (while (and (< (point) limit)
  4808. (re-search-forward org-latex-and-related-regexp nil t))
  4809. (cond
  4810. ((cl-some (lambda (f)
  4811. (memq f '(org-code org-verbatim underline
  4812. org-special-keyword)))
  4813. (save-excursion
  4814. (goto-char (1+ (match-beginning 0)))
  4815. (face-at-point nil t))))
  4816. ;; Try to limit false positives. In this case, ignore
  4817. ;; $$...$$, \(...\), and \[...\] LaTeX constructs if they
  4818. ;; contain an empty line.
  4819. ((save-excursion
  4820. (goto-char (match-beginning 0))
  4821. (and (looking-at-p latex-prefix-re)
  4822. (save-match-data
  4823. (re-search-forward blank-line-re (1- (match-end 0)) t)))))
  4824. (t
  4825. (let* ((offset (if (memq (char-after (1+ (match-beginning 0)))
  4826. '(?_ ?^))
  4827. 1
  4828. 0))
  4829. (start (+ offset (match-beginning 0)))
  4830. (end (match-end 0)))
  4831. (if (memq 'native org-highlight-latex-and-related)
  4832. (org-src-font-lock-fontify-block "latex" start end)
  4833. (font-lock-prepend-text-property start end
  4834. 'face 'org-latex-and-related))
  4835. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  4836. '(font-lock-multiline t))
  4837. (throw 'found t)))))
  4838. nil))))
  4839. (defun org-restart-font-lock ()
  4840. "Restart `font-lock-mode', to force refontification."
  4841. (when (and (boundp 'font-lock-mode) font-lock-mode)
  4842. (font-lock-mode -1)
  4843. (font-lock-mode 1)))
  4844. (defun org-activate-tags (limit)
  4845. (when (re-search-forward org-tag-line-re limit t)
  4846. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4847. (add-text-properties (match-beginning 1) (match-end 1)
  4848. (list 'mouse-face 'highlight
  4849. 'keymap org-mouse-map))
  4850. (org-rear-nonsticky-at (match-end 1))
  4851. t))
  4852. (defun org-outline-level ()
  4853. "Compute the outline level of the heading at point.
  4854. If this is called at a normal headline, the level is the number
  4855. of stars. Use `org-reduced-level' to remove the effect of
  4856. `org-odd-levels'. Unlike to `org-current-level', this function
  4857. takes into consideration inlinetasks."
  4858. (org-with-wide-buffer
  4859. (end-of-line)
  4860. (if (re-search-backward org-outline-regexp-bol nil t)
  4861. (1- (- (match-end 0) (match-beginning 0)))
  4862. 0)))
  4863. (defvar org-font-lock-keywords nil)
  4864. (defsubst org-re-property (property &optional literal allow-null value)
  4865. "Return a regexp matching a PROPERTY line.
  4866. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  4867. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  4868. non-nil, match properties even without a value.
  4869. Match group 3 is set to the value when it exists. If there is no
  4870. value and ALLOW-NULL is non-nil, it is set to the empty string.
  4871. With optional argument VALUE, match only property lines with
  4872. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  4873. unless LITERAL is non-nil."
  4874. (concat
  4875. "^\\(?4:[ \t]*\\)"
  4876. (format "\\(?1::\\(?2:%s\\):\\)"
  4877. (if literal property (regexp-quote property)))
  4878. (cond (value
  4879. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  4880. (if literal value (regexp-quote value))))
  4881. (allow-null
  4882. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  4883. (t
  4884. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  4885. (defconst org-property-re
  4886. (org-re-property "\\S-+" 'literal t)
  4887. "Regular expression matching a property line.
  4888. There are four matching groups:
  4889. 1: :PROPKEY: including the leading and trailing colon,
  4890. 2: PROPKEY without the leading and trailing colon,
  4891. 3: PROPVAL without leading or trailing spaces,
  4892. 4: the indentation of the current line,
  4893. 5: trailing whitespace.")
  4894. (defvar org-font-lock-hook nil
  4895. "Functions to be called for special font lock stuff.")
  4896. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  4897. (defvar org-font-lock-set-keywords-hook nil
  4898. "Functions that can manipulate `org-font-lock-extra-keywords'.
  4899. This is called after `org-font-lock-extra-keywords' is defined, but before
  4900. it is installed to be used by font lock. This can be useful if something
  4901. needs to be inserted at a specific position in the font-lock sequence.")
  4902. (defun org-font-lock-hook (limit)
  4903. "Run `org-font-lock-hook' within LIMIT."
  4904. (run-hook-with-args 'org-font-lock-hook limit))
  4905. (defun org-set-font-lock-defaults ()
  4906. "Set font lock defaults for the current buffer."
  4907. (let* ((em org-fontify-emphasized-text)
  4908. (lk org-highlight-links)
  4909. (org-font-lock-extra-keywords
  4910. (list
  4911. ;; Call the hook
  4912. '(org-font-lock-hook)
  4913. ;; Headlines
  4914. `(,(if org-fontify-whole-heading-line
  4915. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  4916. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  4917. (1 (org-get-level-face 1))
  4918. (2 (org-get-level-face 2))
  4919. (3 (org-get-level-face 3)))
  4920. ;; Table lines
  4921. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  4922. (1 'org-table t))
  4923. ;; Table internals
  4924. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  4925. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  4926. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  4927. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  4928. ;; Properties
  4929. (list org-property-re
  4930. '(1 'org-special-keyword t)
  4931. '(3 'org-property-value t))
  4932. ;; Drawers
  4933. '(org-fontify-drawers)
  4934. ;; Link related fontification.
  4935. '(org-activate-links)
  4936. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  4937. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  4938. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  4939. (when (memq 'footnote lk) '(org-activate-footnote-links))
  4940. ;; Targets.
  4941. (list org-radio-target-regexp '(0 'org-target t))
  4942. (list org-target-regexp '(0 'org-target t))
  4943. ;; Diary sexps.
  4944. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  4945. ;; Macro
  4946. '(org-fontify-macros)
  4947. ;; TODO keyword
  4948. (list (format org-heading-keyword-regexp-format
  4949. org-todo-regexp)
  4950. '(2 (org-get-todo-face 2) t))
  4951. ;; TODO
  4952. (when org-fontify-todo-headline
  4953. (list (format org-heading-keyword-regexp-format
  4954. (concat
  4955. "\\(?:"
  4956. (mapconcat 'regexp-quote org-not-done-keywords "\\|")
  4957. "\\)"))
  4958. '(2 'org-headline-todo t)))
  4959. ;; DONE
  4960. (when org-fontify-done-headline
  4961. (list (format org-heading-keyword-regexp-format
  4962. (concat
  4963. "\\(?:"
  4964. (mapconcat 'regexp-quote org-done-keywords "\\|")
  4965. "\\)"))
  4966. '(2 'org-headline-done t)))
  4967. ;; Priorities
  4968. '(org-font-lock-add-priority-faces)
  4969. ;; Tags
  4970. '(org-font-lock-add-tag-faces)
  4971. ;; Tags groups
  4972. (when (and org-group-tags org-tag-groups-alist)
  4973. (list (concat org-outline-regexp-bol ".+\\(:"
  4974. (regexp-opt (mapcar 'car org-tag-groups-alist))
  4975. ":\\).*$")
  4976. '(1 'org-tag-group prepend)))
  4977. ;; Special keywords
  4978. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  4979. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  4980. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  4981. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  4982. ;; Emphasis
  4983. (when em '(org-do-emphasis-faces))
  4984. ;; Checkboxes
  4985. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  4986. 1 'org-checkbox prepend)
  4987. (when (cdr (assq 'checkbox org-list-automatic-rules))
  4988. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  4989. (0 (org-get-checkbox-statistics-face) t)))
  4990. ;; Description list items
  4991. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  4992. 1 'org-list-dt prepend)
  4993. ;; ARCHIVEd headings
  4994. (list (concat
  4995. org-outline-regexp-bol
  4996. "\\(.*:" org-archive-tag ":.*\\)")
  4997. '(1 'org-archived prepend))
  4998. ;; Specials
  4999. '(org-do-latex-and-related)
  5000. '(org-fontify-entities)
  5001. '(org-raise-scripts)
  5002. ;; Code
  5003. '(org-activate-code (1 'org-code t))
  5004. ;; COMMENT
  5005. (list (format
  5006. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5007. org-todo-regexp
  5008. org-comment-string)
  5009. '(9 'org-special-keyword t))
  5010. ;; Blocks and meta lines
  5011. '(org-fontify-meta-lines-and-blocks))))
  5012. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5013. (run-hooks 'org-font-lock-set-keywords-hook)
  5014. ;; Now set the full font-lock-keywords
  5015. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5016. (setq-local font-lock-defaults
  5017. '(org-font-lock-keywords t nil nil backward-paragraph))
  5018. (setq-local font-lock-extend-after-change-region-function
  5019. #'org-fontify-extend-region)
  5020. (kill-local-variable 'font-lock-keywords)
  5021. nil))
  5022. (defun org-toggle-pretty-entities ()
  5023. "Toggle the composition display of entities as UTF8 characters."
  5024. (interactive)
  5025. (setq-local org-pretty-entities (not org-pretty-entities))
  5026. (org-restart-font-lock)
  5027. (if org-pretty-entities
  5028. (message "Entities are now displayed as UTF8 characters")
  5029. (save-restriction
  5030. (widen)
  5031. (decompose-region (point-min) (point-max))
  5032. (message "Entities are now displayed as plain text"))))
  5033. (defvar-local org-custom-properties-overlays nil
  5034. "List of overlays used for custom properties.")
  5035. (defun org-toggle-custom-properties-visibility ()
  5036. "Display or hide properties in `org-custom-properties'."
  5037. (interactive)
  5038. (if org-custom-properties-overlays
  5039. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5040. (setq org-custom-properties-overlays nil))
  5041. (when org-custom-properties
  5042. (org-with-wide-buffer
  5043. (goto-char (point-min))
  5044. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5045. (while (re-search-forward regexp nil t)
  5046. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5047. (when (and end (< (point) end))
  5048. ;; Hide first custom property in current drawer.
  5049. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5050. (overlay-put o 'invisible t)
  5051. (overlay-put o 'org-custom-property t)
  5052. (push o org-custom-properties-overlays))
  5053. ;; Hide additional custom properties in the same drawer.
  5054. (while (re-search-forward regexp end t)
  5055. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5056. (overlay-put o 'invisible t)
  5057. (overlay-put o 'org-custom-property t)
  5058. (push o org-custom-properties-overlays)))))
  5059. ;; Each entry is limited to a single property drawer.
  5060. (outline-next-heading)))))))
  5061. (defun org-fontify-entities (limit)
  5062. "Find an entity to fontify."
  5063. (let (ee)
  5064. (when org-pretty-entities
  5065. (catch 'match
  5066. ;; "\_ "-family is left out on purpose. Only the first one,
  5067. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5068. ;; confusing when adding a second white space character.
  5069. (while (re-search-forward
  5070. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5071. limit t)
  5072. (when (and (not (org-at-comment-p))
  5073. (setq ee (org-entity-get (match-string 1)))
  5074. (= (length (nth 6 ee)) 1))
  5075. (let* ((end (if (equal (match-string 2) "{}")
  5076. (match-end 2)
  5077. (match-end 1))))
  5078. (add-text-properties
  5079. (match-beginning 0) end
  5080. (list 'font-lock-fontified t))
  5081. (compose-region (match-beginning 0) end
  5082. (nth 6 ee) nil)
  5083. (backward-char 1)
  5084. (throw 'match t))))
  5085. nil))))
  5086. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5087. "Fontify string S like in Org mode."
  5088. (with-temp-buffer
  5089. (insert s)
  5090. (let ((org-odd-levels-only odd-levels))
  5091. (org-mode)
  5092. (org-font-lock-ensure)
  5093. (buffer-string))))
  5094. (defun org-get-level-face (n)
  5095. "Get the right face for match N in font-lock matching of headlines."
  5096. (let* ((org-l0 (- (match-end 2) (match-beginning 1) 1))
  5097. (org-l (if org-odd-levels-only (1+ (/ org-l0 2)) org-l0))
  5098. (org-f (if org-cycle-level-faces
  5099. (nth (% (1- org-l) org-n-level-faces) org-level-faces)
  5100. (nth (1- (min org-l org-n-level-faces)) org-level-faces))))
  5101. (cond
  5102. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5103. ((eq n 2) org-f)
  5104. (t (unless org-level-color-stars-only org-f)))))
  5105. (defun org-face-from-face-or-color (context inherit face-or-color)
  5106. "Create a face list that inherits INHERIT, but sets the foreground color.
  5107. When FACE-OR-COLOR is not a string, just return it."
  5108. (if (stringp face-or-color)
  5109. (list :inherit inherit
  5110. (cdr (assoc context org-faces-easy-properties))
  5111. face-or-color)
  5112. face-or-color))
  5113. (defun org-get-todo-face (kwd)
  5114. "Get the right face for a TODO keyword KWD.
  5115. If KWD is a number, get the corresponding match group."
  5116. (when (numberp kwd) (setq kwd (match-string kwd)))
  5117. (or (org-face-from-face-or-color
  5118. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5119. (and (member kwd org-done-keywords) 'org-done)
  5120. 'org-todo))
  5121. (defun org-get-priority-face (priority)
  5122. "Get the right face for PRIORITY.
  5123. PRIORITY is a character."
  5124. (or (org-face-from-face-or-color
  5125. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5126. 'org-priority))
  5127. (defun org-get-tag-face (tag)
  5128. "Get the right face for TAG.
  5129. If TAG is a number, get the corresponding match group."
  5130. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5131. (or (org-face-from-face-or-color
  5132. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5133. 'org-tag)))
  5134. (defvar org-priority-regexp) ; defined later in the file
  5135. (defun org-font-lock-add-priority-faces (limit)
  5136. "Add the special priority faces."
  5137. (while (re-search-forward org-priority-regexp limit t)
  5138. (add-text-properties
  5139. (match-beginning 1) (match-end 1)
  5140. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5141. 'font-lock-fontified t))))
  5142. (defun org-font-lock-add-tag-faces (limit)
  5143. "Add the special tag faces."
  5144. (when (and org-tag-faces org-tags-special-faces-re)
  5145. (while (re-search-forward org-tags-special-faces-re limit t)
  5146. (add-text-properties (match-beginning 1) (match-end 1)
  5147. (list 'face (org-get-tag-face 1)
  5148. 'font-lock-fontified t))
  5149. (backward-char 1))))
  5150. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5151. "Remove fontification and activation overlays from links."
  5152. (font-lock-default-unfontify-region beg end)
  5153. (let* ((buffer-undo-list t)
  5154. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5155. (inhibit-modification-hooks t)
  5156. deactivate-mark buffer-file-name buffer-file-truename)
  5157. (decompose-region beg end)
  5158. (remove-text-properties beg end
  5159. '(mouse-face t keymap t org-linked-text t
  5160. invisible t intangible t
  5161. org-emphasis t))
  5162. (org-remove-font-lock-display-properties beg end)))
  5163. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5164. ((raise 0.3) (height 0.7))
  5165. ((raise -0.5))
  5166. ((raise 0.5)))
  5167. "Display properties for showing superscripts and subscripts.")
  5168. (defun org-remove-font-lock-display-properties (beg end)
  5169. "Remove specific display properties that have been added by font lock.
  5170. The will remove the raise properties that are used to show superscripts
  5171. and subscripts."
  5172. (let (next prop)
  5173. (while (< beg end)
  5174. (setq next (next-single-property-change beg 'display nil end)
  5175. prop (get-text-property beg 'display))
  5176. (when (member prop org-script-display)
  5177. (put-text-property beg next 'display nil))
  5178. (setq beg next))))
  5179. (defun org-raise-scripts (limit)
  5180. "Add raise properties to sub/superscripts."
  5181. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5182. (re-search-forward
  5183. (if (eq org-use-sub-superscripts t)
  5184. org-match-substring-regexp
  5185. org-match-substring-with-braces-regexp)
  5186. limit t))
  5187. (let* ((pos (point)) table-p comment-p
  5188. (mpos (match-beginning 3))
  5189. (emph-p (get-text-property mpos 'org-emphasis))
  5190. (link-p (get-text-property mpos 'mouse-face))
  5191. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5192. (goto-char (point-at-bol))
  5193. (setq table-p (looking-at-p org-table-dataline-regexp)
  5194. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5195. (goto-char pos)
  5196. ;; Handle a_b^c
  5197. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5198. (unless (or comment-p emph-p link-p keyw-p)
  5199. (put-text-property (match-beginning 3) (match-end 0)
  5200. 'display
  5201. (if (equal (char-after (match-beginning 2)) ?^)
  5202. (nth (if table-p 3 1) org-script-display)
  5203. (nth (if table-p 2 0) org-script-display)))
  5204. (add-text-properties (match-beginning 2) (match-end 2)
  5205. (list 'invisible t))
  5206. (when (and (eq (char-after (match-beginning 3)) ?{)
  5207. (eq (char-before (match-end 3)) ?}))
  5208. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5209. (list 'invisible t))
  5210. (add-text-properties (1- (match-end 3)) (match-end 3)
  5211. (list 'invisible t))))
  5212. t)))
  5213. (defun org-remove-empty-overlays-at (pos)
  5214. "Remove outline overlays that do not contain non-white stuff."
  5215. (dolist (o (overlays-at pos))
  5216. (and (eq 'outline (overlay-get o 'invisible))
  5217. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  5218. (overlay-end o))))
  5219. (delete-overlay o))))
  5220. (defun org-show-empty-lines-in-parent ()
  5221. "Move to the parent and re-show empty lines before visible headlines."
  5222. (save-excursion
  5223. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  5224. (org-cycle-show-empty-lines context))))
  5225. (defun org-files-list ()
  5226. "Return `org-agenda-files' list, plus all open Org files.
  5227. This is useful for operations that need to scan all of a user's
  5228. open and agenda-wise Org files."
  5229. (let ((files (mapcar #'expand-file-name (org-agenda-files))))
  5230. (dolist (buf (buffer-list))
  5231. (with-current-buffer buf
  5232. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  5233. (cl-pushnew (expand-file-name (buffer-file-name)) files
  5234. :test #'equal))))
  5235. files))
  5236. (defsubst org-entry-beginning-position ()
  5237. "Return the beginning position of the current entry."
  5238. (save-excursion (org-back-to-heading t) (point)))
  5239. (defsubst org-entry-end-position ()
  5240. "Return the end position of the current entry."
  5241. (save-excursion (outline-next-heading) (point)))
  5242. (defun org-subtree-end-visible-p ()
  5243. "Is the end of the current subtree visible?"
  5244. (pos-visible-in-window-p
  5245. (save-excursion (org-end-of-subtree t) (point))))
  5246. (defun org-first-headline-recenter ()
  5247. "Move cursor to the first headline and recenter the headline."
  5248. (let ((window (get-buffer-window)))
  5249. (when window
  5250. (goto-char (point-min))
  5251. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  5252. (set-window-start window (line-beginning-position))))))
  5253. ;;; Visibility (headlines, blocks, drawers)
  5254. ;;;; Headlines visibility
  5255. (defun org-show-entry ()
  5256. "Show the body directly following this heading.
  5257. Show the heading too, if it is currently invisible."
  5258. (interactive)
  5259. (save-excursion
  5260. (ignore-errors
  5261. (org-back-to-heading t)
  5262. (org-flag-region
  5263. (line-end-position 0)
  5264. (save-excursion
  5265. (if (re-search-forward
  5266. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  5267. (match-beginning 1)
  5268. (point-max)))
  5269. nil
  5270. 'outline))))
  5271. (defun org-show-children (&optional level)
  5272. "Show all direct subheadings of this heading.
  5273. Prefix arg LEVEL is how many levels below the current level
  5274. should be shown. Default is enough to cause the following
  5275. heading to appear."
  5276. (interactive "p")
  5277. (save-excursion
  5278. (org-back-to-heading t)
  5279. (let* ((current-level (funcall outline-level))
  5280. (max-level (org-get-valid-level
  5281. current-level
  5282. (if level (prefix-numeric-value level) 1)))
  5283. (end (save-excursion (org-end-of-subtree t t)))
  5284. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  5285. (past-first-child nil)
  5286. ;; Make sure to skip inlinetasks.
  5287. (re (format regexp-fmt
  5288. current-level
  5289. (cond
  5290. ((not (featurep 'org-inlinetask)) "")
  5291. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  5292. 3))
  5293. (t (1- org-inlinetask-min-level))))))
  5294. ;; Display parent heading.
  5295. (org-flag-heading nil)
  5296. (forward-line)
  5297. ;; Display children. First child may be deeper than expected
  5298. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  5299. ;; MAX-LEVEL accordingly.
  5300. (while (re-search-forward re end t)
  5301. (unless past-first-child
  5302. (setq re (format regexp-fmt
  5303. current-level
  5304. (max (funcall outline-level) max-level)))
  5305. (setq past-first-child t))
  5306. (org-flag-heading nil)))))
  5307. (defun org-show-subtree ()
  5308. "Show everything after this heading at deeper levels."
  5309. (interactive)
  5310. (org-flag-region
  5311. (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
  5312. ;;;; Blocks and drawers visibility
  5313. (defun org--hide-wrapper-toggle (element category force no-error)
  5314. "Toggle visibility for ELEMENT.
  5315. ELEMENT is a block or drawer type parsed element. CATEGORY is
  5316. either `block' or `drawer'. When FORCE is `off', show the block
  5317. or drawer. If it is non-nil, hide it unconditionally. Throw an
  5318. error when not at a block or drawer, unless NO-ERROR is non-nil.
  5319. Return a non-nil value when toggling is successful."
  5320. (cond
  5321. ((memq (org-element-type element)
  5322. (pcase category
  5323. (`drawer '(drawer property-drawer))
  5324. (`block '(center-block
  5325. comment-block dynamic-block example-block export-block
  5326. quote-block special-block src-block verse-block))
  5327. (_ (error "Unknown category: %S" category))))
  5328. (let* ((post (org-element-property :post-affiliated element))
  5329. (start (save-excursion
  5330. (goto-char post)
  5331. (line-end-position)))
  5332. (end (save-excursion
  5333. (goto-char (org-element-property :end element))
  5334. (skip-chars-backward " \t\n")
  5335. (line-end-position))))
  5336. ;; Do nothing when not before or at the block opening line or at
  5337. ;; the block closing line.
  5338. (unless (let ((eol (line-end-position)))
  5339. (and (> eol start) (/= eol end)))
  5340. (let* ((spec (if (eq category 'drawer)
  5341. 'org-hide-drawer
  5342. 'org-hide-block))
  5343. (flag
  5344. (cond ((eq force 'off) nil)
  5345. (force t)
  5346. ((eq (get-char-property start 'invisible) spec) nil)
  5347. (t t))))
  5348. (org-flag-region start end flag spec))
  5349. ;; When the block is hidden away, make sure point is left in
  5350. ;; a visible part of the buffer.
  5351. (when (invisible-p (max (1- (point)) (point-min)))
  5352. (goto-char post))
  5353. ;; Signal success.
  5354. t)))
  5355. (no-error nil)
  5356. (t
  5357. (user-error (if (eq category 'drawer)
  5358. "Not at a drawer"
  5359. "Not at a block")))))
  5360. (defun org-hide-block-toggle (&optional force no-error element)
  5361. "Toggle the visibility of the current block.
  5362. When optional argument FORCE is `off', make block visible. If it
  5363. is non-nil, hide it unconditionally. Throw an error when not at
  5364. a block, unless NO-ERROR is non-nil. When optional argument
  5365. ELEMENT is provided, consider it instead of the current block.
  5366. Return a non-nil value when toggling is successful."
  5367. (interactive)
  5368. (org--hide-wrapper-toggle
  5369. (or element (org-element-at-point)) 'block force no-error))
  5370. (defun org-hide-drawer-toggle (&optional force no-error element)
  5371. "Toggle the visibility of the current drawer.
  5372. When optional argument FORCE is `off', make drawer visible. If
  5373. it is non-nil, hide it unconditionally. Throw an error when not
  5374. at a drawer, unless NO-ERROR is non-nil. When optional argument
  5375. ELEMENT is provided, consider it instead of the current drawer.
  5376. Return a non-nil value when toggling is successful."
  5377. (interactive)
  5378. (org--hide-wrapper-toggle
  5379. (or element (org-element-at-point)) 'drawer force no-error))
  5380. (defun org-hide-block-all ()
  5381. "Fold all blocks in the current buffer."
  5382. (interactive)
  5383. (org-show-all '(blocks))
  5384. (org-block-map 'org-hide-block-toggle))
  5385. (defun org-cycle-hide-drawers (state &optional exceptions)
  5386. "Re-hide all drawers after a visibility state change.
  5387. STATE should be one of the symbols listed in the docstring of
  5388. `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
  5389. a list of strings specifying which drawers should not be hidden."
  5390. (when (and (derived-mode-p 'org-mode)
  5391. (not (memq state '(overview folded contents))))
  5392. (save-excursion
  5393. (let* ((globalp (eq state 'all))
  5394. (beg (if globalp (point-min) (point)))
  5395. (end (if globalp (point-max)
  5396. (if (eq state 'children)
  5397. (save-excursion (outline-next-heading) (point))
  5398. (org-end-of-subtree t)))))
  5399. (goto-char beg)
  5400. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  5401. (unless (member-ignore-case (match-string 1) exceptions)
  5402. (let ((drawer (org-element-at-point)))
  5403. (when (memq (org-element-type drawer) '(drawer property-drawer))
  5404. (org-hide-drawer-toggle t nil drawer)
  5405. ;; Make sure to skip drawer entirely or we might flag
  5406. ;; it another time when matching its ending line with
  5407. ;; `org-drawer-regexp'.
  5408. (goto-char (org-element-property :end drawer))))))))))
  5409. ;;;; Visibility cycling
  5410. (defvar-local org-cycle-global-status nil)
  5411. (put 'org-cycle-global-status 'org-state t)
  5412. (defvar-local org-cycle-subtree-status nil)
  5413. (put 'org-cycle-subtree-status 'org-state t)
  5414. (defun org-show-all (&optional types)
  5415. "Show all contents in the visible part of the buffer.
  5416. By default, the function expands headings, blocks and drawers.
  5417. When optional argument TYPE is a list of symbols among `blocks',
  5418. `drawers' and `headings', to only expand one specific type."
  5419. (interactive)
  5420. (dolist (type (or types '(blocks drawers headings)))
  5421. (org-flag-region (point-min) (point-max) nil
  5422. (pcase type
  5423. (`blocks 'org-hide-block)
  5424. (`drawers 'org-hide-drawer)
  5425. (`headings 'outline)
  5426. (_ (error "Invalid type: %S" type))))))
  5427. ;;;###autoload
  5428. (defun org-cycle (&optional arg)
  5429. "TAB-action and visibility cycling for Org mode.
  5430. This is the command invoked in Org mode by the `TAB' key. Its main
  5431. purpose is outline visibility cycling, but it also invokes other actions
  5432. in special contexts.
  5433. When this function is called with a `\\[universal-argument]' prefix, rotate \
  5434. the entire
  5435. buffer through 3 states (global cycling)
  5436. 1. OVERVIEW: Show only top-level headlines.
  5437. 2. CONTENTS: Show all headlines of all levels, but no body text.
  5438. 3. SHOW ALL: Show everything.
  5439. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  5440. switch to the startup visibility,
  5441. determined by the variable `org-startup-folded', and by any VISIBILITY
  5442. properties in the buffer.
  5443. With a `\\[universal-argument] \\[universal-argument] \
  5444. \\[universal-argument]' prefix argument, show the entire buffer, including
  5445. any drawers.
  5446. When inside a table, re-align the table and move to the next field.
  5447. When point is at the beginning of a headline, rotate the subtree started
  5448. by this line through 3 different states (local cycling)
  5449. 1. FOLDED: Only the main headline is shown.
  5450. 2. CHILDREN: The main headline and the direct children are shown.
  5451. From this state, you can move to one of the children
  5452. and zoom in further.
  5453. 3. SUBTREE: Show the entire subtree, including body text.
  5454. If there is no subtree, switch directly from CHILDREN to FOLDED.
  5455. When point is at the beginning of an empty headline and the variable
  5456. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  5457. of the headline by demoting and promoting it to likely levels. This
  5458. speeds up creation document structure by pressing `TAB' once or several
  5459. times right after creating a new headline.
  5460. When there is a numeric prefix, go up to a heading with level ARG, do
  5461. a `show-subtree' and return to the previous cursor position. If ARG
  5462. is negative, go up that many levels.
  5463. When point is not at the beginning of a headline, execute the global
  5464. binding for `TAB', which is re-indenting the line. See the option
  5465. `org-cycle-emulate-tab' for details.
  5466. As a special case, if point is at the very beginning of the buffer, if
  5467. there is no headline there, and if the variable `org-cycle-global-at-bob'
  5468. is non-nil, this function acts as if called with prefix argument \
  5469. \(`\\[universal-argument] TAB',
  5470. same as `S-TAB') also when called without prefix argument."
  5471. (interactive "P")
  5472. (org-load-modules-maybe)
  5473. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  5474. (and org-cycle-level-after-item/entry-creation
  5475. (or (org-cycle-level)
  5476. (org-cycle-item-indentation))))
  5477. (let* ((limit-level
  5478. (or org-cycle-max-level
  5479. (and (boundp 'org-inlinetask-min-level)
  5480. org-inlinetask-min-level
  5481. (1- org-inlinetask-min-level))))
  5482. (nstars
  5483. (and limit-level
  5484. (if org-odd-levels-only
  5485. (1- (* 2 limit-level))
  5486. limit-level)))
  5487. (org-outline-regexp
  5488. (format "\\*%s " (if nstars (format "\\{1,%d\\}" nstars) "+"))))
  5489. (cond
  5490. ((equal arg '(16))
  5491. (setq last-command 'dummy)
  5492. (org-set-startup-visibility)
  5493. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  5494. ((equal arg '(64))
  5495. (org-show-all)
  5496. (org-unlogged-message "Entire buffer visible, including drawers"))
  5497. ((equal arg '(4)) (org-cycle-internal-global))
  5498. ;; Show-subtree, ARG levels up from here.
  5499. ((integerp arg)
  5500. (save-excursion
  5501. (org-back-to-heading)
  5502. (outline-up-heading (if (< arg 0) (- arg)
  5503. (- (funcall outline-level) arg)))
  5504. (org-show-subtree)))
  5505. ;; Global cycling at BOB: delegate to `org-cycle-internal-global'.
  5506. ((and org-cycle-global-at-bob
  5507. (bobp)
  5508. (not (looking-at org-outline-regexp)))
  5509. (let ((org-cycle-hook
  5510. (remq 'org-optimize-window-after-visibility-change
  5511. org-cycle-hook)))
  5512. (org-cycle-internal-global)))
  5513. ;; Try CDLaTeX TAB completion.
  5514. ((org-try-cdlatex-tab))
  5515. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  5516. ((and (featurep 'org-inlinetask)
  5517. (org-inlinetask-at-task-p)
  5518. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5519. (org-inlinetask-toggle-visibility))
  5520. (t
  5521. (let ((pos (point))
  5522. (element (org-element-at-point)))
  5523. (cond
  5524. ;; Try toggling visibility for block at point.
  5525. ((org-hide-block-toggle nil t element))
  5526. ;; Try toggling visibility for block at point.
  5527. ((org-hide-drawer-toggle nil t element))
  5528. ;; Table: enter it or move to the next field.
  5529. ((and (org-match-line "[ \t]*[|+]")
  5530. (org-element-lineage element '(table) t))
  5531. (if (and (eq 'table (org-element-type element))
  5532. (eq 'table.el (org-element-property :type element)))
  5533. (message (substitute-command-keys "\\<org-mode-map>\
  5534. Use `\\[org-edit-special]' to edit table.el tables"))
  5535. (org-table-justify-field-maybe)
  5536. (call-interactively #'org-table-next-field)))
  5537. ((run-hook-with-args-until-success
  5538. 'org-tab-after-check-for-table-hook))
  5539. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  5540. ((and (or (and org-cycle-include-plain-lists
  5541. (let ((item (org-element-lineage element
  5542. '(item plain-list)
  5543. t)))
  5544. (and item
  5545. (= (line-beginning-position)
  5546. (org-element-property :post-affiliated
  5547. item)))))
  5548. (save-excursion (move-beginning-of-line 1)
  5549. (looking-at org-outline-regexp)))
  5550. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5551. (org-cycle-internal-local))
  5552. ;; From there: TAB emulation and template completion.
  5553. (buffer-read-only (org-back-to-heading))
  5554. ((run-hook-with-args-until-success
  5555. 'org-tab-after-check-for-cycling-hook))
  5556. ((run-hook-with-args-until-success
  5557. 'org-tab-before-tab-emulation-hook))
  5558. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  5559. (or (not (bolp))
  5560. (not (looking-at org-outline-regexp))))
  5561. (call-interactively (global-key-binding (kbd "TAB"))))
  5562. ((or (eq org-cycle-emulate-tab t)
  5563. (and (memq org-cycle-emulate-tab '(white whitestart))
  5564. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  5565. (or (and (eq org-cycle-emulate-tab 'white)
  5566. (= (match-end 0) (point-at-eol)))
  5567. (and (eq org-cycle-emulate-tab 'whitestart)
  5568. (>= (match-end 0) pos)))))
  5569. (call-interactively (global-key-binding (kbd "TAB"))))
  5570. (t
  5571. (save-excursion
  5572. (org-back-to-heading)
  5573. (org-cycle))))))))))
  5574. (defun org-cycle-internal-global ()
  5575. "Do the global cycling action."
  5576. ;; Hack to avoid display of messages for .org attachments in Gnus
  5577. (let ((ga (string-match "\\*fontification" (buffer-name))))
  5578. (cond
  5579. ((and (eq last-command this-command)
  5580. (eq org-cycle-global-status 'overview))
  5581. ;; We just created the overview - now do table of contents
  5582. ;; This can be slow in very large buffers, so indicate action
  5583. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  5584. (unless ga (org-unlogged-message "CONTENTS..."))
  5585. (org-content)
  5586. (unless ga (org-unlogged-message "CONTENTS...done"))
  5587. (setq org-cycle-global-status 'contents)
  5588. (run-hook-with-args 'org-cycle-hook 'contents))
  5589. ((and (eq last-command this-command)
  5590. (eq org-cycle-global-status 'contents))
  5591. ;; We just showed the table of contents - now show everything
  5592. (run-hook-with-args 'org-pre-cycle-hook 'all)
  5593. (org-show-all '(headings blocks))
  5594. (unless ga (org-unlogged-message "SHOW ALL"))
  5595. (setq org-cycle-global-status 'all)
  5596. (run-hook-with-args 'org-cycle-hook 'all))
  5597. (t
  5598. ;; Default action: go to overview
  5599. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  5600. (org-overview)
  5601. (unless ga (org-unlogged-message "OVERVIEW"))
  5602. (setq org-cycle-global-status 'overview)
  5603. (run-hook-with-args 'org-cycle-hook 'overview)))))
  5604. (defvar org-called-with-limited-levels nil
  5605. "Non-nil when `org-with-limited-levels' is currently active.")
  5606. (defun org-cycle-internal-local ()
  5607. "Do the local cycling action."
  5608. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  5609. ;; First, determine end of headline (EOH), end of subtree or item
  5610. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  5611. (save-excursion
  5612. (if (org-at-item-p)
  5613. (progn
  5614. (beginning-of-line)
  5615. (setq struct (org-list-struct))
  5616. (setq eoh (point-at-eol))
  5617. (setq eos (org-list-get-item-end-before-blank (point) struct))
  5618. (setq has-children (org-list-has-child-p (point) struct)))
  5619. (org-back-to-heading)
  5620. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  5621. (setq eos (save-excursion (org-end-of-subtree t t)
  5622. (when (bolp) (backward-char)) (point)))
  5623. (setq has-children
  5624. (or
  5625. (save-excursion
  5626. (let ((level (funcall outline-level)))
  5627. (outline-next-heading)
  5628. (and (org-at-heading-p t)
  5629. (> (funcall outline-level) level))))
  5630. (and (eq org-cycle-include-plain-lists 'integrate)
  5631. (save-excursion
  5632. (org-list-search-forward (org-item-beginning-re) eos t))))))
  5633. ;; Determine end invisible part of buffer (EOL)
  5634. (beginning-of-line 2)
  5635. (while (and (not (eobp)) ;This is like `next-line'.
  5636. (get-char-property (1- (point)) 'invisible))
  5637. (goto-char (next-single-char-property-change (point) 'invisible))
  5638. (and (eolp) (beginning-of-line 2)))
  5639. (setq eol (point)))
  5640. ;; Find out what to do next and set `this-command'
  5641. (cond
  5642. ((= eos eoh)
  5643. ;; Nothing is hidden behind this heading
  5644. (unless (org-before-first-heading-p)
  5645. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  5646. (org-unlogged-message "EMPTY ENTRY")
  5647. (setq org-cycle-subtree-status nil)
  5648. (save-excursion
  5649. (goto-char eos)
  5650. (outline-next-heading)
  5651. (when (org-invisible-p) (org-flag-heading nil))))
  5652. ((and (or (>= eol eos)
  5653. (not (string-match "\\S-" (buffer-substring eol eos))))
  5654. (or has-children
  5655. (not (setq children-skipped
  5656. org-cycle-skip-children-state-if-no-children))))
  5657. ;; Entire subtree is hidden in one line: children view
  5658. (unless (org-before-first-heading-p)
  5659. (run-hook-with-args 'org-pre-cycle-hook 'children))
  5660. (if (org-at-item-p)
  5661. (org-list-set-item-visibility (point-at-bol) struct 'children)
  5662. (org-show-entry)
  5663. (org-with-limited-levels (org-show-children))
  5664. (org-show-set-visibility 'canonical)
  5665. ;; Fold every list in subtree to top-level items.
  5666. (when (eq org-cycle-include-plain-lists 'integrate)
  5667. (save-excursion
  5668. (org-back-to-heading)
  5669. (while (org-list-search-forward (org-item-beginning-re) eos t)
  5670. (beginning-of-line 1)
  5671. (let* ((struct (org-list-struct))
  5672. (prevs (org-list-prevs-alist struct))
  5673. (end (org-list-get-bottom-point struct)))
  5674. (dolist (e (org-list-get-all-items (point) struct prevs))
  5675. (org-list-set-item-visibility e struct 'folded))
  5676. (goto-char (if (< end eos) end eos)))))))
  5677. (org-unlogged-message "CHILDREN")
  5678. (save-excursion
  5679. (goto-char eos)
  5680. (outline-next-heading)
  5681. (when (org-invisible-p) (org-flag-heading nil)))
  5682. (setq org-cycle-subtree-status 'children)
  5683. (unless (org-before-first-heading-p)
  5684. (run-hook-with-args 'org-cycle-hook 'children)))
  5685. ((or children-skipped
  5686. (and (eq last-command this-command)
  5687. (eq org-cycle-subtree-status 'children)))
  5688. ;; We just showed the children, or no children are there,
  5689. ;; now show everything.
  5690. (unless (org-before-first-heading-p)
  5691. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  5692. (org-flag-region eoh eos nil 'outline)
  5693. (org-unlogged-message
  5694. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  5695. (setq org-cycle-subtree-status 'subtree)
  5696. (unless (org-before-first-heading-p)
  5697. (run-hook-with-args 'org-cycle-hook 'subtree)))
  5698. (t
  5699. ;; Default action: hide the subtree.
  5700. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  5701. (org-flag-region eoh eos t 'outline)
  5702. (org-unlogged-message "FOLDED")
  5703. (setq org-cycle-subtree-status 'folded)
  5704. (unless (org-before-first-heading-p)
  5705. (run-hook-with-args 'org-cycle-hook 'folded))))))
  5706. ;;;###autoload
  5707. (defun org-global-cycle (&optional arg)
  5708. "Cycle the global visibility. For details see `org-cycle'.
  5709. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  5710. With a numeric prefix, show all headlines up to that level."
  5711. (interactive "P")
  5712. (let ((org-cycle-include-plain-lists
  5713. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  5714. (cond
  5715. ((integerp arg)
  5716. (org-show-all '(headings blocks))
  5717. (outline-hide-sublevels arg)
  5718. (setq org-cycle-global-status 'contents))
  5719. ((equal arg '(4))
  5720. (org-set-startup-visibility)
  5721. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  5722. (t
  5723. (org-cycle '(4))))))
  5724. (defun org-set-startup-visibility ()
  5725. "Set the visibility required by startup options and properties."
  5726. (cond
  5727. ((eq org-startup-folded t)
  5728. (org-overview))
  5729. ((eq org-startup-folded 'content)
  5730. (org-content))
  5731. ((or (eq org-startup-folded 'showeverything)
  5732. (eq org-startup-folded nil))
  5733. (org-show-all)))
  5734. (unless (eq org-startup-folded 'showeverything)
  5735. (when org-hide-block-startup (org-hide-block-all))
  5736. (org-set-visibility-according-to-property)
  5737. (org-cycle-hide-archived-subtrees 'all)
  5738. (org-cycle-hide-drawers 'all)
  5739. (org-cycle-show-empty-lines t)))
  5740. (defun org-set-visibility-according-to-property ()
  5741. "Switch subtree visibility according to VISIBILITY property."
  5742. (interactive)
  5743. (let ((regexp (org-re-property "VISIBILITY")))
  5744. (org-with-point-at 1
  5745. (while (re-search-forward regexp nil t)
  5746. (let ((state (match-string 3)))
  5747. (if (not (org-at-property-p)) (outline-next-heading)
  5748. (save-excursion
  5749. (org-back-to-heading t)
  5750. (org-flag-subtree t)
  5751. (org-reveal)
  5752. (pcase state
  5753. ("folded"
  5754. (org-flag-subtree t))
  5755. ("children"
  5756. (org-show-hidden-entry)
  5757. (org-show-children))
  5758. ("content"
  5759. (save-excursion
  5760. (save-restriction
  5761. (org-narrow-to-subtree)
  5762. (org-content))))
  5763. ((or "all" "showall")
  5764. (outline-show-subtree))
  5765. (_ nil)))
  5766. (org-end-of-subtree)))))))
  5767. (defun org-overview ()
  5768. "Switch to overview mode, showing only top-level headlines.
  5769. This shows all headlines with a level equal or greater than the level
  5770. of the first headline in the buffer. This is important, because if the
  5771. first headline is not level one, then (hide-sublevels 1) gives confusing
  5772. results."
  5773. (interactive)
  5774. (save-excursion
  5775. (let ((level
  5776. (save-excursion
  5777. (goto-char (point-min))
  5778. (when (re-search-forward org-outline-regexp-bol nil t)
  5779. (goto-char (match-beginning 0))
  5780. (funcall outline-level)))))
  5781. (and level (outline-hide-sublevels level)))))
  5782. (defun org-content (&optional arg)
  5783. "Show all headlines in the buffer, like a table of contents.
  5784. With numerical argument N, show content up to level N."
  5785. (interactive "P")
  5786. (org-overview)
  5787. (save-excursion
  5788. ;; Visit all headings and show their offspring
  5789. (and (integerp arg) (org-overview))
  5790. (goto-char (point-max))
  5791. (catch 'exit
  5792. (while (and (progn (condition-case nil
  5793. (outline-previous-visible-heading 1)
  5794. (error (goto-char (point-min))))
  5795. t)
  5796. (looking-at org-outline-regexp))
  5797. (if (integerp arg)
  5798. (org-show-children (1- arg))
  5799. (outline-show-branches))
  5800. (when (bobp) (throw 'exit nil))))))
  5801. (defun org-optimize-window-after-visibility-change (state)
  5802. "Adjust the window after a change in outline visibility.
  5803. This function is the default value of the hook `org-cycle-hook'."
  5804. (when (get-buffer-window (current-buffer))
  5805. (cond
  5806. ((eq state 'content) nil)
  5807. ((eq state 'all) nil)
  5808. ((eq state 'folded) nil)
  5809. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  5810. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  5811. (defun org-clean-visibility-after-subtree-move ()
  5812. "Fix visibility issues after moving a subtree."
  5813. ;; First, find a reasonable region to look at:
  5814. ;; Start two siblings above, end three below
  5815. (let* ((beg (save-excursion
  5816. (and (org-get-last-sibling)
  5817. (org-get-last-sibling))
  5818. (point)))
  5819. (end (save-excursion
  5820. (and (org-get-next-sibling)
  5821. (org-get-next-sibling)
  5822. (org-get-next-sibling))
  5823. (if (org-at-heading-p)
  5824. (point-at-eol)
  5825. (point))))
  5826. (level (looking-at "\\*+"))
  5827. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  5828. (save-excursion
  5829. (save-restriction
  5830. (narrow-to-region beg end)
  5831. (when re
  5832. ;; Properly fold already folded siblings
  5833. (goto-char (point-min))
  5834. (while (re-search-forward re nil t)
  5835. (when (and (not (org-invisible-p))
  5836. (org-invisible-p (line-end-position)))
  5837. (outline-hide-entry))))
  5838. (org-cycle-hide-drawers 'all)
  5839. (org-cycle-show-empty-lines 'overview)))))
  5840. (defun org-cycle-show-empty-lines (state)
  5841. "Show empty lines above all visible headlines.
  5842. The region to be covered depends on STATE when called through
  5843. `org-cycle-hook'. Lisp program can use t for STATE to get the
  5844. entire buffer covered. Note that an empty line is only shown if there
  5845. are at least `org-cycle-separator-lines' empty lines before the headline."
  5846. (when (/= org-cycle-separator-lines 0)
  5847. (save-excursion
  5848. (let* ((n (abs org-cycle-separator-lines))
  5849. (re (cond
  5850. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  5851. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  5852. (t (let ((ns (number-to-string (- n 2))))
  5853. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  5854. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  5855. beg end)
  5856. (cond
  5857. ((memq state '(overview contents t))
  5858. (setq beg (point-min) end (point-max)))
  5859. ((memq state '(children folded))
  5860. (setq beg (point)
  5861. end (progn (org-end-of-subtree t t)
  5862. (line-beginning-position 2)))))
  5863. (when beg
  5864. (goto-char beg)
  5865. (while (re-search-forward re end t)
  5866. (unless (get-char-property (match-end 1) 'invisible)
  5867. (let ((e (match-end 1))
  5868. (b (if (>= org-cycle-separator-lines 0)
  5869. (match-beginning 1)
  5870. (save-excursion
  5871. (goto-char (match-beginning 0))
  5872. (skip-chars-backward " \t\n")
  5873. (line-end-position)))))
  5874. (org-flag-region b e nil 'outline))))))))
  5875. ;; Never hide empty lines at the end of the file.
  5876. (save-excursion
  5877. (goto-char (point-max))
  5878. (outline-previous-heading)
  5879. (outline-end-of-heading)
  5880. (when (and (looking-at "[ \t\n]+")
  5881. (= (match-end 0) (point-max)))
  5882. (org-flag-region (point) (match-end 0) nil 'outline))))
  5883. ;;;; Reveal point location
  5884. (defun org-show-context (&optional key)
  5885. "Make sure point and context are visible.
  5886. Optional argument KEY, when non-nil, is a symbol. See
  5887. `org-show-context-detail' for allowed values and how much is to
  5888. be shown."
  5889. (org-show-set-visibility
  5890. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  5891. ((cdr (assq key org-show-context-detail)))
  5892. (t (cdr (assq 'default org-show-context-detail))))))
  5893. (defun org-show-set-visibility (detail)
  5894. "Set visibility around point according to DETAIL.
  5895. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  5896. `tree', `canonical' or t. See `org-show-context-detail' for more
  5897. information."
  5898. ;; Show current heading and possibly its entry, following headline
  5899. ;; or all children.
  5900. (if (and (org-at-heading-p) (not (eq detail 'local)))
  5901. (org-flag-heading nil)
  5902. (org-show-entry)
  5903. ;; If point is hidden within a drawer or a block, make sure to
  5904. ;; expose it.
  5905. (dolist (o (overlays-at (point)))
  5906. (when (memq (overlay-get o 'invisible)
  5907. '(org-hide-block org-hide-drawer outline))
  5908. (delete-overlay o)))
  5909. (unless (org-before-first-heading-p)
  5910. (org-with-limited-levels
  5911. (cl-case detail
  5912. ((tree canonical t) (org-show-children))
  5913. ((nil minimal ancestors))
  5914. (t (save-excursion
  5915. (outline-next-heading)
  5916. (org-flag-heading nil)))))))
  5917. ;; Show all siblings.
  5918. (when (eq detail 'lineage) (org-show-siblings))
  5919. ;; Show ancestors, possibly with their children.
  5920. (when (memq detail '(ancestors lineage tree canonical t))
  5921. (save-excursion
  5922. (while (org-up-heading-safe)
  5923. (org-flag-heading nil)
  5924. (when (memq detail '(canonical t)) (org-show-entry))
  5925. (when (memq detail '(tree canonical t)) (org-show-children))))))
  5926. (defvar org-reveal-start-hook nil
  5927. "Hook run before revealing a location.")
  5928. (defun org-reveal (&optional siblings)
  5929. "Show current entry, hierarchy above it, and the following headline.
  5930. This can be used to show a consistent set of context around
  5931. locations exposed with `org-show-context'.
  5932. With optional argument SIBLINGS, on each level of the hierarchy all
  5933. siblings are shown. This repairs the tree structure to what it would
  5934. look like when opened with hierarchical calls to `org-cycle'.
  5935. With a \\[universal-argument] \\[universal-argument] prefix, \
  5936. go to the parent and show the entire tree."
  5937. (interactive "P")
  5938. (run-hooks 'org-reveal-start-hook)
  5939. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  5940. ((equal siblings '(16))
  5941. (save-excursion
  5942. (when (org-up-heading-safe)
  5943. (org-show-subtree)
  5944. (run-hook-with-args 'org-cycle-hook 'subtree))))
  5945. (t (org-show-set-visibility 'lineage))))
  5946. ;;; Indirect buffer display of subtrees
  5947. (defvar org-indirect-dedicated-frame nil
  5948. "This is the frame being used for indirect tree display.")
  5949. (defvar org-last-indirect-buffer nil)
  5950. (defun org-tree-to-indirect-buffer (&optional arg)
  5951. "Create indirect buffer and narrow it to current subtree.
  5952. With a numerical prefix ARG, go up to this level and then take that tree.
  5953. If ARG is negative, go up that many levels.
  5954. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  5955. indirect buffer previously made with this command, to avoid proliferation of
  5956. indirect buffers. However, when you call the command with a \
  5957. `\\[universal-argument]' prefix, or
  5958. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  5959. so that you can work with several indirect buffers at the same time. If
  5960. `org-indirect-buffer-display' is `dedicated-frame', the \
  5961. `\\[universal-argument]' prefix also
  5962. requests that a new frame be made for the new buffer, so that the dedicated
  5963. frame is not changed."
  5964. (interactive "P")
  5965. (let ((cbuf (current-buffer))
  5966. (cwin (selected-window))
  5967. (pos (point))
  5968. beg end level heading ibuf)
  5969. (save-excursion
  5970. (org-back-to-heading t)
  5971. (when (numberp arg)
  5972. (setq level (org-outline-level))
  5973. (when (< arg 0) (setq arg (+ level arg)))
  5974. (while (> (setq level (org-outline-level)) arg)
  5975. (org-up-heading-safe)))
  5976. (setq beg (point)
  5977. heading (org-get-heading 'no-tags))
  5978. (org-end-of-subtree t t)
  5979. (when (org-at-heading-p) (backward-char 1))
  5980. (setq end (point)))
  5981. (when (and (buffer-live-p org-last-indirect-buffer)
  5982. (not (eq org-indirect-buffer-display 'new-frame))
  5983. (not arg))
  5984. (kill-buffer org-last-indirect-buffer))
  5985. (setq ibuf (org-get-indirect-buffer cbuf heading)
  5986. org-last-indirect-buffer ibuf)
  5987. (cond
  5988. ((or (eq org-indirect-buffer-display 'new-frame)
  5989. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  5990. (select-frame (make-frame))
  5991. (delete-other-windows)
  5992. (pop-to-buffer-same-window ibuf)
  5993. (org-set-frame-title heading))
  5994. ((eq org-indirect-buffer-display 'dedicated-frame)
  5995. (raise-frame
  5996. (select-frame (or (and org-indirect-dedicated-frame
  5997. (frame-live-p org-indirect-dedicated-frame)
  5998. org-indirect-dedicated-frame)
  5999. (setq org-indirect-dedicated-frame (make-frame)))))
  6000. (delete-other-windows)
  6001. (pop-to-buffer-same-window ibuf)
  6002. (org-set-frame-title (concat "Indirect: " heading)))
  6003. ((eq org-indirect-buffer-display 'current-window)
  6004. (pop-to-buffer-same-window ibuf))
  6005. ((eq org-indirect-buffer-display 'other-window)
  6006. (pop-to-buffer ibuf))
  6007. (t (error "Invalid value")))
  6008. (narrow-to-region beg end)
  6009. (org-show-all '(headings blocks))
  6010. (goto-char pos)
  6011. (run-hook-with-args 'org-cycle-hook 'all)
  6012. (and (window-live-p cwin) (select-window cwin))))
  6013. (defun org-get-indirect-buffer (&optional buffer heading)
  6014. (setq buffer (or buffer (current-buffer)))
  6015. (let ((n 1) (base (buffer-name buffer)) bname)
  6016. (while (buffer-live-p
  6017. (get-buffer
  6018. (setq bname
  6019. (concat base "-"
  6020. (if heading (concat heading "-" (number-to-string n))
  6021. (number-to-string n))))))
  6022. (setq n (1+ n)))
  6023. (condition-case nil
  6024. (make-indirect-buffer buffer bname 'clone)
  6025. (error (make-indirect-buffer buffer bname)))))
  6026. (defun org-set-frame-title (title)
  6027. "Set the title of the current frame to the string TITLE."
  6028. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6029. ;;;; Structure editing
  6030. ;;; Inserting headlines
  6031. (defun org--blank-before-heading-p (&optional parent)
  6032. "Non-nil when an empty line should precede a new heading here.
  6033. When optional argument PARENT is non-nil, consider parent
  6034. headline instead of current one."
  6035. (pcase (assq 'heading org-blank-before-new-entry)
  6036. (`(heading . auto)
  6037. (save-excursion
  6038. (org-with-limited-levels
  6039. (unless (and (org-before-first-heading-p)
  6040. (not (outline-next-heading)))
  6041. (org-back-to-heading t)
  6042. (when parent (org-up-heading-safe))
  6043. (cond ((not (bobp))
  6044. (org-previous-line-empty-p))
  6045. ((outline-next-heading)
  6046. (org-previous-line-empty-p))
  6047. ;; Ignore trailing spaces on last buffer line.
  6048. ((progn (skip-chars-backward " \t") (bolp))
  6049. (org-previous-line-empty-p))
  6050. (t nil))))))
  6051. (`(heading . ,value) value)
  6052. (_ nil)))
  6053. (defun org-insert-heading (&optional arg invisible-ok top)
  6054. "Insert a new heading or an item with the same depth at point.
  6055. If point is at the beginning of a heading, insert a new heading
  6056. or a new headline above the current one. When at the beginning
  6057. of a regular line of text, turn it into a heading.
  6058. If point is in the middle of a line, split it and create a new
  6059. headline with the text in the current line after point (see
  6060. `org-M-RET-may-split-line' on how to modify this behavior). As
  6061. a special case, on a headline, splitting can only happen on the
  6062. title itself. E.g., this excludes breaking stars or tags.
  6063. With a `\\[universal-argument]' prefix, set \
  6064. `org-insert-heading-respect-content' to
  6065. a non-nil value for the duration of the command. This forces the
  6066. insertion of a heading after the current subtree, independently
  6067. on the location of point.
  6068. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6069. insert the heading at the end of the tree
  6070. above the current heading. For example, if point is within a
  6071. 2nd-level heading, then it will insert a 2nd-level heading at
  6072. the end of the 1st-level parent subtree.
  6073. When INVISIBLE-OK is set, stop at invisible headlines when going
  6074. back. This is important for non-interactive uses of the
  6075. command.
  6076. When optional argument TOP is non-nil, insert a level 1 heading,
  6077. unconditionally."
  6078. (interactive "P")
  6079. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6080. (level (org-current-level))
  6081. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6082. (cond
  6083. ((or org-insert-heading-respect-content
  6084. (member arg '((4) (16)))
  6085. (and (not invisible-ok)
  6086. (invisible-p (max (1- (point)) (point-min)))))
  6087. ;; Position point at the location of insertion. Make sure we
  6088. ;; end up on a visible headline if INVISIBLE-OK is nil.
  6089. (org-with-limited-levels
  6090. (if (not level) (outline-next-heading) ;before first headline
  6091. (org-back-to-heading invisible-ok)
  6092. (when (equal arg '(16)) (org-up-heading-safe))
  6093. (org-end-of-subtree)))
  6094. (unless (bolp) (insert "\n"))
  6095. (unless (and blank? (org-previous-line-empty-p))
  6096. (org-N-empty-lines-before-current (if blank? 1 0)))
  6097. (insert stars " ")
  6098. ;; When INVISIBLE-OK is non-nil, ensure newly created headline
  6099. ;; is visible.
  6100. (unless invisible-ok
  6101. (pcase (get-char-property-and-overlay (point) 'invisible)
  6102. (`(outline . ,o)
  6103. (move-overlay o (overlay-start o) (line-end-position 0)))
  6104. (_ nil))))
  6105. ;; At a headline...
  6106. ((org-at-heading-p)
  6107. (cond ((bolp)
  6108. (when blank? (save-excursion (insert "\n")))
  6109. (save-excursion (insert stars " \n"))
  6110. (unless (and blank? (org-previous-line-empty-p))
  6111. (org-N-empty-lines-before-current (if blank? 1 0)))
  6112. (end-of-line))
  6113. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6114. (org-match-line org-complex-heading-regexp)
  6115. (org-pos-in-match-range (point) 4))
  6116. ;; Grab the text that should moved to the new headline.
  6117. ;; Preserve tags.
  6118. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6119. (if (looking-at "[ \t]*$") (replace-match "")
  6120. (org-align-tags))
  6121. (end-of-line)
  6122. (when blank? (insert "\n"))
  6123. (insert "\n" stars " ")
  6124. (when (org-string-nw-p split) (insert split))))
  6125. (t
  6126. (end-of-line)
  6127. (when blank? (insert "\n"))
  6128. (insert "\n" stars " "))))
  6129. ;; On regular text, turn line into a headline or split, if
  6130. ;; appropriate.
  6131. ((bolp)
  6132. (insert stars " ")
  6133. (unless (and blank? (org-previous-line-empty-p))
  6134. (org-N-empty-lines-before-current (if blank? 1 0))))
  6135. (t
  6136. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6137. (end-of-line))
  6138. (insert "\n" stars " ")
  6139. (unless (and blank? (org-previous-line-empty-p))
  6140. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6141. (run-hooks 'org-insert-heading-hook))
  6142. (defun org-N-empty-lines-before-current (n)
  6143. "Make the number of empty lines before current exactly N.
  6144. So this will delete or add empty lines."
  6145. (let ((column (current-column)))
  6146. (beginning-of-line)
  6147. (unless (bobp)
  6148. (let ((start (save-excursion
  6149. (skip-chars-backward " \r\t\n")
  6150. (line-end-position))))
  6151. (delete-region start (line-end-position 0))))
  6152. (insert (make-string n ?\n))
  6153. (move-to-column column)))
  6154. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6155. "Return the heading of the current entry, without the stars.
  6156. When NO-TAGS is non-nil, don't include tags.
  6157. When NO-TODO is non-nil, don't include TODO keywords.
  6158. When NO-PRIORITY is non-nil, don't include priority cookie.
  6159. When NO-COMMENT is non-nil, don't include COMMENT string.
  6160. Return nil before first heading."
  6161. (unless (org-before-first-heading-p)
  6162. (save-excursion
  6163. (org-back-to-heading t)
  6164. (let ((case-fold-search nil))
  6165. (looking-at org-complex-heading-regexp)
  6166. (let ((todo (and (not no-todo) (match-string 2)))
  6167. (priority (and (not no-priority) (match-string 3)))
  6168. (headline (pcase (match-string 4)
  6169. (`nil "")
  6170. ((and (guard no-comment) h)
  6171. (replace-regexp-in-string
  6172. (eval-when-compile
  6173. (format "\\`%s[ \t]+" org-comment-string))
  6174. "" h))
  6175. (h h)))
  6176. (tags (and (not no-tags) (match-string 5))))
  6177. (mapconcat #'identity
  6178. (delq nil (list todo priority headline tags))
  6179. " "))))))
  6180. (defun org-heading-components ()
  6181. "Return the components of the current heading.
  6182. This is a list with the following elements:
  6183. - the level as an integer
  6184. - the reduced level, different if `org-odd-levels-only' is set.
  6185. - the TODO keyword, or nil
  6186. - the priority character, like ?A, or nil if no priority is given
  6187. - the headline text itself, or the tags string if no headline text
  6188. - the tags string, or nil."
  6189. (save-excursion
  6190. (org-back-to-heading t)
  6191. (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
  6192. (list (length (match-string 1))
  6193. (org-reduced-level (length (match-string 1)))
  6194. (match-string-no-properties 2)
  6195. (and (match-end 3) (aref (match-string 3) 2))
  6196. (match-string-no-properties 4)
  6197. (match-string-no-properties 5)))))
  6198. (defun org-get-entry ()
  6199. "Get the entry text, after heading, entire subtree."
  6200. (save-excursion
  6201. (org-back-to-heading t)
  6202. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  6203. (defun org-edit-headline (&optional heading)
  6204. "Edit the current headline.
  6205. Set it to HEADING when provided."
  6206. (interactive)
  6207. (org-with-wide-buffer
  6208. (org-back-to-heading t)
  6209. (let ((case-fold-search nil))
  6210. (when (looking-at org-complex-heading-regexp)
  6211. (let* ((old (match-string-no-properties 4))
  6212. (new (save-match-data
  6213. (org-trim (or heading (read-string "Edit: " old))))))
  6214. (unless (equal old new)
  6215. (if old (replace-match new t t nil 4)
  6216. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  6217. (insert " " new))
  6218. (org-align-tags)
  6219. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  6220. (defun org-insert-heading-after-current ()
  6221. "Insert a new heading with same level as current, after current subtree."
  6222. (interactive)
  6223. (org-back-to-heading)
  6224. (org-insert-heading)
  6225. (org-move-subtree-down)
  6226. (end-of-line 1))
  6227. (defun org-insert-heading-respect-content (&optional invisible-ok)
  6228. "Insert heading with `org-insert-heading-respect-content' set to t."
  6229. (interactive)
  6230. (org-insert-heading '(4) invisible-ok))
  6231. (defun org-insert-todo-heading-respect-content (&optional force-state)
  6232. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  6233. (interactive)
  6234. (org-insert-todo-heading force-state '(4)))
  6235. (defun org-insert-todo-heading (arg &optional force-heading)
  6236. "Insert a new heading with the same level and TODO state as current heading.
  6237. If the heading has no TODO state, or if the state is DONE, use
  6238. the first state (TODO by default). Also with one prefix arg,
  6239. force first state. With two prefix args, force inserting at the
  6240. end of the parent subtree.
  6241. When called at a plain list item, insert a new item with an
  6242. unchecked check box."
  6243. (interactive "P")
  6244. (when (or force-heading (not (org-insert-item 'checkbox)))
  6245. (org-insert-heading (or (and (equal arg '(16)) '(16))
  6246. force-heading))
  6247. (save-excursion
  6248. (org-forward-heading-same-level -1)
  6249. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  6250. (let* ((new-mark-x
  6251. (if (or (equal arg '(4))
  6252. (not (match-beginning 2))
  6253. (member (match-string 2) org-done-keywords))
  6254. (car org-todo-keywords-1)
  6255. (match-string 2)))
  6256. (new-mark
  6257. (or
  6258. (run-hook-with-args-until-success
  6259. 'org-todo-get-default-hook new-mark-x nil)
  6260. new-mark-x)))
  6261. (beginning-of-line 1)
  6262. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  6263. (if org-treat-insert-todo-heading-as-state-change
  6264. (org-todo new-mark)
  6265. (insert new-mark " "))))
  6266. (when org-provide-todo-statistics
  6267. (org-update-parent-todo-statistics))))
  6268. (defun org-insert-subheading (arg)
  6269. "Insert a new subheading and demote it.
  6270. Works for outline headings and for plain lists alike."
  6271. (interactive "P")
  6272. (org-insert-heading arg)
  6273. (cond
  6274. ((org-at-heading-p) (org-do-demote))
  6275. ((org-at-item-p) (org-indent-item))))
  6276. (defun org-insert-todo-subheading (arg)
  6277. "Insert a new subheading with TODO keyword or checkbox and demote it.
  6278. Works for outline headings and for plain lists alike."
  6279. (interactive "P")
  6280. (org-insert-todo-heading arg)
  6281. (cond
  6282. ((org-at-heading-p) (org-do-demote))
  6283. ((org-at-item-p) (org-indent-item))))
  6284. ;;; Promotion and Demotion
  6285. (defvar org-after-demote-entry-hook nil
  6286. "Hook run after an entry has been demoted.
  6287. The cursor will be at the beginning of the entry.
  6288. When a subtree is being demoted, the hook will be called for each node.")
  6289. (defvar org-after-promote-entry-hook nil
  6290. "Hook run after an entry has been promoted.
  6291. The cursor will be at the beginning of the entry.
  6292. When a subtree is being promoted, the hook will be called for each node.")
  6293. (defun org-promote-subtree ()
  6294. "Promote the entire subtree.
  6295. See also `org-promote'."
  6296. (interactive)
  6297. (save-excursion
  6298. (org-with-limited-levels (org-map-tree 'org-promote)))
  6299. (org-fix-position-after-promote))
  6300. (defun org-demote-subtree ()
  6301. "Demote the entire subtree.
  6302. See `org-demote' and `org-promote'."
  6303. (interactive)
  6304. (save-excursion
  6305. (org-with-limited-levels (org-map-tree 'org-demote)))
  6306. (org-fix-position-after-promote))
  6307. (defun org-do-promote ()
  6308. "Promote the current heading higher up the tree.
  6309. If the region is active in `transient-mark-mode', promote all
  6310. headings in the region."
  6311. (interactive)
  6312. (save-excursion
  6313. (if (org-region-active-p)
  6314. (org-map-region 'org-promote (region-beginning) (region-end))
  6315. (org-promote)))
  6316. (org-fix-position-after-promote))
  6317. (defun org-do-demote ()
  6318. "Demote the current heading lower down the tree.
  6319. If the region is active in `transient-mark-mode', demote all
  6320. headings in the region."
  6321. (interactive)
  6322. (save-excursion
  6323. (if (org-region-active-p)
  6324. (org-map-region 'org-demote (region-beginning) (region-end))
  6325. (org-demote)))
  6326. (org-fix-position-after-promote))
  6327. (defun org-fix-position-after-promote ()
  6328. "Fix cursor position and indentation after demoting/promoting."
  6329. (let ((pos (point)))
  6330. (when (save-excursion
  6331. (beginning-of-line)
  6332. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  6333. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  6334. (cond ((eobp) (insert " "))
  6335. ((eolp) (insert " "))
  6336. ((equal (char-after) ?\s) (forward-char 1))))))
  6337. (defun org-current-level ()
  6338. "Return the level of the current entry, or nil if before the first headline.
  6339. The level is the number of stars at the beginning of the
  6340. headline. Use `org-reduced-level' to remove the effect of
  6341. `org-odd-levels'. Unlike to `org-outline-level', this function
  6342. ignores inlinetasks."
  6343. (let ((level (org-with-limited-levels (org-outline-level))))
  6344. (and (> level 0) level)))
  6345. (defun org-get-previous-line-level ()
  6346. "Return the outline depth of the last headline before the current line.
  6347. Returns 0 for the first headline in the buffer, and nil if before the
  6348. first headline."
  6349. (and (org-current-level)
  6350. (or (and (/= (line-beginning-position) (point-min))
  6351. (save-excursion (beginning-of-line 0) (org-current-level)))
  6352. 0)))
  6353. (defun org-reduced-level (l)
  6354. "Compute the effective level of a heading.
  6355. This takes into account the setting of `org-odd-levels-only'."
  6356. (cond
  6357. ((zerop l) 0)
  6358. (org-odd-levels-only (1+ (floor (/ l 2))))
  6359. (t l)))
  6360. (defun org-level-increment ()
  6361. "Return the number of stars that will be added or removed at a
  6362. time to headlines when structure editing, based on the value of
  6363. `org-odd-levels-only'."
  6364. (if org-odd-levels-only 2 1))
  6365. (defun org-get-valid-level (level &optional change)
  6366. "Rectify a level change under the influence of `org-odd-levels-only'.
  6367. LEVEL is a current level, CHANGE is by how much the level should
  6368. be modified. Even if CHANGE is nil, LEVEL may be returned
  6369. modified because even level numbers will become the next higher
  6370. odd number. Returns values greater than 0."
  6371. (if org-odd-levels-only
  6372. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  6373. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  6374. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  6375. (max 1 (+ level (or change 0)))))
  6376. (defun org-promote ()
  6377. "Promote the current heading higher up the tree."
  6378. (org-with-wide-buffer
  6379. (org-back-to-heading t)
  6380. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6381. after-change-functions))
  6382. (level (save-match-data (funcall outline-level)))
  6383. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  6384. (diff (abs (- level (length up-head) -1))))
  6385. (cond
  6386. ((and (= level 1) org-allow-promoting-top-level-subtree)
  6387. (replace-match "# " nil t))
  6388. ((= level 1)
  6389. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  6390. (t (replace-match up-head nil t)))
  6391. (unless (= level 1)
  6392. (when org-auto-align-tags (org-align-tags))
  6393. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  6394. (run-hooks 'org-after-promote-entry-hook))))
  6395. (defun org-demote ()
  6396. "Demote the current heading lower down the tree."
  6397. (org-with-wide-buffer
  6398. (org-back-to-heading t)
  6399. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6400. after-change-functions))
  6401. (level (save-match-data (funcall outline-level)))
  6402. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  6403. (diff (abs (- level (length down-head) -1))))
  6404. (replace-match down-head nil t)
  6405. (when org-auto-align-tags (org-align-tags))
  6406. (when org-adapt-indentation (org-fixup-indentation diff))
  6407. (run-hooks 'org-after-demote-entry-hook))))
  6408. (defun org-cycle-level ()
  6409. "Cycle the level of an empty headline through possible states.
  6410. This goes first to child, then to parent, level, then up the hierarchy.
  6411. After top level, it switches back to sibling level."
  6412. (interactive)
  6413. (let ((org-adapt-indentation nil))
  6414. (when (org-point-at-end-of-empty-headline)
  6415. (setq this-command 'org-cycle-level) ; Only needed for caching
  6416. (let ((cur-level (org-current-level))
  6417. (prev-level (org-get-previous-line-level)))
  6418. (cond
  6419. ;; If first headline in file, promote to top-level.
  6420. ((= prev-level 0)
  6421. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6422. do (org-do-promote)))
  6423. ;; If same level as prev, demote one.
  6424. ((= prev-level cur-level)
  6425. (org-do-demote))
  6426. ;; If parent is top-level, promote to top level if not already.
  6427. ((= prev-level 1)
  6428. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6429. do (org-do-promote)))
  6430. ;; If top-level, return to prev-level.
  6431. ((= cur-level 1)
  6432. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  6433. do (org-do-demote)))
  6434. ;; If less than prev-level, promote one.
  6435. ((< cur-level prev-level)
  6436. (org-do-promote))
  6437. ;; If deeper than prev-level, promote until higher than
  6438. ;; prev-level.
  6439. ((> cur-level prev-level)
  6440. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  6441. do (org-do-promote))))
  6442. t))))
  6443. (defun org-map-tree (fun)
  6444. "Call FUN for every heading underneath the current one."
  6445. (org-back-to-heading t)
  6446. (let ((level (funcall outline-level)))
  6447. (save-excursion
  6448. (funcall fun)
  6449. (while (and (progn
  6450. (outline-next-heading)
  6451. (> (funcall outline-level) level))
  6452. (not (eobp)))
  6453. (funcall fun)))))
  6454. (defun org-map-region (fun beg end)
  6455. "Call FUN for every heading between BEG and END."
  6456. (let ((org-ignore-region t))
  6457. (save-excursion
  6458. (setq end (copy-marker end))
  6459. (goto-char beg)
  6460. (when (and (re-search-forward org-outline-regexp-bol nil t)
  6461. (< (point) end))
  6462. (funcall fun))
  6463. (while (and (progn
  6464. (outline-next-heading)
  6465. (< (point) end))
  6466. (not (eobp)))
  6467. (funcall fun)))))
  6468. (defun org-fixup-indentation (diff)
  6469. "Change the indentation in the current entry by DIFF.
  6470. DIFF is an integer. Indentation is done according to the
  6471. following rules:
  6472. - Planning information and property drawers are always indented
  6473. according to the new level of the headline;
  6474. - Footnote definitions and their contents are ignored;
  6475. - Inlinetasks' boundaries are not shifted;
  6476. - Empty lines are ignored;
  6477. - Other lines' indentation are shifted by DIFF columns, unless
  6478. it would introduce a structural change in the document, in
  6479. which case no shifting is done at all.
  6480. Assume point is at a heading or an inlinetask beginning."
  6481. (org-with-wide-buffer
  6482. (narrow-to-region (line-beginning-position)
  6483. (save-excursion
  6484. (if (org-with-limited-levels (org-at-heading-p))
  6485. (org-with-limited-levels (outline-next-heading))
  6486. (org-inlinetask-goto-end))
  6487. (point)))
  6488. (forward-line)
  6489. ;; Indent properly planning info and property drawer.
  6490. (when (looking-at-p org-planning-line-re)
  6491. (org-indent-line)
  6492. (forward-line))
  6493. (when (looking-at org-property-drawer-re)
  6494. (goto-char (match-end 0))
  6495. (forward-line)
  6496. (org-indent-region (match-beginning 0) (match-end 0)))
  6497. (when (looking-at org-logbook-drawer-re)
  6498. (goto-char (match-end 0))
  6499. (forward-line)
  6500. (org-indent-region (match-beginning 0) (match-end 0)))
  6501. (catch 'no-shift
  6502. (when (or (zerop diff) (not (eq org-adapt-indentation t)))
  6503. (throw 'no-shift nil))
  6504. ;; If DIFF is negative, first check if a shift is possible at all
  6505. ;; (e.g., it doesn't break structure). This can only happen if
  6506. ;; some contents are not properly indented.
  6507. (let ((case-fold-search t))
  6508. (when (< diff 0)
  6509. (let ((diff (- diff))
  6510. (forbidden-re (concat org-outline-regexp
  6511. "\\|"
  6512. (substring org-footnote-definition-re 1))))
  6513. (save-excursion
  6514. (while (not (eobp))
  6515. (cond
  6516. ((looking-at-p "[ \t]*$") (forward-line))
  6517. ((and (looking-at-p org-footnote-definition-re)
  6518. (let ((e (org-element-at-point)))
  6519. (and (eq (org-element-type e) 'footnote-definition)
  6520. (goto-char (org-element-property :end e))))))
  6521. ((looking-at-p org-outline-regexp) (forward-line))
  6522. ;; Give up if shifting would move before column 0 or
  6523. ;; if it would introduce a headline or a footnote
  6524. ;; definition.
  6525. (t
  6526. (skip-chars-forward " \t")
  6527. (let ((ind (current-column)))
  6528. (when (or (< ind diff)
  6529. (and (= ind diff) (looking-at-p forbidden-re)))
  6530. (throw 'no-shift nil)))
  6531. ;; Ignore contents of example blocks and source
  6532. ;; blocks if their indentation is meant to be
  6533. ;; preserved. Jump to block's closing line.
  6534. (beginning-of-line)
  6535. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6536. (let ((e (org-element-at-point)))
  6537. (and (memq (org-element-type e)
  6538. '(example-block src-block))
  6539. (or org-src-preserve-indentation
  6540. (org-element-property :preserve-indent e))
  6541. (goto-char (org-element-property :end e))
  6542. (progn (skip-chars-backward " \r\t\n")
  6543. (beginning-of-line)
  6544. t))))
  6545. (forward-line))))))))
  6546. ;; Shift lines but footnote definitions, inlinetasks boundaries
  6547. ;; by DIFF. Also skip contents of source or example blocks
  6548. ;; when indentation is meant to be preserved.
  6549. (while (not (eobp))
  6550. (cond
  6551. ((and (looking-at-p org-footnote-definition-re)
  6552. (let ((e (org-element-at-point)))
  6553. (and (eq (org-element-type e) 'footnote-definition)
  6554. (goto-char (org-element-property :end e))))))
  6555. ((looking-at-p org-outline-regexp) (forward-line))
  6556. ((looking-at-p "[ \t]*$") (forward-line))
  6557. (t
  6558. (indent-line-to (+ (current-indentation) diff))
  6559. (beginning-of-line)
  6560. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6561. (let ((e (org-element-at-point)))
  6562. (and (memq (org-element-type e)
  6563. '(example-block src-block))
  6564. (or org-src-preserve-indentation
  6565. (org-element-property :preserve-indent e))
  6566. (goto-char (org-element-property :end e))
  6567. (progn (skip-chars-backward " \r\t\n")
  6568. (beginning-of-line)
  6569. t))))
  6570. (forward-line)))))))))
  6571. (defun org-convert-to-odd-levels ()
  6572. "Convert an Org file with all levels allowed to one with odd levels.
  6573. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  6574. level 5 etc."
  6575. (interactive)
  6576. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  6577. (let ((outline-level 'org-outline-level)
  6578. (org-odd-levels-only nil) n)
  6579. (save-excursion
  6580. (goto-char (point-min))
  6581. (while (re-search-forward "^\\*\\*+ " nil t)
  6582. (setq n (- (length (match-string 0)) 2))
  6583. (while (>= (setq n (1- n)) 0)
  6584. (org-demote))
  6585. (end-of-line 1))))))
  6586. (defun org-convert-to-oddeven-levels ()
  6587. "Convert an Org file with only odd levels to one with odd/even levels.
  6588. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  6589. file contains a section with an even level, conversion would
  6590. destroy the structure of the file. An error is signaled in this
  6591. case."
  6592. (interactive)
  6593. (goto-char (point-min))
  6594. ;; First check if there are no even levels
  6595. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  6596. (org-show-set-visibility 'canonical)
  6597. (error "Not all levels are odd in this file. Conversion not possible"))
  6598. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  6599. (let ((outline-regexp org-outline-regexp)
  6600. (outline-level 'org-outline-level)
  6601. (org-odd-levels-only nil) n)
  6602. (save-excursion
  6603. (goto-char (point-min))
  6604. (while (re-search-forward "^\\*\\*+ " nil t)
  6605. (setq n (/ (1- (length (match-string 0))) 2))
  6606. (while (>= (setq n (1- n)) 0)
  6607. (org-promote))
  6608. (end-of-line 1))))))
  6609. (defun org-tr-level (n)
  6610. "Make N odd if required."
  6611. (if org-odd-levels-only (1+ (/ n 2)) n))
  6612. ;;; Vertical tree motion, cutting and pasting of subtrees
  6613. (defun org-move-subtree-up (&optional arg)
  6614. "Move the current subtree up past ARG headlines of the same level."
  6615. (interactive "p")
  6616. (org-move-subtree-down (- (prefix-numeric-value arg))))
  6617. (defun org-move-subtree-down (&optional arg)
  6618. "Move the current subtree down past ARG headlines of the same level."
  6619. (interactive "p")
  6620. (setq arg (prefix-numeric-value arg))
  6621. (org-preserve-local-variables
  6622. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  6623. 'org-get-last-sibling))
  6624. (ins-point (make-marker))
  6625. (cnt (abs arg))
  6626. (col (current-column))
  6627. beg end txt folded)
  6628. ;; Select the tree
  6629. (org-back-to-heading)
  6630. (setq beg (point))
  6631. (save-match-data
  6632. (save-excursion (outline-end-of-heading)
  6633. (setq folded (org-invisible-p)))
  6634. (progn (org-end-of-subtree nil t)
  6635. (unless (eobp) (backward-char))))
  6636. (outline-next-heading)
  6637. (setq end (point))
  6638. (goto-char beg)
  6639. ;; Find insertion point, with error handling
  6640. (while (> cnt 0)
  6641. (unless (and (funcall movfunc) (looking-at org-outline-regexp))
  6642. (goto-char beg)
  6643. (user-error "Cannot move past superior level or buffer limit"))
  6644. (setq cnt (1- cnt)))
  6645. (when (> arg 0)
  6646. ;; Moving forward - still need to move over subtree
  6647. (org-end-of-subtree t t)
  6648. (save-excursion
  6649. (org-back-over-empty-lines)
  6650. (or (bolp) (newline))))
  6651. (move-marker ins-point (point))
  6652. (setq txt (buffer-substring beg end))
  6653. (org-save-markers-in-region beg end)
  6654. (delete-region beg end)
  6655. (org-remove-empty-overlays-at beg)
  6656. (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
  6657. (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
  6658. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  6659. (let ((bbb (point)))
  6660. (insert-before-markers txt)
  6661. (org-reinstall-markers-in-region bbb)
  6662. (move-marker ins-point bbb))
  6663. (or (bolp) (insert "\n"))
  6664. (goto-char ins-point)
  6665. (org-skip-whitespace)
  6666. (move-marker ins-point nil)
  6667. (if folded
  6668. (org-flag-subtree t)
  6669. (org-show-entry)
  6670. (org-show-children))
  6671. (org-clean-visibility-after-subtree-move)
  6672. ;; move back to the initial column we were at
  6673. (move-to-column col))))
  6674. (defvar org-subtree-clip ""
  6675. "Clipboard for cut and paste of subtrees.
  6676. This is actually only a copy of the kill, because we use the normal kill
  6677. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  6678. (defvar org-subtree-clip-folded nil
  6679. "Was the last copied subtree folded?
  6680. This is used to fold the tree back after pasting.")
  6681. (defun org-cut-subtree (&optional n)
  6682. "Cut the current subtree into the clipboard.
  6683. With prefix arg N, cut this many sequential subtrees.
  6684. This is a short-hand for marking the subtree and then cutting it."
  6685. (interactive "p")
  6686. (org-copy-subtree n 'cut))
  6687. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  6688. "Copy the current subtree into the clipboard.
  6689. With prefix arg N, copy this many sequential subtrees.
  6690. This is a short-hand for marking the subtree and then copying it.
  6691. If CUT is non-nil, actually cut the subtree.
  6692. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  6693. of some markers in the region, even if CUT is non-nil. This is
  6694. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  6695. (interactive "p")
  6696. (org-preserve-local-variables
  6697. (let (beg end folded (beg0 (point)))
  6698. (if (called-interactively-p 'any)
  6699. (org-back-to-heading nil) ; take what looks like a subtree
  6700. (org-back-to-heading t)) ; take what is really there
  6701. (setq beg (point))
  6702. (skip-chars-forward " \t\r\n")
  6703. (save-match-data
  6704. (if nosubtrees
  6705. (outline-next-heading)
  6706. (save-excursion (outline-end-of-heading)
  6707. (setq folded (org-invisible-p)))
  6708. (ignore-errors (org-forward-heading-same-level (1- n) t))
  6709. (org-end-of-subtree t t)))
  6710. ;; Include the end of an inlinetask
  6711. (when (and (featurep 'org-inlinetask)
  6712. (looking-at-p (concat (org-inlinetask-outline-regexp)
  6713. "END[ \t]*$")))
  6714. (end-of-line))
  6715. (setq end (point))
  6716. (goto-char beg0)
  6717. (when (> end beg)
  6718. (setq org-subtree-clip-folded folded)
  6719. (when (or cut force-store-markers)
  6720. (org-save-markers-in-region beg end))
  6721. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  6722. (setq org-subtree-clip (current-kill 0))
  6723. (message "%s: Subtree(s) with %d characters"
  6724. (if cut "Cut" "Copied")
  6725. (length org-subtree-clip))))))
  6726. (defun org-paste-subtree (&optional level tree for-yank remove)
  6727. "Paste the clipboard as a subtree, with modification of headline level.
  6728. The entire subtree is promoted or demoted in order to match a new headline
  6729. level.
  6730. If the cursor is at the beginning of a headline, the same level as
  6731. that headline is used to paste the tree.
  6732. If not, the new level is derived from the *visible* headings
  6733. before and after the insertion point, and taken to be the inferior headline
  6734. level of the two. So if the previous visible heading is level 3 and the
  6735. next is level 4 (or vice versa), level 4 will be used for insertion.
  6736. This makes sure that the subtree remains an independent subtree and does
  6737. not swallow low level entries.
  6738. You can also force a different level, either by using a numeric prefix
  6739. argument, or by inserting the heading marker by hand. For example, if the
  6740. cursor is after \"*****\", then the tree will be shifted to level 5.
  6741. If optional TREE is given, use this text instead of the kill ring.
  6742. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  6743. move back over whitespace before inserting, and move point to the end of
  6744. the inserted text when done.
  6745. When REMOVE is non-nil, remove the subtree from the clipboard."
  6746. (interactive "P")
  6747. (setq tree (or tree (and kill-ring (current-kill 0))))
  6748. (unless (org-kill-is-subtree-p tree)
  6749. (user-error
  6750. (substitute-command-keys
  6751. "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
  6752. (org-with-limited-levels
  6753. (let* ((visp (not (org-invisible-p)))
  6754. (txt tree)
  6755. (old-level (if (string-match org-outline-regexp-bol txt)
  6756. (- (match-end 0) (match-beginning 0) 1)
  6757. -1))
  6758. (force-level
  6759. (cond
  6760. (level (prefix-numeric-value level))
  6761. ;; When point is after the stars in an otherwise empty
  6762. ;; headline, use the number of stars as the forced level.
  6763. ((and (org-match-line "^\\*+[ \t]*$")
  6764. (not (eq ?* (char-after))))
  6765. (org-outline-level))
  6766. ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
  6767. (previous-level
  6768. (save-excursion
  6769. (org-previous-visible-heading 1)
  6770. (if (org-at-heading-p) (org-outline-level) 1)))
  6771. (next-level
  6772. (save-excursion
  6773. (if (org-at-heading-p) (org-outline-level)
  6774. (org-next-visible-heading 1)
  6775. (if (org-at-heading-p) (org-outline-level) 1))))
  6776. (new-level (or force-level (max previous-level next-level)))
  6777. (shift (if (or (= old-level -1)
  6778. (= new-level -1)
  6779. (= old-level new-level))
  6780. 0
  6781. (- new-level old-level)))
  6782. (delta (if (> shift 0) -1 1))
  6783. (func (if (> shift 0) #'org-demote #'org-promote))
  6784. (org-odd-levels-only nil)
  6785. beg end newend)
  6786. ;; Remove the forced level indicator.
  6787. (when (and force-level (not level))
  6788. (delete-region (line-beginning-position) (point)))
  6789. ;; Paste before the next visible heading or at end of buffer,
  6790. ;; unless point is at the beginning of a headline.
  6791. (unless (and (bolp) (org-at-heading-p))
  6792. (org-next-visible-heading 1)
  6793. (unless (bolp) (insert "\n")))
  6794. (setq beg (point))
  6795. (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  6796. (insert-before-markers txt)
  6797. (unless (string-suffix-p "\n" txt) (insert "\n"))
  6798. (setq newend (point))
  6799. (org-reinstall-markers-in-region beg)
  6800. (setq end (point))
  6801. (goto-char beg)
  6802. (skip-chars-forward " \t\n\r")
  6803. (setq beg (point))
  6804. (when (and (org-invisible-p) visp)
  6805. (save-excursion (outline-show-heading)))
  6806. ;; Shift if necessary.
  6807. (unless (= shift 0)
  6808. (save-restriction
  6809. (narrow-to-region beg end)
  6810. (while (not (= shift 0))
  6811. (org-map-region func (point-min) (point-max))
  6812. (setq shift (+ delta shift)))
  6813. (goto-char (point-min))
  6814. (setq newend (point-max))))
  6815. (when (or for-yank (called-interactively-p 'interactive))
  6816. (message "Clipboard pasted as level %d subtree" new-level))
  6817. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  6818. kill-ring
  6819. (equal org-subtree-clip (current-kill 0))
  6820. org-subtree-clip-folded)
  6821. ;; The tree was folded before it was killed/copied
  6822. (org-flag-subtree t))
  6823. (when for-yank (goto-char newend))
  6824. (when remove (pop kill-ring)))))
  6825. (defun org-kill-is-subtree-p (&optional txt)
  6826. "Check if the current kill is an outline subtree, or a set of trees.
  6827. Returns nil if kill does not start with a headline, or if the first
  6828. headline level is not the largest headline level in the tree.
  6829. So this will actually accept several entries of equal levels as well,
  6830. which is OK for `org-paste-subtree'.
  6831. If optional TXT is given, check this string instead of the current kill."
  6832. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  6833. (re (org-get-limited-outline-regexp))
  6834. (^re (concat "^" re))
  6835. (start-level (and kill
  6836. (string-match
  6837. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  6838. kill)
  6839. (- (match-end 2) (match-beginning 2) 1)))
  6840. (start (1+ (or (match-beginning 2) -1))))
  6841. (if (not start-level)
  6842. (progn
  6843. nil) ;; does not even start with a heading
  6844. (catch 'exit
  6845. (while (setq start (string-match ^re kill (1+ start)))
  6846. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  6847. (throw 'exit nil)))
  6848. t))))
  6849. (defvar org-markers-to-move nil
  6850. "Markers that should be moved with a cut-and-paste operation.
  6851. Those markers are stored together with their positions relative to
  6852. the start of the region.")
  6853. (defun org-save-markers-in-region (beg end)
  6854. "Check markers in region.
  6855. If these markers are between BEG and END, record their position relative
  6856. to BEG, so that after moving the block of text, we can put the markers back
  6857. into place.
  6858. This function gets called just before an entry or tree gets cut from the
  6859. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  6860. called immediately, to move the markers with the entries."
  6861. (setq org-markers-to-move nil)
  6862. (when (featurep 'org-clock)
  6863. (org-clock-save-markers-for-cut-and-paste beg end))
  6864. (when (featurep 'org-agenda)
  6865. (org-agenda-save-markers-for-cut-and-paste beg end)))
  6866. (defun org-check-and-save-marker (marker beg end)
  6867. "Check if MARKER is between BEG and END.
  6868. If yes, remember the marker and the distance to BEG."
  6869. (when (and (marker-buffer marker)
  6870. (equal (marker-buffer marker) (current-buffer))
  6871. (>= marker beg) (< marker end))
  6872. (push (cons marker (- marker beg)) org-markers-to-move)))
  6873. (defun org-reinstall-markers-in-region (beg)
  6874. "Move all remembered markers to their position relative to BEG."
  6875. (dolist (x org-markers-to-move)
  6876. (move-marker (car x) (+ beg (cdr x))))
  6877. (setq org-markers-to-move nil))
  6878. (defun org-narrow-to-subtree ()
  6879. "Narrow buffer to the current subtree."
  6880. (interactive)
  6881. (save-excursion
  6882. (save-match-data
  6883. (org-with-limited-levels
  6884. (narrow-to-region
  6885. (progn (org-back-to-heading t) (point))
  6886. (progn (org-end-of-subtree t t)
  6887. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  6888. (point)))))))
  6889. (defun org-toggle-narrow-to-subtree ()
  6890. "Narrow to the subtree at point or widen a narrowed buffer."
  6891. (interactive)
  6892. (if (buffer-narrowed-p)
  6893. (progn (widen) (message "Buffer widen"))
  6894. (org-narrow-to-subtree)
  6895. (message "Buffer narrowed to current subtree")))
  6896. (defun org-narrow-to-block ()
  6897. "Narrow buffer to the current block."
  6898. (interactive)
  6899. (let* ((case-fold-search t)
  6900. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  6901. "^[ \t]*#\\+end_.*")))
  6902. (if blockp
  6903. (narrow-to-region (car blockp) (cdr blockp))
  6904. (user-error "Not in a block"))))
  6905. (defun org-clone-subtree-with-time-shift (n &optional shift)
  6906. "Clone the task (subtree) at point N times.
  6907. The clones will be inserted as siblings.
  6908. In interactive use, the user will be prompted for the number of
  6909. clones to be produced. If the entry has a timestamp, the user
  6910. will also be prompted for a time shift, which may be a repeater
  6911. as used in time stamps, for example `+3d'. To disable this,
  6912. you can call the function with a universal prefix argument.
  6913. When a valid repeater is given and the entry contains any time
  6914. stamps, the clones will become a sequence in time, with time
  6915. stamps in the subtree shifted for each clone produced. If SHIFT
  6916. is nil or the empty string, time stamps will be left alone. The
  6917. ID property of the original subtree is removed.
  6918. In each clone, all the CLOCK entries will be removed. This
  6919. prevents Org from considering that the clocked times overlap.
  6920. If the original subtree did contain time stamps with a repeater,
  6921. the following will happen:
  6922. - the repeater will be removed in each clone
  6923. - an additional clone will be produced, with the current, unshifted
  6924. date(s) in the entry.
  6925. - the original entry will be placed *after* all the clones, with
  6926. repeater intact.
  6927. - the start days in the repeater in the original entry will be shifted
  6928. to past the last clone.
  6929. In this way you can spell out a number of instances of a repeating task,
  6930. and still retain the repeater to cover future instances of the task.
  6931. As described above, N+1 clones are produced when the original
  6932. subtree has a repeater. Setting N to 0, then, can be used to
  6933. remove the repeater from a subtree and create a shifted clone
  6934. with the original repeater."
  6935. (interactive "nNumber of clones to produce: ")
  6936. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  6937. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  6938. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  6939. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  6940. (shift
  6941. (or shift
  6942. (if (and (not (equal current-prefix-arg '(4)))
  6943. (save-excursion
  6944. (goto-char beg)
  6945. (re-search-forward org-ts-regexp-both end-of-tree t)))
  6946. (read-from-minibuffer
  6947. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  6948. ""))) ;No time shift
  6949. (doshift
  6950. (and (org-string-nw-p shift)
  6951. (or (string-match "\\`[ \t]*\\([+-]?[0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
  6952. shift)
  6953. (user-error "Invalid shift specification %s" shift)))))
  6954. (goto-char end-of-tree)
  6955. (unless (bolp) (insert "\n"))
  6956. (let* ((end (point))
  6957. (template (buffer-substring beg end))
  6958. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  6959. (shift-what (pcase (and doshift (match-string 2 shift))
  6960. (`nil nil)
  6961. ("d" 'day)
  6962. ("w" (setq shift-n (* 7 shift-n)) 'day)
  6963. ("m" 'month)
  6964. ("y" 'year)
  6965. (_ (error "Unsupported time unit"))))
  6966. (nmin 1)
  6967. (nmax n)
  6968. (n-no-remove -1)
  6969. (org-id-overriding-file-name (buffer-file-name (buffer-base-buffer)))
  6970. (idprop (org-entry-get beg "ID")))
  6971. (when (and doshift
  6972. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  6973. template))
  6974. (delete-region beg end)
  6975. (setq end beg)
  6976. (setq nmin 0)
  6977. (setq nmax (1+ nmax))
  6978. (setq n-no-remove nmax))
  6979. (goto-char end)
  6980. (cl-loop for n from nmin to nmax do
  6981. (insert
  6982. ;; Prepare clone.
  6983. (with-temp-buffer
  6984. (insert template)
  6985. (org-mode)
  6986. (goto-char (point-min))
  6987. (org-show-subtree)
  6988. (and idprop (if org-clone-delete-id
  6989. (org-entry-delete nil "ID")
  6990. (org-id-get-create t)))
  6991. (unless (= n 0)
  6992. (while (re-search-forward org-clock-line-re nil t)
  6993. (delete-region (line-beginning-position)
  6994. (line-beginning-position 2)))
  6995. (goto-char (point-min))
  6996. (while (re-search-forward org-drawer-regexp nil t)
  6997. (org-remove-empty-drawer-at (point))))
  6998. (goto-char (point-min))
  6999. (when doshift
  7000. (while (re-search-forward org-ts-regexp-both nil t)
  7001. (org-timestamp-change (* n shift-n) shift-what))
  7002. (unless (= n n-no-remove)
  7003. (goto-char (point-min))
  7004. (while (re-search-forward org-ts-regexp nil t)
  7005. (save-excursion
  7006. (goto-char (match-beginning 0))
  7007. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7008. (delete-region (match-beginning 1) (match-end 1)))))))
  7009. (buffer-string)))))
  7010. (goto-char beg)))
  7011. ;;; Outline path
  7012. (defvar org-outline-path-cache nil
  7013. "Alist between buffer positions and outline paths.
  7014. It value is an alist (POSITION . PATH) where POSITION is the
  7015. buffer position at the beginning of an entry and PATH is a list
  7016. of strings describing the outline path for that entry, in reverse
  7017. order.")
  7018. (defun org--get-outline-path-1 (&optional use-cache)
  7019. "Return outline path to current headline.
  7020. Outline path is a list of strings, in reverse order. When
  7021. optional argument USE-CACHE is non-nil, make use of a cache. See
  7022. `org-get-outline-path' for details.
  7023. Assume buffer is widened and point is on a headline."
  7024. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  7025. (let ((p (point))
  7026. (heading (let ((case-fold-search nil))
  7027. (looking-at org-complex-heading-regexp)
  7028. (if (not (match-end 4)) ""
  7029. ;; Remove statistics cookies.
  7030. (org-trim
  7031. (org-link-display-format
  7032. (replace-regexp-in-string
  7033. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  7034. (match-string-no-properties 4))))))))
  7035. (if (org-up-heading-safe)
  7036. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  7037. (when use-cache
  7038. (push (cons p path) org-outline-path-cache))
  7039. path)
  7040. ;; This is a new root node. Since we assume we are moving
  7041. ;; forward, we can drop previous cache so as to limit number
  7042. ;; of associations there.
  7043. (let ((path (list heading)))
  7044. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  7045. path)))))
  7046. (defun org-get-outline-path (&optional with-self use-cache)
  7047. "Return the outline path to the current entry.
  7048. An outline path is a list of ancestors for current headline, as
  7049. a list of strings. Statistics cookies are removed and links are
  7050. replaced with their description, if any, or their path otherwise.
  7051. When optional argument WITH-SELF is non-nil, the path also
  7052. includes the current headline.
  7053. When optional argument USE-CACHE is non-nil, cache outline paths
  7054. between calls to this function so as to avoid backtracking. This
  7055. argument is useful when planning to find more than one outline
  7056. path in the same document. In that case, there are two
  7057. conditions to satisfy:
  7058. - `org-outline-path-cache' is set to nil before starting the
  7059. process;
  7060. - outline paths are computed by increasing buffer positions."
  7061. (org-with-wide-buffer
  7062. (and (or (and with-self (org-back-to-heading t))
  7063. (org-up-heading-safe))
  7064. (reverse (org--get-outline-path-1 use-cache)))))
  7065. (defun org-format-outline-path (path &optional width prefix separator)
  7066. "Format the outline path PATH for display.
  7067. WIDTH is the maximum number of characters that is available.
  7068. PREFIX is a prefix to be included in the returned string,
  7069. such as the file name.
  7070. SEPARATOR is inserted between the different parts of the path,
  7071. the default is \"/\"."
  7072. (setq width (or width 79))
  7073. (setq path (delq nil path))
  7074. (unless (> width 0)
  7075. (user-error "Argument `width' must be positive"))
  7076. (setq separator (or separator "/"))
  7077. (let* ((org-odd-levels-only nil)
  7078. (fpath (concat
  7079. prefix (and prefix path separator)
  7080. (mapconcat
  7081. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  7082. (cl-loop for head in path
  7083. for n from 0
  7084. collect (org-add-props
  7085. head nil 'face
  7086. (nth (% n org-n-level-faces) org-level-faces)))
  7087. separator))))
  7088. (when (> (length fpath) width)
  7089. (if (< width 7)
  7090. ;; It's unlikely that `width' will be this small, but don't
  7091. ;; waste characters by adding ".." if it is.
  7092. (setq fpath (substring fpath 0 width))
  7093. (setf (substring fpath (- width 2)) "..")))
  7094. fpath))
  7095. (defun org-display-outline-path (&optional file current separator just-return-string)
  7096. "Display the current outline path in the echo area.
  7097. If FILE is non-nil, prepend the output with the file name.
  7098. If CURRENT is non-nil, append the current heading to the output.
  7099. SEPARATOR is passed through to `org-format-outline-path'. It separates
  7100. the different parts of the path and defaults to \"/\".
  7101. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  7102. (interactive "P")
  7103. (let* (case-fold-search
  7104. (bfn (buffer-file-name (buffer-base-buffer)))
  7105. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  7106. res)
  7107. (when current (setq path (append path
  7108. (save-excursion
  7109. (org-back-to-heading t)
  7110. (when (looking-at org-complex-heading-regexp)
  7111. (list (match-string 4)))))))
  7112. (setq res
  7113. (org-format-outline-path
  7114. path
  7115. (1- (frame-width))
  7116. (and file bfn (concat (file-name-nondirectory bfn) separator))
  7117. separator))
  7118. (if just-return-string
  7119. (org-no-properties res)
  7120. (org-unlogged-message "%s" res))))
  7121. ;;; Outline Sorting
  7122. (defun org-sort (&optional with-case)
  7123. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7124. Optional argument WITH-CASE means sort case-sensitively."
  7125. (interactive "P")
  7126. (org-call-with-arg
  7127. (cond ((org-at-table-p) #'org-table-sort-lines)
  7128. ((org-at-item-p) #'org-sort-list)
  7129. (t #'org-sort-entries))
  7130. with-case))
  7131. (defun org-sort-remove-invisible (s)
  7132. "Remove invisible part of links and emphasis markers from string S."
  7133. (remove-text-properties 0 (length s) org-rm-props s)
  7134. (replace-regexp-in-string
  7135. org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
  7136. (replace-regexp-in-string
  7137. org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
  7138. (org-link-display-format s)
  7139. t t) t t))
  7140. (defvar org-after-sorting-entries-or-items-hook nil
  7141. "Hook that is run after a bunch of entries or items have been sorted.
  7142. When children are sorted, the cursor is in the parent line when this
  7143. hook gets called. When a region or a plain list is sorted, the cursor
  7144. will be in the first entry of the sorted region/list.")
  7145. (defun org-sort-entries
  7146. (&optional with-case sorting-type getkey-func compare-func property
  7147. interactive?)
  7148. "Sort entries on a certain level of an outline tree.
  7149. If there is an active region, the entries in the region are sorted.
  7150. Else, if the cursor is before the first entry, sort the top-level items.
  7151. Else, the children of the entry at point are sorted.
  7152. Sorting can be alphabetically, numerically, by date/time as given by
  7153. a time stamp, by a property, by priority order, or by a custom function.
  7154. The command prompts for the sorting type unless it has been given to the
  7155. function through the SORTING-TYPE argument, which needs to be a character,
  7156. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7157. the precise meaning of each character:
  7158. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7159. c By creation time, which is assumed to be the first inactive time stamp
  7160. at the beginning of a line.
  7161. d By deadline date/time.
  7162. k By clocking time.
  7163. n Numerically, by converting the beginning of the entry/item to a number.
  7164. o By order of TODO keywords.
  7165. p By priority according to the cookie.
  7166. r By the value of a property.
  7167. s By scheduled date/time.
  7168. t By date/time, either the first active time stamp in the entry, or, if
  7169. none exist, by the first inactive one.
  7170. Capital letters will reverse the sort order.
  7171. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7172. called with point at the beginning of the record. It must return a
  7173. value that is compatible with COMPARE-FUNC, the function used to
  7174. compare entries.
  7175. Comparing entries ignores case by default. However, with an optional argument
  7176. WITH-CASE, the sorting considers case as well.
  7177. Sorting is done against the visible part of the headlines, it ignores hidden
  7178. links.
  7179. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  7180. A non-nil value for INTERACTIVE? is used to signal that this
  7181. function is being called interactively."
  7182. (interactive (list current-prefix-arg nil nil nil nil t))
  7183. (let ((case-func (if with-case 'identity 'downcase))
  7184. start beg end stars re re2
  7185. txt what tmp)
  7186. ;; Find beginning and end of region to sort
  7187. (cond
  7188. ((org-region-active-p)
  7189. ;; we will sort the region
  7190. (setq end (region-end)
  7191. what "region")
  7192. (goto-char (region-beginning))
  7193. (unless (org-at-heading-p) (outline-next-heading))
  7194. (setq start (point)))
  7195. ((or (org-at-heading-p)
  7196. (ignore-errors (progn (org-back-to-heading) t)))
  7197. ;; we will sort the children of the current headline
  7198. (org-back-to-heading)
  7199. (setq start (point)
  7200. end (progn (org-end-of-subtree t t)
  7201. (or (bolp) (insert "\n"))
  7202. (when (>= (org-back-over-empty-lines) 1)
  7203. (forward-line 1))
  7204. (point))
  7205. what "children")
  7206. (goto-char start)
  7207. (outline-show-subtree)
  7208. (outline-next-heading))
  7209. (t
  7210. ;; we will sort the top-level entries in this file
  7211. (goto-char (point-min))
  7212. (or (org-at-heading-p) (outline-next-heading))
  7213. (setq start (point))
  7214. (goto-char (point-max))
  7215. (beginning-of-line 1)
  7216. (when (looking-at ".*?\\S-")
  7217. ;; File ends in a non-white line
  7218. (end-of-line 1)
  7219. (insert "\n"))
  7220. (setq end (point-max))
  7221. (setq what "top-level")
  7222. (goto-char start)
  7223. (org-show-all '(headings blocks))))
  7224. (setq beg (point))
  7225. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7226. (looking-at "\\(\\*+\\)")
  7227. (setq stars (match-string 1)
  7228. re (concat "^" (regexp-quote stars) " +")
  7229. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7230. txt (buffer-substring beg end))
  7231. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7232. (when (and (not (equal stars "*")) (string-match re2 txt))
  7233. (user-error "Region to sort contains a level above the first entry"))
  7234. (unless sorting-type
  7235. (message
  7236. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7237. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7238. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7239. what)
  7240. (setq sorting-type (read-char-exclusive)))
  7241. (unless getkey-func
  7242. (and (= (downcase sorting-type) ?f)
  7243. (setq getkey-func
  7244. (or (and interactive?
  7245. (org-read-function
  7246. "Function for extracting keys: "))
  7247. (error "Missing key extractor")))))
  7248. (and (= (downcase sorting-type) ?r)
  7249. (not property)
  7250. (setq property
  7251. (completing-read "Property: "
  7252. (mapcar #'list (org-buffer-property-keys t))
  7253. nil t)))
  7254. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  7255. (message "Sorting entries...")
  7256. (save-restriction
  7257. (narrow-to-region start end)
  7258. (let ((restore-clock?
  7259. ;; The clock marker is lost when using `sort-subr'; mark
  7260. ;; the clock with temporary `:org-clock-marker-backup'
  7261. ;; text property.
  7262. (when (and (eq (org-clock-is-active) (current-buffer))
  7263. (<= start (marker-position org-clock-marker))
  7264. (>= end (marker-position org-clock-marker)))
  7265. (with-silent-modifications
  7266. (put-text-property (1- org-clock-marker) org-clock-marker
  7267. :org-clock-marker-backup t))
  7268. t))
  7269. (dcst (downcase sorting-type))
  7270. (case-fold-search nil)
  7271. (now (current-time)))
  7272. (org-preserve-local-variables
  7273. (sort-subr
  7274. (/= dcst sorting-type)
  7275. ;; This function moves to the beginning character of the
  7276. ;; "record" to be sorted.
  7277. (lambda nil
  7278. (if (re-search-forward re nil t)
  7279. (goto-char (match-beginning 0))
  7280. (goto-char (point-max))))
  7281. ;; This function moves to the last character of the "record" being
  7282. ;; sorted.
  7283. (lambda nil
  7284. (save-match-data
  7285. (condition-case nil
  7286. (outline-forward-same-level 1)
  7287. (error
  7288. (goto-char (point-max))))))
  7289. ;; This function returns the value that gets sorted against.
  7290. (lambda ()
  7291. (cond
  7292. ((= dcst ?n)
  7293. (string-to-number
  7294. (org-sort-remove-invisible (org-get-heading t t t t))))
  7295. ((= dcst ?a)
  7296. (funcall case-func
  7297. (org-sort-remove-invisible (org-get-heading t t t t))))
  7298. ((= dcst ?k)
  7299. (or (get-text-property (point) :org-clock-minutes) 0))
  7300. ((= dcst ?t)
  7301. (let ((end (save-excursion (outline-next-heading) (point))))
  7302. (if (or (re-search-forward org-ts-regexp end t)
  7303. (re-search-forward org-ts-regexp-both end t))
  7304. (org-time-string-to-seconds (match-string 0))
  7305. (float-time now))))
  7306. ((= dcst ?c)
  7307. (let ((end (save-excursion (outline-next-heading) (point))))
  7308. (if (re-search-forward
  7309. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  7310. end t)
  7311. (org-time-string-to-seconds (match-string 0))
  7312. (float-time now))))
  7313. ((= dcst ?s)
  7314. (let ((end (save-excursion (outline-next-heading) (point))))
  7315. (if (re-search-forward org-scheduled-time-regexp end t)
  7316. (org-time-string-to-seconds (match-string 1))
  7317. (float-time now))))
  7318. ((= dcst ?d)
  7319. (let ((end (save-excursion (outline-next-heading) (point))))
  7320. (if (re-search-forward org-deadline-time-regexp end t)
  7321. (org-time-string-to-seconds (match-string 1))
  7322. (float-time now))))
  7323. ((= dcst ?p)
  7324. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  7325. (string-to-char (match-string 2))
  7326. org-priority-default))
  7327. ((= dcst ?r)
  7328. (or (org-entry-get nil property) ""))
  7329. ((= dcst ?o)
  7330. (when (looking-at org-complex-heading-regexp)
  7331. (let* ((m (match-string 2))
  7332. (s (if (member m org-done-keywords) '- '+)))
  7333. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  7334. ((= dcst ?f)
  7335. (if getkey-func
  7336. (progn
  7337. (setq tmp (funcall getkey-func))
  7338. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  7339. tmp)
  7340. (error "Invalid key function `%s'" getkey-func)))
  7341. (t (error "Invalid sorting type `%c'" sorting-type))))
  7342. nil
  7343. (cond
  7344. ((= dcst ?a) 'org-string-collate-lessp)
  7345. ((= dcst ?f)
  7346. (or compare-func
  7347. (and interactive?
  7348. (org-read-function
  7349. (concat "Function for comparing keys "
  7350. "(empty for default `sort-subr' predicate): ")
  7351. 'allow-empty))))
  7352. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
  7353. (org-cycle-hide-drawers 'all)
  7354. (when restore-clock?
  7355. (move-marker org-clock-marker
  7356. (1+ (next-single-property-change
  7357. start :org-clock-marker-backup)))
  7358. (remove-text-properties (1- org-clock-marker) org-clock-marker
  7359. '(:org-clock-marker-backup t)))))
  7360. (run-hooks 'org-after-sorting-entries-or-items-hook)
  7361. (message "Sorting entries...done")))
  7362. (defun org-contextualize-keys (alist contexts)
  7363. "Return valid elements in ALIST depending on CONTEXTS.
  7364. `org-agenda-custom-commands' or `org-capture-templates' are the
  7365. values used for ALIST, and `org-agenda-custom-commands-contexts'
  7366. or `org-capture-templates-contexts' are the associated contexts
  7367. definitions."
  7368. (let ((contexts
  7369. ;; normalize contexts
  7370. (mapcar
  7371. (lambda(c) (cond ((listp (cadr c))
  7372. (list (car c) (car c) (nth 1 c)))
  7373. ((string= "" (cadr c))
  7374. (list (car c) (car c) (nth 2 c)))
  7375. (t c)))
  7376. contexts))
  7377. (a alist) r s)
  7378. ;; loop over all commands or templates
  7379. (dolist (c a)
  7380. (let (vrules repl)
  7381. (cond
  7382. ((not (assoc (car c) contexts))
  7383. (push c r))
  7384. ((and (assoc (car c) contexts)
  7385. (setq vrules (org-contextualize-validate-key
  7386. (car c) contexts)))
  7387. (mapc (lambda (vr)
  7388. (unless (equal (car vr) (cadr vr))
  7389. (setq repl vr)))
  7390. vrules)
  7391. (if (not repl) (push c r)
  7392. (push (cadr repl) s)
  7393. (push
  7394. (cons (car c)
  7395. (cdr (or (assoc (cadr repl) alist)
  7396. (error "Undefined key `%s' as contextual replacement for `%s'"
  7397. (cadr repl) (car c)))))
  7398. r))))))
  7399. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  7400. (delq
  7401. nil
  7402. (delete-dups
  7403. (mapcar (lambda (x)
  7404. (let ((tpl (car x)))
  7405. (unless (delq
  7406. nil
  7407. (mapcar (lambda (y)
  7408. (equal y tpl))
  7409. s))
  7410. x)))
  7411. (reverse r))))))
  7412. (defun org-contextualize-validate-key (key contexts)
  7413. "Check CONTEXTS for agenda or capture KEY."
  7414. (let (res)
  7415. (dolist (r contexts)
  7416. (dolist (rr (car (last r)))
  7417. (when
  7418. (and (equal key (car r))
  7419. (if (functionp rr) (funcall rr)
  7420. (or (and (eq (car rr) 'in-file)
  7421. (buffer-file-name)
  7422. (string-match (cdr rr) (buffer-file-name)))
  7423. (and (eq (car rr) 'in-mode)
  7424. (string-match (cdr rr) (symbol-name major-mode)))
  7425. (and (eq (car rr) 'in-buffer)
  7426. (string-match (cdr rr) (buffer-name)))
  7427. (when (and (eq (car rr) 'not-in-file)
  7428. (buffer-file-name))
  7429. (not (string-match (cdr rr) (buffer-file-name))))
  7430. (when (eq (car rr) 'not-in-mode)
  7431. (not (string-match (cdr rr) (symbol-name major-mode))))
  7432. (when (eq (car rr) 'not-in-buffer)
  7433. (not (string-match (cdr rr) (buffer-name)))))))
  7434. (push r res))))
  7435. (delete-dups (delq nil res))))
  7436. ;; Defined to provide a value for defcustom, since there is no
  7437. ;; string-collate-greaterp in Emacs.
  7438. (defun org-string-collate-greaterp (s1 s2)
  7439. "Return non-nil if S1 is greater than S2 in collation order."
  7440. (not (org-string-collate-lessp s1 s2)))
  7441. ;;;###autoload
  7442. (defun org-run-like-in-org-mode (cmd)
  7443. "Run a command, pretending that the current buffer is in Org mode.
  7444. This will temporarily bind local variables that are typically bound in
  7445. Org mode to the values they have in Org mode, and then interactively
  7446. call CMD."
  7447. (org-load-modules-maybe)
  7448. (let (binds)
  7449. (dolist (var (org-get-local-variables))
  7450. (when (or (not (boundp (car var)))
  7451. (eq (symbol-value (car var))
  7452. (default-value (car var))))
  7453. (push (list (car var) `(quote ,(cadr var))) binds)))
  7454. (eval `(let ,binds
  7455. (call-interactively (quote ,cmd))))))
  7456. (defun org-get-category (&optional pos force-refresh)
  7457. "Get the category applying to position POS."
  7458. (save-match-data
  7459. (when force-refresh (org-refresh-category-properties))
  7460. (let ((pos (or pos (point))))
  7461. (or (get-text-property pos 'org-category)
  7462. (progn (org-refresh-category-properties)
  7463. (get-text-property pos 'org-category))))))
  7464. ;;; Refresh properties
  7465. (defun org-refresh-properties (dprop tprop)
  7466. "Refresh buffer text properties.
  7467. DPROP is the drawer property and TPROP is either the
  7468. corresponding text property to set, or an alist with each element
  7469. being a text property (as a symbol) and a function to apply to
  7470. the value of the drawer property."
  7471. (let* ((case-fold-search t)
  7472. (inhibit-read-only t)
  7473. (inherit? (org-property-inherit-p dprop))
  7474. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  7475. (global-or-keyword (and inherit?
  7476. (org--property-global-or-keyword-value dprop nil))))
  7477. (with-silent-modifications
  7478. (org-with-point-at 1
  7479. ;; Set global and keyword based values to the whole buffer.
  7480. (when global-or-keyword
  7481. (put-text-property (point-min) (point-max) tprop global-or-keyword))
  7482. ;; Set values based on property-drawers throughout the document.
  7483. (while (re-search-forward property-re nil t)
  7484. (when (org-at-property-p)
  7485. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  7486. (outline-next-heading))))))
  7487. (defun org-refresh-property (tprop p &optional inherit)
  7488. "Refresh the buffer text property TPROP from the drawer property P.
  7489. The refresh happens only for the current entry, or the whole
  7490. sub-tree if optional argument INHERIT is non-nil.
  7491. If point is before first headline, the function applies to the
  7492. part before the first headline. In that particular case, when
  7493. optional argument INHERIT is non-nil, it refreshes properties for
  7494. the whole buffer."
  7495. (save-excursion
  7496. (org-back-to-heading-or-point-min t)
  7497. (let ((start (point))
  7498. (end (save-excursion
  7499. (cond ((and inherit (org-before-first-heading-p))
  7500. (point-max))
  7501. (inherit
  7502. (org-end-of-subtree t t))
  7503. ((outline-next-heading))
  7504. ((point-max))))))
  7505. (if (symbolp tprop)
  7506. ;; TPROP is a text property symbol.
  7507. (put-text-property start end tprop p)
  7508. ;; TPROP is an alist with (property . function) elements.
  7509. (pcase-dolist (`(,prop . ,f) tprop)
  7510. (put-text-property start end prop (funcall f p)))))))
  7511. (defun org-refresh-category-properties ()
  7512. "Refresh category text properties in the buffer."
  7513. (let ((case-fold-search t)
  7514. (inhibit-read-only t)
  7515. (default-category
  7516. (cond ((null org-category)
  7517. (if buffer-file-name
  7518. (file-name-sans-extension
  7519. (file-name-nondirectory buffer-file-name))
  7520. "???"))
  7521. ((symbolp org-category) (symbol-name org-category))
  7522. (t org-category))))
  7523. (with-silent-modifications
  7524. (org-with-wide-buffer
  7525. ;; Set buffer-wide property from keyword. Search last #+CATEGORY
  7526. ;; keyword. If none is found, fall-back to `org-category' or
  7527. ;; buffer file name, or set it by the document property drawer.
  7528. (put-text-property
  7529. (point-min) (point-max)
  7530. 'org-category
  7531. (catch 'buffer-category
  7532. (goto-char (point-max))
  7533. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  7534. (let ((element (org-element-at-point)))
  7535. (when (eq (org-element-type element) 'keyword)
  7536. (throw 'buffer-category
  7537. (org-element-property :value element)))))
  7538. default-category))
  7539. ;; Set categories from the document property drawer or
  7540. ;; property drawers in the outline. If category is found in
  7541. ;; the property drawer for the whole buffer that value
  7542. ;; overrides the keyword-based value set above.
  7543. (goto-char (point-min))
  7544. (let ((regexp (org-re-property "CATEGORY")))
  7545. (while (re-search-forward regexp nil t)
  7546. (let ((value (match-string-no-properties 3)))
  7547. (when (org-at-property-p)
  7548. (put-text-property
  7549. (save-excursion (org-back-to-heading-or-point-min t))
  7550. (save-excursion (if (org-before-first-heading-p)
  7551. (point-max)
  7552. (org-end-of-subtree t t)))
  7553. 'org-category
  7554. value)))))))))
  7555. (defun org-refresh-stats-properties ()
  7556. "Refresh stats text properties in the buffer."
  7557. (with-silent-modifications
  7558. (org-with-point-at 1
  7559. (let ((regexp (concat org-outline-regexp-bol
  7560. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  7561. (while (re-search-forward regexp nil t)
  7562. (let* ((numerator (string-to-number (match-string 1)))
  7563. (denominator (and (match-end 2)
  7564. (string-to-number (match-string 2))))
  7565. (stats (cond ((not denominator) numerator) ;percent
  7566. ((= denominator 0) 0)
  7567. (t (/ (* numerator 100) denominator)))))
  7568. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  7569. 'org-stats stats)))))))
  7570. (defun org-refresh-effort-properties ()
  7571. "Refresh effort properties."
  7572. (org-refresh-properties
  7573. org-effort-property
  7574. '((effort . identity)
  7575. (effort-minutes . org-duration-to-minutes))))
  7576. (defun org-find-file-at-mouse (ev)
  7577. "Open file link or URL at mouse."
  7578. (interactive "e")
  7579. (mouse-set-point ev)
  7580. (org-open-at-point 'in-emacs))
  7581. (defun org-open-at-mouse (ev)
  7582. "Open file link or URL at mouse.
  7583. See the docstring of `org-open-file' for details."
  7584. (interactive "e")
  7585. (mouse-set-point ev)
  7586. (when (eq major-mode 'org-agenda-mode)
  7587. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  7588. (org-open-at-point))
  7589. (defvar org-window-config-before-follow-link nil
  7590. "The window configuration before following a link.
  7591. This is saved in case the need arises to restore it.")
  7592. (defun org--file-default-apps ()
  7593. "Return the default applications for this operating system."
  7594. (pcase system-type
  7595. (`darwin org-file-apps-macos)
  7596. (`windows-nt org-file-apps-windowsnt)
  7597. (_ org-file-apps-gnu)))
  7598. (defun org--file-apps-entry-dlink-p (entry)
  7599. "Non-nil if ENTRY should be matched against the link by `org-open-file'.
  7600. It assumes that is the case when the entry uses a regular
  7601. expression which has at least one grouping construct and the
  7602. action is either a Lisp form or a command string containing
  7603. \"%1\", i.e., using at least one subexpression match as
  7604. a parameter."
  7605. (pcase entry
  7606. (`(,selector . ,action)
  7607. (and (stringp selector)
  7608. (> (regexp-opt-depth selector) 0)
  7609. (or (and (stringp action)
  7610. (string-match "%[0-9]" action))
  7611. (consp action))))
  7612. (_ nil)))
  7613. (defun org--file-apps-regexp-alist (list &optional add-auto-mode)
  7614. "Convert extensions to regular expressions in the cars of LIST.
  7615. Also, weed out any non-string entries, because the return value
  7616. is used only for regexp matching.
  7617. When ADD-AUTO-MODE is non-nil, make all matches in `auto-mode-alist'
  7618. point to the symbol `emacs', indicating that the file should be
  7619. opened in Emacs."
  7620. (append
  7621. (delq nil
  7622. (mapcar (lambda (x)
  7623. (unless (not (stringp (car x)))
  7624. (if (string-match "\\W" (car x))
  7625. x
  7626. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  7627. list))
  7628. (when add-auto-mode
  7629. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  7630. ;;;###autoload
  7631. (defun org-open-file (path &optional in-emacs line search)
  7632. "Open the file at PATH.
  7633. First, this expands any special file name abbreviations. Then the
  7634. configuration variable `org-file-apps' is checked if it contains an
  7635. entry for this file type, and if yes, the corresponding command is launched.
  7636. If no application is found, Emacs simply visits the file.
  7637. With optional prefix argument IN-EMACS, Emacs will visit the file.
  7638. With a double \\[universal-argument] \\[universal-argument] \
  7639. prefix arg, Org tries to avoid opening in Emacs
  7640. and to use an external application to visit the file.
  7641. Optional LINE specifies a line to go to, optional SEARCH a string
  7642. to search for. If LINE or SEARCH is given, the file will be
  7643. opened in Emacs, unless an entry from `org-file-apps' that makes
  7644. use of groups in a regexp matches.
  7645. If you want to change the way frames are used when following a
  7646. link, please customize `org-link-frame-setup'.
  7647. If the file does not exist, throw an error."
  7648. (let* ((file (if (equal path "") buffer-file-name
  7649. (substitute-in-file-name (expand-file-name path))))
  7650. (file-apps (append org-file-apps (org--file-default-apps)))
  7651. (apps (cl-remove-if #'org--file-apps-entry-dlink-p file-apps))
  7652. (apps-dlink (cl-remove-if-not #'org--file-apps-entry-dlink-p
  7653. file-apps))
  7654. (remp (and (assq 'remote apps) (file-remote-p file)))
  7655. (dirp (unless remp (file-directory-p file)))
  7656. (file (if (and dirp org-open-directory-means-index-dot-org)
  7657. (concat (file-name-as-directory file) "index.org")
  7658. file))
  7659. (a-m-a-p (assq 'auto-mode apps))
  7660. (dfile (downcase file))
  7661. ;; Reconstruct the original link from the PATH, LINE and
  7662. ;; SEARCH args.
  7663. (link (cond (line (concat file "::" (number-to-string line)))
  7664. (search (concat file "::" search))
  7665. (t file)))
  7666. (dlink (downcase link))
  7667. (ext
  7668. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  7669. (match-string 1 dfile)))
  7670. (save-position-maybe
  7671. (let ((old-buffer (current-buffer))
  7672. (old-pos (point))
  7673. (old-mode major-mode))
  7674. (lambda ()
  7675. (and (derived-mode-p 'org-mode)
  7676. (eq old-mode 'org-mode)
  7677. (or (not (eq old-buffer (current-buffer)))
  7678. (not (eq old-pos (point))))
  7679. (org-mark-ring-push old-pos old-buffer)))))
  7680. cmd link-match-data)
  7681. (cond
  7682. ((member in-emacs '((16) system))
  7683. (setq cmd (cdr (assq 'system apps))))
  7684. (in-emacs (setq cmd 'emacs))
  7685. (t
  7686. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  7687. (and dirp (cdr (assq 'directory apps)))
  7688. ;; First, try matching against apps-dlink if we
  7689. ;; get a match here, store the match data for
  7690. ;; later.
  7691. (let ((match (assoc-default dlink apps-dlink
  7692. 'string-match)))
  7693. (if match
  7694. (progn (setq link-match-data (match-data))
  7695. match)
  7696. (progn (setq in-emacs (or in-emacs line search))
  7697. nil))) ; if we have no match in apps-dlink,
  7698. ; always open the file in emacs if line or search
  7699. ; is given (for backwards compatibility)
  7700. (assoc-default dfile
  7701. (org--file-apps-regexp-alist apps a-m-a-p)
  7702. 'string-match)
  7703. (cdr (assoc ext apps))
  7704. (cdr (assq t apps))))))
  7705. (when (eq cmd 'system)
  7706. (setq cmd (cdr (assq 'system apps))))
  7707. (when (eq cmd 'default)
  7708. (setq cmd (cdr (assoc t apps))))
  7709. (when (eq cmd 'mailcap)
  7710. (require 'mailcap)
  7711. (mailcap-parse-mailcaps)
  7712. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  7713. (command (mailcap-mime-info mime-type)))
  7714. (if (stringp command)
  7715. (setq cmd command)
  7716. (setq cmd 'emacs))))
  7717. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  7718. (not (file-exists-p file))
  7719. (not org-open-non-existing-files))
  7720. (user-error "No such file: %s" file))
  7721. (cond
  7722. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  7723. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  7724. (while (string-match "['\"]%s['\"]" cmd)
  7725. (setq cmd (replace-match "%s" t t cmd)))
  7726. (setq cmd (replace-regexp-in-string
  7727. "%s"
  7728. (shell-quote-argument (convert-standard-filename file))
  7729. cmd
  7730. nil t))
  7731. ;; Replace "%1", "%2" etc. in command with group matches from regex
  7732. (save-match-data
  7733. (let ((match-index 1)
  7734. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  7735. (set-match-data link-match-data)
  7736. (while (<= match-index number-of-groups)
  7737. (let ((regex (concat "%" (number-to-string match-index)))
  7738. (replace-with (match-string match-index dlink)))
  7739. (while (string-match regex cmd)
  7740. (setq cmd (replace-match replace-with t t cmd))))
  7741. (setq match-index (+ match-index 1)))))
  7742. (save-window-excursion
  7743. (message "Running %s...done" cmd)
  7744. (start-process-shell-command cmd nil cmd)
  7745. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  7746. ((or (stringp cmd)
  7747. (eq cmd 'emacs))
  7748. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  7749. (widen)
  7750. (cond (line (org-goto-line line)
  7751. (when (derived-mode-p 'org-mode) (org-reveal)))
  7752. (search (condition-case err
  7753. (org-link-search search)
  7754. ;; Save position before error-ing out so user
  7755. ;; can easily move back to the original buffer.
  7756. (error (funcall save-position-maybe)
  7757. (error (nth 1 err)))))))
  7758. ((functionp cmd)
  7759. (save-match-data
  7760. (set-match-data link-match-data)
  7761. (condition-case nil
  7762. (funcall cmd file link)
  7763. ;; FIXME: Remove this check when most default installations
  7764. ;; of Emacs have at least Org 9.0.
  7765. ((debug wrong-number-of-arguments wrong-type-argument
  7766. invalid-function)
  7767. (user-error "Please see Org News for version 9.0 about \
  7768. `org-file-apps'--Lisp error: %S" cmd)))))
  7769. ((consp cmd)
  7770. ;; FIXME: Remove this check when most default installations of
  7771. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  7772. ;; fall back to `org-link-frame-setup' for an old usage of
  7773. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  7774. (user-error "Please see Org News for version 9.0 about \
  7775. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  7776. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  7777. (funcall save-position-maybe)))
  7778. ;;;###autoload
  7779. (defun org-open-at-point-global ()
  7780. "Follow a link or a time-stamp like Org mode does.
  7781. Also follow links and emails as seen by `thing-at-point'.
  7782. This command can be called in any mode to follow an external
  7783. link or a time-stamp that has Org mode syntax. Its behavior
  7784. is undefined when called on internal links like fuzzy links.
  7785. Raise a user error when there is nothing to follow."
  7786. (interactive)
  7787. (let ((tap-url (thing-at-point 'url))
  7788. (tap-email (thing-at-point 'email)))
  7789. (cond ((org-in-regexp org-link-any-re)
  7790. (org-link-open-from-string (match-string-no-properties 0)))
  7791. ((or (org-in-regexp org-ts-regexp-both nil t)
  7792. (org-in-regexp org-tsr-regexp-both nil t))
  7793. (org-follow-timestamp-link))
  7794. (tap-url (org-link-open-from-string tap-url))
  7795. (tap-email (org-link-open-from-string
  7796. (concat "mailto:" tap-email)))
  7797. (t (user-error "No link found")))))
  7798. (defvar org-open-at-point-functions nil
  7799. "Hook that is run when following a link at point.
  7800. Functions in this hook must return t if they identify and follow
  7801. a link at point. If they don't find anything interesting at point,
  7802. they must return nil.")
  7803. (defun org-open-at-point (&optional arg)
  7804. "Open link, timestamp, footnote or tags at point.
  7805. When point is on a link, follow it. Normally, files will be
  7806. opened by an appropriate application. If the optional prefix
  7807. argument ARG is non-nil, Emacs will visit the file. With
  7808. a double prefix argument, try to open outside of Emacs, in the
  7809. application the system uses for this file type.
  7810. When point is on a timestamp, open the agenda at the day
  7811. specified.
  7812. When point is a footnote definition, move to the first reference
  7813. found. If it is on a reference, move to the associated
  7814. definition.
  7815. When point is on a headline, display a list of every link in the
  7816. entry, so it is possible to pick one, or all, of them. If point
  7817. is on a tag, call `org-tags-view' instead.
  7818. On top of syntactically correct links, this function also tries
  7819. to open links and time-stamps in comments, node properties, and
  7820. keywords if point is on something looking like a timestamp or
  7821. a link."
  7822. (interactive "P")
  7823. (org-load-modules-maybe)
  7824. (setq org-window-config-before-follow-link (current-window-configuration))
  7825. (org-remove-occur-highlights nil nil t)
  7826. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  7827. (let* ((context
  7828. ;; Only consider supported types, even if they are not the
  7829. ;; closest one.
  7830. (org-element-lineage
  7831. (org-element-context)
  7832. '(clock comment comment-block footnote-definition
  7833. footnote-reference headline inline-src-block inlinetask
  7834. keyword link node-property planning src-block timestamp)
  7835. t))
  7836. (type (org-element-type context))
  7837. (value (org-element-property :value context)))
  7838. (cond
  7839. ((not type) (user-error "No link found"))
  7840. ;; No valid link at point. For convenience, look if something
  7841. ;; looks like a link under point in some specific places.
  7842. ((memq type '(comment comment-block node-property keyword))
  7843. (call-interactively #'org-open-at-point-global))
  7844. ;; On a headline or an inlinetask, but not on a timestamp,
  7845. ;; a link, a footnote reference.
  7846. ((memq type '(headline inlinetask))
  7847. (org-match-line org-complex-heading-regexp)
  7848. (let ((tags-beg (match-beginning 5))
  7849. (tags-end (match-end 5)))
  7850. (if (and tags-beg (>= (point) tags-beg) (< (point) tags-end))
  7851. ;; On tags.
  7852. (org-tags-view
  7853. arg
  7854. (save-excursion
  7855. (let* ((beg-tag (or (search-backward ":" tags-beg 'at-limit) (point)))
  7856. (end-tag (search-forward ":" tags-end nil 2)))
  7857. (buffer-substring (1+ beg-tag) (1- end-tag)))))
  7858. ;; Not on tags.
  7859. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  7860. (`(nil . ,_)
  7861. (require 'org-attach)
  7862. (when (org-attach-dir)
  7863. (message "Opening attachment")
  7864. (if (equal arg '(4))
  7865. (org-attach-reveal-in-emacs)
  7866. (org-attach-reveal))))
  7867. (`(,links . ,links-end)
  7868. (dolist (link (if (stringp links) (list links) links))
  7869. (search-forward link nil links-end)
  7870. (goto-char (match-beginning 0))
  7871. (org-open-at-point arg)))))))
  7872. ;; On a footnote reference or at definition's label.
  7873. ((or (eq type 'footnote-reference)
  7874. (and (eq type 'footnote-definition)
  7875. (save-excursion
  7876. ;; Do not validate action when point is on the
  7877. ;; spaces right after the footnote label, in order
  7878. ;; to be on par with behavior on links.
  7879. (skip-chars-forward " \t")
  7880. (let ((begin
  7881. (org-element-property :contents-begin context)))
  7882. (if begin (< (point) begin)
  7883. (= (org-element-property :post-affiliated context)
  7884. (line-beginning-position)))))))
  7885. (org-footnote-action))
  7886. ;; On a planning line. Check if we are really on a timestamp.
  7887. ((and (eq type 'planning)
  7888. (org-in-regexp org-ts-regexp-both nil t))
  7889. (org-follow-timestamp-link))
  7890. ;; On a clock line, make sure point is on the timestamp
  7891. ;; before opening it.
  7892. ((and (eq type 'clock)
  7893. value
  7894. (>= (point) (org-element-property :begin value))
  7895. (<= (point) (org-element-property :end value)))
  7896. (org-follow-timestamp-link))
  7897. ((eq type 'src-block) (org-babel-open-src-block-result))
  7898. ;; Do nothing on white spaces after an object.
  7899. ((>= (point)
  7900. (save-excursion
  7901. (goto-char (org-element-property :end context))
  7902. (skip-chars-backward " \t")
  7903. (point)))
  7904. (user-error "No link found"))
  7905. ((eq type 'inline-src-block) (org-babel-open-src-block-result))
  7906. ((eq type 'timestamp) (org-follow-timestamp-link))
  7907. ((eq type 'link) (org-link-open context arg))
  7908. (t (user-error "No link found")))))
  7909. (run-hook-with-args 'org-follow-link-hook))
  7910. ;;;###autoload
  7911. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  7912. "Offer links in the current entry and return the selected link.
  7913. If there is only one link, return it.
  7914. If NTH is an integer, return the NTH link found.
  7915. If ZERO is a string, check also this string for a link, and if
  7916. there is one, return it."
  7917. (with-current-buffer buffer
  7918. (org-with-wide-buffer
  7919. (goto-char marker)
  7920. (let ((cnt ?0)
  7921. have-zero end links link c)
  7922. (when (and (stringp zero) (string-match org-link-bracket-re zero))
  7923. (push (match-string 0 zero) links)
  7924. (setq cnt (1- cnt) have-zero t))
  7925. (save-excursion
  7926. (org-back-to-heading t)
  7927. (setq end (save-excursion (outline-next-heading) (point)))
  7928. (while (re-search-forward org-link-any-re end t)
  7929. (push (match-string 0) links))
  7930. (setq links (org-uniquify (reverse links))))
  7931. (cond
  7932. ((null links)
  7933. (message "No links"))
  7934. ((equal (length links) 1)
  7935. (setq link (car links)))
  7936. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  7937. (setq link (nth (if have-zero nth (1- nth)) links)))
  7938. (t ; we have to select a link
  7939. (save-excursion
  7940. (save-window-excursion
  7941. (delete-other-windows)
  7942. (with-output-to-temp-buffer "*Select Link*"
  7943. (dolist (l links)
  7944. (cond
  7945. ((not (string-match org-link-bracket-re l))
  7946. (princ (format "[%c] %s\n" (cl-incf cnt)
  7947. (org-unbracket-string "<" ">" l))))
  7948. ((match-end 2)
  7949. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  7950. (match-string 2 l) (match-string 1 l))))
  7951. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  7952. (match-string 1 l)))))))
  7953. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  7954. (message "Select link to open, RET to open all:")
  7955. (setq c (read-char-exclusive))
  7956. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  7957. (when (equal c ?q) (user-error "Abort"))
  7958. (if (equal c ?\C-m)
  7959. (setq link links)
  7960. (setq nth (- c ?0))
  7961. (when have-zero (setq nth (1+ nth)))
  7962. (unless (and (integerp nth) (>= (length links) nth))
  7963. (user-error "Invalid link selection"))
  7964. (setq link (nth (1- nth) links)))))
  7965. (cons link end)))))
  7966. ;;; File search
  7967. (defun org-do-occur (regexp &optional cleanup)
  7968. "Call the Emacs command `occur'.
  7969. If CLEANUP is non-nil, remove the printout of the regular expression
  7970. in the *Occur* buffer. This is useful if the regex is long and not useful
  7971. to read."
  7972. (occur regexp)
  7973. (when cleanup
  7974. (let ((cwin (selected-window)) win beg end)
  7975. (when (setq win (get-buffer-window "*Occur*"))
  7976. (select-window win))
  7977. (goto-char (point-min))
  7978. (when (re-search-forward "match[a-z]+" nil t)
  7979. (setq beg (match-end 0))
  7980. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  7981. (setq end (1- (match-beginning 0)))))
  7982. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  7983. (goto-char (point-min))
  7984. (select-window cwin))))
  7985. ;;; The Mark Ring
  7986. (defvar org-mark-ring nil
  7987. "Mark ring for positions before jumps in Org mode.")
  7988. (defvar org-mark-ring-last-goto nil
  7989. "Last position in the mark ring used to go back.")
  7990. ;; Fill and close the ring
  7991. (setq org-mark-ring nil)
  7992. (setq org-mark-ring-last-goto nil) ;in case file is reloaded
  7993. (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
  7994. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  7995. org-mark-ring)
  7996. (defun org-mark-ring-push (&optional pos buffer)
  7997. "Put the current position into the mark ring and rotate it.
  7998. Also push position into the Emacs mark ring. If optional
  7999. argument POS and BUFFER are not nil, mark this location instead."
  8000. (interactive)
  8001. (let ((pos (or pos (point)))
  8002. (buffer (or buffer (current-buffer))))
  8003. (with-current-buffer buffer
  8004. (org-with-point-at pos (push-mark nil t)))
  8005. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  8006. (move-marker (car org-mark-ring) pos buffer))
  8007. (message
  8008. (substitute-command-keys
  8009. "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
  8010. (defun org-mark-ring-goto (&optional n)
  8011. "Jump to the previous position in the mark ring.
  8012. With prefix arg N, jump back that many stored positions. When
  8013. called several times in succession, walk through the entire ring.
  8014. Org mode commands jumping to a different position in the current file,
  8015. or to another Org file, automatically push the old position onto the ring."
  8016. (interactive "p")
  8017. (let (p m)
  8018. (if (eq last-command this-command)
  8019. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  8020. (setq p org-mark-ring))
  8021. (setq org-mark-ring-last-goto p)
  8022. (setq m (car p))
  8023. (pop-to-buffer-same-window (marker-buffer m))
  8024. (goto-char m)
  8025. (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  8026. ;;; Following specific links
  8027. (defvar org-agenda-buffer-tmp-name)
  8028. (defvar org-agenda-start-on-weekday)
  8029. (defun org-follow-timestamp-link ()
  8030. "Open an agenda view for the time-stamp date/range at point."
  8031. (cond
  8032. ((org-at-date-range-p t)
  8033. (let ((org-agenda-start-on-weekday)
  8034. (t1 (match-string 1))
  8035. (t2 (match-string 2)) tt1 tt2)
  8036. (setq tt1 (time-to-days (org-time-string-to-time t1))
  8037. tt2 (time-to-days (org-time-string-to-time t2)))
  8038. (let ((org-agenda-buffer-tmp-name
  8039. (format "*Org Agenda(a:%s)"
  8040. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  8041. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  8042. ((org-at-timestamp-p 'lax)
  8043. (let ((org-agenda-buffer-tmp-name
  8044. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  8045. (org-agenda-list nil (time-to-days (org-time-string-to-time
  8046. (substring (match-string 1) 0 10)))
  8047. 1)))
  8048. (t (error "This should not happen"))))
  8049. ;;; Following file links
  8050. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  8051. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  8052. (declare-function mailcap-mime-info
  8053. "mailcap" (string &optional request no-decode))
  8054. (defvar org-wait nil)
  8055. ;;;; Refiling
  8056. (defun org-get-org-file ()
  8057. "Read a filename, with default directory `org-directory'."
  8058. (let ((default (or org-default-notes-file remember-data-file)))
  8059. (read-file-name (format "File name [%s]: " default)
  8060. (file-name-as-directory org-directory)
  8061. default)))
  8062. (defun org-notes-order-reversed-p ()
  8063. "Check if the current file should receive notes in reversed order."
  8064. (cond
  8065. ((not org-reverse-note-order) nil)
  8066. ((eq t org-reverse-note-order) t)
  8067. ((not (listp org-reverse-note-order)) nil)
  8068. (t (catch 'exit
  8069. (dolist (entry org-reverse-note-order)
  8070. (when (string-match (car entry) buffer-file-name)
  8071. (throw 'exit (cdr entry))))))))
  8072. (defvar org-agenda-new-buffers nil
  8073. "Buffers created to visit agenda files.")
  8074. (declare-function org-string-nw-p "org-macs" (s))
  8075. ;;;; Dynamic blocks
  8076. (defun org-find-dblock (name)
  8077. "Find the first dynamic block with name NAME in the buffer.
  8078. If not found, stay at current position and return nil."
  8079. (let ((case-fold-search t) pos)
  8080. (save-excursion
  8081. (goto-char (point-min))
  8082. (setq pos (and (re-search-forward
  8083. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  8084. (match-beginning 0))))
  8085. (when pos (goto-char pos))
  8086. pos))
  8087. (defun org-create-dblock (plist)
  8088. "Create a dynamic block section, with parameters taken from PLIST.
  8089. PLIST must contain a :name entry which is used as the name of the block."
  8090. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  8091. (end-of-line 1)
  8092. (newline))
  8093. (let ((col (current-column))
  8094. (name (plist-get plist :name)))
  8095. (insert "#+BEGIN: " name)
  8096. (while plist
  8097. (if (eq (car plist) :name)
  8098. (setq plist (cddr plist))
  8099. (insert " " (prin1-to-string (pop plist)))))
  8100. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  8101. (beginning-of-line -2)))
  8102. (defun org-prepare-dblock ()
  8103. "Prepare dynamic block for refresh.
  8104. This empties the block, puts the cursor at the insert position and returns
  8105. the property list including an extra property :name with the block name."
  8106. (unless (looking-at org-dblock-start-re)
  8107. (user-error "Not at a dynamic block"))
  8108. (let* ((begdel (1+ (match-end 0)))
  8109. (name (org-no-properties (match-string 1)))
  8110. (params (append (list :name name)
  8111. (read (concat "(" (match-string 3) ")")))))
  8112. (save-excursion
  8113. (beginning-of-line 1)
  8114. (skip-chars-forward " \t")
  8115. (setq params (plist-put params :indentation-column (current-column))))
  8116. (unless (re-search-forward org-dblock-end-re nil t)
  8117. (error "Dynamic block not terminated"))
  8118. (setq params
  8119. (append params
  8120. (list :content (buffer-substring
  8121. begdel (match-beginning 0)))))
  8122. (delete-region begdel (match-beginning 0))
  8123. (goto-char begdel)
  8124. (open-line 1)
  8125. params))
  8126. (defun org-map-dblocks (&optional command)
  8127. "Apply COMMAND to all dynamic blocks in the current buffer.
  8128. If COMMAND is not given, use `org-update-dblock'."
  8129. (let ((cmd (or command 'org-update-dblock)))
  8130. (save-excursion
  8131. (goto-char (point-min))
  8132. (while (re-search-forward org-dblock-start-re nil t)
  8133. (goto-char (match-beginning 0))
  8134. (save-excursion
  8135. (condition-case nil
  8136. (funcall cmd)
  8137. (error (message "Error during update of dynamic block"))))
  8138. (unless (re-search-forward org-dblock-end-re nil t)
  8139. (error "Dynamic block not terminated"))))))
  8140. (defvar org-dynamic-block-alist nil
  8141. "Alist defining all the Org dynamic blocks.
  8142. The key is the dynamic block type name, as a string. The value
  8143. is the function used to insert the dynamic block.
  8144. Use `org-dynamic-block-define' to populate it.")
  8145. (defun org-dynamic-block-function (type)
  8146. "Return function associated to a given dynamic block type.
  8147. TYPE is the dynamic block type, as a string."
  8148. (cdr (assoc type org-dynamic-block-alist)))
  8149. (defun org-dynamic-block-types ()
  8150. "List all defined dynamic block types."
  8151. (mapcar #'car org-dynamic-block-alist))
  8152. (defun org-dynamic-block-define (type func)
  8153. "Define dynamic block TYPE with FUNC.
  8154. TYPE is a string. FUNC is the function creating the dynamic
  8155. block of such type."
  8156. (pcase (assoc type org-dynamic-block-alist)
  8157. (`nil (push (cons type func) org-dynamic-block-alist))
  8158. (def (setcdr def func))))
  8159. (defun org-dynamic-block-insert-dblock (type)
  8160. "Insert a dynamic block of type TYPE.
  8161. When used interactively, select the dynamic block types among
  8162. defined types, per `org-dynamic-block-define'."
  8163. (interactive (list (completing-read "Dynamic block: "
  8164. (org-dynamic-block-types))))
  8165. (pcase (org-dynamic-block-function type)
  8166. (`nil (error "No such dynamic block: %S" type))
  8167. ((and f (pred functionp)) (funcall f))
  8168. (_ (error "Invalid function for dynamic block %S" type))))
  8169. (defun org-dblock-update (&optional arg)
  8170. "User command for updating dynamic blocks.
  8171. Update the dynamic block at point. With prefix ARG, update all dynamic
  8172. blocks in the buffer."
  8173. (interactive "P")
  8174. (if arg
  8175. (org-update-all-dblocks)
  8176. (or (looking-at org-dblock-start-re)
  8177. (org-beginning-of-dblock))
  8178. (org-update-dblock)))
  8179. (defun org-update-dblock ()
  8180. "Update the dynamic block at point.
  8181. This means to empty the block, parse for parameters and then call
  8182. the correct writing function."
  8183. (interactive)
  8184. (save-excursion
  8185. (let* ((win (selected-window))
  8186. (pos (point))
  8187. (line (org-current-line))
  8188. (params (org-prepare-dblock))
  8189. (name (plist-get params :name))
  8190. (indent (plist-get params :indentation-column))
  8191. (cmd (intern (concat "org-dblock-write:" name))))
  8192. (message "Updating dynamic block `%s' at line %d..." name line)
  8193. (funcall cmd params)
  8194. (message "Updating dynamic block `%s' at line %d...done" name line)
  8195. (goto-char pos)
  8196. (when (and indent (> indent 0))
  8197. (setq indent (make-string indent ?\ ))
  8198. (save-excursion
  8199. (select-window win)
  8200. (org-beginning-of-dblock)
  8201. (forward-line 1)
  8202. (while (not (looking-at org-dblock-end-re))
  8203. (insert indent)
  8204. (beginning-of-line 2))
  8205. (when (looking-at org-dblock-end-re)
  8206. (and (looking-at "[ \t]+")
  8207. (replace-match ""))
  8208. (insert indent)))))))
  8209. (defun org-beginning-of-dblock ()
  8210. "Find the beginning of the dynamic block at point.
  8211. Error if there is no such block at point."
  8212. (let ((pos (point))
  8213. beg)
  8214. (end-of-line 1)
  8215. (if (and (re-search-backward org-dblock-start-re nil t)
  8216. (setq beg (match-beginning 0))
  8217. (re-search-forward org-dblock-end-re nil t)
  8218. (> (match-end 0) pos))
  8219. (goto-char beg)
  8220. (goto-char pos)
  8221. (error "Not in a dynamic block"))))
  8222. (defun org-update-all-dblocks ()
  8223. "Update all dynamic blocks in the buffer.
  8224. This function can be used in a hook."
  8225. (interactive)
  8226. (when (derived-mode-p 'org-mode)
  8227. (org-map-dblocks 'org-update-dblock)))
  8228. ;;;; Completion
  8229. (declare-function org-export-backend-options "ox" (cl-x) t)
  8230. (defun org-get-export-keywords ()
  8231. "Return a list of all currently understood export keywords.
  8232. Export keywords include options, block names, attributes and
  8233. keywords relative to each registered export back-end."
  8234. (let (keywords)
  8235. (dolist (backend
  8236. (bound-and-true-p org-export-registered-backends)
  8237. (delq nil keywords))
  8238. ;; Back-end name (for keywords, like #+LATEX:)
  8239. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  8240. (dolist (option-entry (org-export-backend-options backend))
  8241. ;; Back-end options.
  8242. (push (nth 1 option-entry) keywords)))))
  8243. (defconst org-options-keywords
  8244. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  8245. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  8246. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  8247. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  8248. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  8249. (defcustom org-structure-template-alist
  8250. '(("a" . "export ascii")
  8251. ("c" . "center")
  8252. ("C" . "comment")
  8253. ("e" . "example")
  8254. ("E" . "export")
  8255. ("h" . "export html")
  8256. ("l" . "export latex")
  8257. ("q" . "quote")
  8258. ("s" . "src")
  8259. ("v" . "verse"))
  8260. "An alist of keys and block types.
  8261. `org-insert-structure-template' will display a menu with this
  8262. list of templates to choose from. The block type is inserted,
  8263. with \"#+BEGIN_\" and \"#+END_\" added automatically.
  8264. The menu keys are defined by the car of each entry in this alist.
  8265. If two entries have the keys \"a\" and \"aa\" respectively, the
  8266. former will be inserted by typing \"a TAB/RET/SPC\" and the
  8267. latter will be inserted by typing \"aa\". If an entry with the
  8268. key \"aab\" is later added, it can be inserted by typing \"ab\".
  8269. If loaded, Org Tempo also uses `org-structure-template-alist'. A
  8270. block can be inserted by pressing TAB after the string \"<KEY\"."
  8271. :group 'org-edit-structure
  8272. :type '(repeat
  8273. (cons (string :tag "Key")
  8274. (string :tag "Template")))
  8275. :package-version '(Org . "9.2"))
  8276. (defun org--check-org-structure-template-alist (&optional checklist)
  8277. "Check whether `org-structure-template-alist' is set up correctly.
  8278. In particular, check if the Org 9.2 format is used as opposed to
  8279. previous format.
  8280. "
  8281. (let ((elm (cl-remove-if-not (lambda (x) (listp (cdr x)))
  8282. (or (eval checklist)
  8283. org-structure-template-alist))))
  8284. (when elm
  8285. (org-display-warning
  8286. (format "
  8287. Please update the entries of `%s'.
  8288. In Org 9.2 the format was changed from something like
  8289. (\"s\" \"#+BEGIN_SRC ?\\n#+END_SRC\")
  8290. to something like
  8291. (\"s\" . \"src\")
  8292. Please refer to the documentation of `org-structure-template-alist'.
  8293. The following entries must be updated:
  8294. %s"
  8295. (or checklist 'org-structure-template-alist)
  8296. (pp-to-string elm))))))
  8297. (defun org--insert-structure-template-mks ()
  8298. "Present `org-structure-template-alist' with `org-mks'.
  8299. Menus are added if keys require more than one keystroke. Tabs
  8300. are added to single key entries when more than one stroke is
  8301. needed. Keys longer than two characters are reduced to two
  8302. characters."
  8303. (org--check-org-structure-template-alist)
  8304. (let* (case-fold-search
  8305. (templates (append org-structure-template-alist
  8306. '(("\t" . "Press TAB, RET or SPC to write block name"))))
  8307. (keys (mapcar #'car templates))
  8308. (start-letters
  8309. (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
  8310. ;; Sort each element of `org-structure-template-alist' into
  8311. ;; sublists according to the first letter.
  8312. (superlist
  8313. (mapcar (lambda (letter)
  8314. (list letter
  8315. (cl-remove-if-not
  8316. (apply-partially #'string-match-p (concat "^" letter))
  8317. templates :key #'car)))
  8318. start-letters)))
  8319. (org-mks
  8320. (apply #'append
  8321. ;; Make an `org-mks' table. If only one element is
  8322. ;; present in a sublist, make it part of the top-menu,
  8323. ;; otherwise make a submenu according to the starting
  8324. ;; letter and populate it.
  8325. (mapcar (lambda (sublist)
  8326. (if (eq 1 (length (cadr sublist)))
  8327. (mapcar (lambda (elm)
  8328. (list (substring (car elm) 0 1)
  8329. (cdr elm) ""))
  8330. (cadr sublist))
  8331. ;; Create submenu.
  8332. (let* ((topkey (car sublist))
  8333. (elms (cadr sublist))
  8334. (keys (mapcar #'car elms))
  8335. (long (> (length elms) 3)))
  8336. (append
  8337. (list
  8338. ;; Make a description of the submenu.
  8339. (list topkey
  8340. (concat
  8341. (mapconcat #'cdr
  8342. (cl-subseq elms 0 (if long 3 (length elms)))
  8343. ", ")
  8344. (when long ", ..."))))
  8345. ;; List of entries in submenu.
  8346. (cl-mapcar #'list
  8347. (org--insert-structure-template-unique-keys keys)
  8348. (mapcar #'cdr elms)
  8349. (make-list (length elms) ""))))))
  8350. superlist))
  8351. "Select a key\n============"
  8352. "Key: ")))
  8353. (defun org--insert-structure-template-unique-keys (keys)
  8354. "Make a list of unique, two characters long elements from KEYS.
  8355. Elements of length one have a tab appended. Elements of length
  8356. two are kept as is. Longer elements are truncated to length two.
  8357. If an element cannot be made unique, an error is raised."
  8358. (let ((ordered-keys (cl-sort (copy-sequence keys) #'< :key #'length))
  8359. menu-keys)
  8360. (dolist (key ordered-keys)
  8361. (let ((potential-key
  8362. (cl-case (length key)
  8363. (1 (concat key "\t"))
  8364. (2 key)
  8365. (otherwise
  8366. (cl-find-if-not (lambda (k) (assoc k menu-keys))
  8367. (mapcar (apply-partially #'concat (substring key 0 1))
  8368. (split-string (substring key 1) "" t)))))))
  8369. (if (or (not potential-key) (assoc potential-key menu-keys))
  8370. (user-error "Could not make unique key for %s." key)
  8371. (push (cons potential-key key) menu-keys))))
  8372. (mapcar #'car
  8373. (cl-sort menu-keys #'<
  8374. :key (lambda (elm) (cl-position (cdr elm) keys))))))
  8375. (defun org-insert-structure-template (type)
  8376. "Insert a block structure of the type #+begin_foo/#+end_foo.
  8377. Select a block from `org-structure-template-alist' then type
  8378. either RET, TAB or SPC to write the block type. With an active
  8379. region, wrap the region in the block. Otherwise, insert an empty
  8380. block."
  8381. (interactive
  8382. (list (pcase (org--insert-structure-template-mks)
  8383. (`("\t" . ,_) (read-string "Structure type: "))
  8384. (`(,_ ,choice . ,_) choice))))
  8385. (let* ((region? (use-region-p))
  8386. (region-start (and region? (region-beginning)))
  8387. (region-end (and region? (copy-marker (region-end))))
  8388. (extended? (string-match-p "\\`\\(src\\|export\\)\\'" type))
  8389. (verbatim? (string-match-p
  8390. (concat "\\`" (regexp-opt '("example" "export" "src")))
  8391. type)))
  8392. (when region? (goto-char region-start))
  8393. (let ((column (current-indentation)))
  8394. (if (save-excursion (skip-chars-backward " \t") (bolp))
  8395. (beginning-of-line)
  8396. (insert "\n"))
  8397. (save-excursion
  8398. (indent-to column)
  8399. (insert (format "#+begin_%s%s\n" type (if extended? " " "")))
  8400. (when region?
  8401. (when verbatim? (org-escape-code-in-region (point) region-end))
  8402. (goto-char region-end)
  8403. ;; Ignore empty lines at the end of the region.
  8404. (skip-chars-backward " \r\t\n")
  8405. (end-of-line))
  8406. (unless (bolp) (insert "\n"))
  8407. (indent-to column)
  8408. (insert (format "#+end_%s" (car (split-string type))))
  8409. (if (looking-at "[ \t]*$") (replace-match "")
  8410. (insert "\n"))
  8411. (when (and (eobp) (not (bolp))) (insert "\n")))
  8412. (if extended? (end-of-line)
  8413. (forward-line)
  8414. (skip-chars-forward " \t")))))
  8415. ;;;; TODO, DEADLINE, Comments
  8416. (defun org-toggle-comment ()
  8417. "Change the COMMENT state of an entry."
  8418. (interactive)
  8419. (save-excursion
  8420. (org-back-to-heading)
  8421. (let ((case-fold-search nil))
  8422. (looking-at org-complex-heading-regexp))
  8423. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  8424. (skip-chars-forward " \t")
  8425. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  8426. (if (org-in-commented-heading-p t)
  8427. (delete-region (point)
  8428. (progn (search-forward " " (line-end-position) 'move)
  8429. (skip-chars-forward " \t")
  8430. (point)))
  8431. (insert org-comment-string)
  8432. (unless (eolp) (insert " ")))))
  8433. (defvar org-last-todo-state-is-todo nil
  8434. "This is non-nil when the last TODO state change led to a TODO state.
  8435. If the last change removed the TODO tag or switched to DONE, then
  8436. this is nil.")
  8437. (defvar org-todo-setup-filter-hook nil
  8438. "Hook for functions that pre-filter todo specs.
  8439. Each function takes a todo spec and returns either nil or the spec
  8440. transformed into canonical form." )
  8441. (defvar org-todo-get-default-hook nil
  8442. "Hook for functions that get a default item for todo.
  8443. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  8444. nil or a string to be used for the todo mark." )
  8445. (defvar org-agenda-headline-snapshot-before-repeat)
  8446. (defun org-current-effective-time ()
  8447. "Return current time adjusted for `org-extend-today-until' variable."
  8448. (let* ((ct (org-current-time))
  8449. (dct (decode-time ct))
  8450. (ct1
  8451. (cond
  8452. (org-use-last-clock-out-time-as-effective-time
  8453. (or (org-clock-get-last-clock-out-time) ct))
  8454. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  8455. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  8456. (t ct))))
  8457. ct1))
  8458. (defun org-todo-yesterday (&optional arg)
  8459. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  8460. (interactive "P")
  8461. (if (eq major-mode 'org-agenda-mode)
  8462. (apply 'org-agenda-todo-yesterday arg)
  8463. (let* ((org-use-effective-time t)
  8464. (hour (nth 2 (decode-time (org-current-time))))
  8465. (org-extend-today-until (1+ hour)))
  8466. (org-todo arg))))
  8467. (defvar org-block-entry-blocking ""
  8468. "First entry preventing the TODO state change.")
  8469. (defun org-cancel-repeater ()
  8470. "Cancel a repeater by setting its numeric value to zero."
  8471. (interactive)
  8472. (save-excursion
  8473. (org-back-to-heading t)
  8474. (let ((bound1 (point))
  8475. (bound0 (save-excursion (outline-next-heading) (point))))
  8476. (when (and (re-search-forward
  8477. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  8478. org-deadline-time-regexp "\\)\\|\\("
  8479. org-ts-regexp "\\)")
  8480. bound0 t)
  8481. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  8482. bound1 t))
  8483. (replace-match "0" t nil nil 1)))))
  8484. (defvar org-state)
  8485. (defvar org-blocked-by-checkboxes)
  8486. (defun org-todo (&optional arg)
  8487. "Change the TODO state of an item.
  8488. The state of an item is given by a keyword at the start of the heading,
  8489. like
  8490. *** TODO Write paper
  8491. *** DONE Call mom
  8492. The different keywords are specified in the variable `org-todo-keywords'.
  8493. By default the available states are \"TODO\" and \"DONE\". So, for this
  8494. example: when the item starts with TODO, it is changed to DONE.
  8495. When it starts with DONE, the DONE is removed. And when neither TODO nor
  8496. DONE are present, add TODO at the beginning of the heading.
  8497. You can set up single-character keys to fast-select the new state. See the
  8498. `org-todo-keywords' and `org-use-fast-todo-selection' for details.
  8499. With `\\[universal-argument]' prefix ARG, force logging the state change \
  8500. and take a
  8501. logging note.
  8502. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  8503. next set of TODO \
  8504. keywords (nextset).
  8505. Another way to achieve this is `S-C-<right>'.
  8506. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8507. prefix, circumvent any state blocking.
  8508. With numeric prefix arg, switch to the Nth state.
  8509. With a numeric prefix arg of 0, inhibit note taking for the change.
  8510. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  8511. When called through ELisp, arg is also interpreted in the following way:
  8512. `none' -> empty state
  8513. \"\" -> switch to empty state
  8514. `done' -> switch to DONE
  8515. `nextset' -> switch to the next set of keywords
  8516. `previousset' -> switch to the previous set of keywords
  8517. \"WAITING\" -> switch to the specified keyword, but only if it
  8518. really is a member of `org-todo-keywords'."
  8519. (interactive "P")
  8520. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  8521. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  8522. 'region-start-level 'region))
  8523. org-loop-over-headlines-in-active-region)
  8524. (org-map-entries
  8525. `(org-todo ,arg)
  8526. org-loop-over-headlines-in-active-region
  8527. cl (when (org-invisible-p) (org-end-of-subtree nil t))))
  8528. (when (equal arg '(16)) (setq arg 'nextset))
  8529. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  8530. (let ((org-blocker-hook org-blocker-hook)
  8531. commentp
  8532. case-fold-search)
  8533. (when (equal arg '(64))
  8534. (setq arg nil org-blocker-hook nil))
  8535. (when (and org-blocker-hook
  8536. (or org-inhibit-blocking
  8537. (org-entry-get nil "NOBLOCKING")))
  8538. (setq org-blocker-hook nil))
  8539. (save-excursion
  8540. (catch 'exit
  8541. (org-back-to-heading t)
  8542. (when (org-in-commented-heading-p t)
  8543. (org-toggle-comment)
  8544. (setq commentp t))
  8545. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  8546. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  8547. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  8548. (let* ((match-data (match-data))
  8549. (startpos (copy-marker (line-beginning-position)))
  8550. (force-log (and (equal arg '(4)) (prog1 t (setq arg nil))))
  8551. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  8552. (org-log-done org-log-done)
  8553. (org-log-repeat org-log-repeat)
  8554. (org-todo-log-states org-todo-log-states)
  8555. (org-inhibit-logging
  8556. (if (equal arg 0)
  8557. (progn (setq arg nil) 'note) org-inhibit-logging))
  8558. (this (match-string 1))
  8559. (hl-pos (match-beginning 0))
  8560. (head (org-get-todo-sequence-head this))
  8561. (ass (assoc head org-todo-kwd-alist))
  8562. (interpret (nth 1 ass))
  8563. (done-word (nth 3 ass))
  8564. (final-done-word (nth 4 ass))
  8565. (org-last-state (or this ""))
  8566. (completion-ignore-case t)
  8567. (member (member this org-todo-keywords-1))
  8568. (tail (cdr member))
  8569. (org-state (cond
  8570. ((eq arg 'right)
  8571. ;; Next state
  8572. (if this
  8573. (if tail (car tail) nil)
  8574. (car org-todo-keywords-1)))
  8575. ((eq arg 'left)
  8576. ;; Previous state
  8577. (unless (equal member org-todo-keywords-1)
  8578. (if this
  8579. (nth (- (length org-todo-keywords-1)
  8580. (length tail) 2)
  8581. org-todo-keywords-1)
  8582. (org-last org-todo-keywords-1))))
  8583. (arg
  8584. ;; User or caller requests a specific state.
  8585. (cond
  8586. ((equal arg "") nil)
  8587. ((eq arg 'none) nil)
  8588. ((eq arg 'done) (or done-word (car org-done-keywords)))
  8589. ((eq arg 'nextset)
  8590. (or (car (cdr (member head org-todo-heads)))
  8591. (car org-todo-heads)))
  8592. ((eq arg 'previousset)
  8593. (let ((org-todo-heads (reverse org-todo-heads)))
  8594. (or (car (cdr (member head org-todo-heads)))
  8595. (car org-todo-heads))))
  8596. ((car (member arg org-todo-keywords-1)))
  8597. ((stringp arg)
  8598. (user-error "State `%s' not valid in this file" arg))
  8599. ((nth (1- (prefix-numeric-value arg))
  8600. org-todo-keywords-1))))
  8601. ((and org-todo-key-trigger org-use-fast-todo-selection)
  8602. ;; Use fast selection.
  8603. (org-fast-todo-selection this))
  8604. ((null member) (or head (car org-todo-keywords-1)))
  8605. ((equal this final-done-word) nil) ;-> make empty
  8606. ((null tail) nil) ;-> first entry
  8607. ((memq interpret '(type priority))
  8608. (if (eq this-command last-command)
  8609. (car tail)
  8610. (if (> (length tail) 0)
  8611. (or done-word (car org-done-keywords))
  8612. nil)))
  8613. (t
  8614. (car tail))))
  8615. (org-state (or
  8616. (run-hook-with-args-until-success
  8617. 'org-todo-get-default-hook org-state org-last-state)
  8618. org-state))
  8619. (next (if (org-string-nw-p org-state) (concat " " org-state " ") " "))
  8620. (change-plist (list :type 'todo-state-change :from this :to org-state
  8621. :position startpos))
  8622. dolog now-done-p)
  8623. (when org-blocker-hook
  8624. (let (org-blocked-by-checkboxes block-reason)
  8625. (setq org-last-todo-state-is-todo
  8626. (not (member this org-done-keywords)))
  8627. (unless (save-excursion
  8628. (save-match-data
  8629. (org-with-wide-buffer
  8630. (run-hook-with-args-until-failure
  8631. 'org-blocker-hook change-plist))))
  8632. (setq block-reason (if org-blocked-by-checkboxes
  8633. "contained checkboxes"
  8634. (format "\"%s\"" org-block-entry-blocking)))
  8635. (if (called-interactively-p 'interactive)
  8636. (user-error "TODO state change from %s to %s blocked (by %s)"
  8637. this org-state block-reason)
  8638. ;; Fail silently.
  8639. (message "TODO state change from %s to %s blocked (by %s)"
  8640. this org-state block-reason)
  8641. (throw 'exit nil)))))
  8642. (store-match-data match-data)
  8643. (replace-match next t t)
  8644. (cond ((and org-state (equal this org-state))
  8645. (message "TODO state was already %s" (org-trim next)))
  8646. ((not (pos-visible-in-window-p hl-pos))
  8647. (message "TODO state changed to %s" (org-trim next))))
  8648. (unless head
  8649. (setq head (org-get-todo-sequence-head org-state)
  8650. ass (assoc head org-todo-kwd-alist)
  8651. interpret (nth 1 ass)
  8652. done-word (nth 3 ass)
  8653. final-done-word (nth 4 ass)))
  8654. (when (memq arg '(nextset previousset))
  8655. (message "Keyword-Set %d/%d: %s"
  8656. (- (length org-todo-sets) -1
  8657. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  8658. (length org-todo-sets)
  8659. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  8660. (setq org-last-todo-state-is-todo
  8661. (not (member org-state org-done-keywords)))
  8662. (setq now-done-p (and (member org-state org-done-keywords)
  8663. (not (member this org-done-keywords))))
  8664. (and logging (org-local-logging logging))
  8665. (when (or (and (or org-todo-log-states org-log-done)
  8666. (not (eq org-inhibit-logging t))
  8667. (not (memq arg '(nextset previousset))))
  8668. force-log)
  8669. ;; We need to look at recording a time and note.
  8670. (setq dolog (or (if force-log 'note)
  8671. (nth 1 (assoc org-state org-todo-log-states))
  8672. (nth 2 (assoc this org-todo-log-states))))
  8673. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  8674. (setq dolog 'time))
  8675. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  8676. (and org-state
  8677. (member org-state org-not-done-keywords)
  8678. (not (member this org-not-done-keywords))))
  8679. ;; This is now a todo state and was not one before
  8680. ;; If there was a CLOSED time stamp, get rid of it.
  8681. (org-add-planning-info nil nil 'closed))
  8682. (when (and now-done-p org-log-done)
  8683. ;; It is now done, and it was not done before.
  8684. (org-add-planning-info 'closed (org-current-effective-time))
  8685. (when (and (not dolog) (eq 'note org-log-done))
  8686. (org-add-log-setup 'done org-state this 'note)))
  8687. (when (and org-state dolog)
  8688. ;; This is a non-nil state, and we need to log it.
  8689. (org-add-log-setup 'state org-state this dolog)))
  8690. ;; Fixup tag positioning.
  8691. (org-todo-trigger-tag-changes org-state)
  8692. (when org-auto-align-tags (org-align-tags))
  8693. (when org-provide-todo-statistics
  8694. (org-update-parent-todo-statistics))
  8695. (when (bound-and-true-p org-clock-out-when-done)
  8696. (org-clock-out-if-current))
  8697. (run-hooks 'org-after-todo-state-change-hook)
  8698. (when (and arg (not (member org-state org-done-keywords)))
  8699. (setq head (org-get-todo-sequence-head org-state)))
  8700. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  8701. ;; Do we need to trigger a repeat?
  8702. (when now-done-p
  8703. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  8704. ;; This is for the agenda, take a snapshot of the headline.
  8705. (save-match-data
  8706. (setq org-agenda-headline-snapshot-before-repeat
  8707. (org-get-heading))))
  8708. (org-auto-repeat-maybe org-state))
  8709. ;; Fixup cursor location if close to the keyword.
  8710. (when (and (outline-on-heading-p)
  8711. (not (bolp))
  8712. (save-excursion (beginning-of-line 1)
  8713. (looking-at org-todo-line-regexp))
  8714. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  8715. (goto-char (or (match-end 2) (match-end 1)))
  8716. (and (looking-at " ")
  8717. (not (looking-at " *:"))
  8718. (just-one-space)))
  8719. (when org-trigger-hook
  8720. (save-excursion
  8721. (run-hook-with-args 'org-trigger-hook change-plist)))
  8722. (when commentp (org-toggle-comment))))))))
  8723. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  8724. "Block turning an entry into a TODO, using the hierarchy.
  8725. This checks whether the current task should be blocked from state
  8726. changes. Such blocking occurs when:
  8727. 1. The task has children which are not all in a completed state.
  8728. 2. A task has a parent with the property :ORDERED:, and there
  8729. are siblings prior to the current task with incomplete
  8730. status.
  8731. 3. The parent of the task is blocked because it has siblings that should
  8732. be done first, or is child of a block grandparent TODO entry."
  8733. (if (not org-enforce-todo-dependencies)
  8734. t ; if locally turned off don't block
  8735. (catch 'dont-block
  8736. ;; If this is not a todo state change, or if this entry is already DONE,
  8737. ;; do not block
  8738. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  8739. (member (plist-get change-plist :from)
  8740. (cons 'done org-done-keywords))
  8741. (member (plist-get change-plist :to)
  8742. (cons 'todo org-not-done-keywords))
  8743. (not (plist-get change-plist :to)))
  8744. (throw 'dont-block t))
  8745. ;; If this task has children, and any are undone, it's blocked
  8746. (save-excursion
  8747. (org-back-to-heading t)
  8748. (let ((this-level (funcall outline-level)))
  8749. (outline-next-heading)
  8750. (let ((child-level (funcall outline-level)))
  8751. (while (and (not (eobp))
  8752. (> child-level this-level))
  8753. ;; this todo has children, check whether they are all
  8754. ;; completed
  8755. (when (and (not (org-entry-is-done-p))
  8756. (org-entry-is-todo-p))
  8757. (setq org-block-entry-blocking (org-get-heading))
  8758. (throw 'dont-block nil))
  8759. (outline-next-heading)
  8760. (setq child-level (funcall outline-level))))))
  8761. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  8762. ;; any previous siblings are undone, it's blocked
  8763. (save-excursion
  8764. (org-back-to-heading t)
  8765. (let* ((pos (point))
  8766. (parent-pos (and (org-up-heading-safe) (point)))
  8767. (case-fold-search nil))
  8768. (unless parent-pos (throw 'dont-block t)) ; no parent
  8769. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  8770. (forward-line 1)
  8771. (re-search-forward org-not-done-heading-regexp pos t))
  8772. (setq org-block-entry-blocking (match-string 0))
  8773. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  8774. ;; Search further up the hierarchy, to see if an ancestor is blocked
  8775. (while t
  8776. (goto-char parent-pos)
  8777. (unless (looking-at org-not-done-heading-regexp)
  8778. (throw 'dont-block t)) ; do not block, parent is not a TODO
  8779. (setq pos (point))
  8780. (setq parent-pos (and (org-up-heading-safe) (point)))
  8781. (unless parent-pos (throw 'dont-block t)) ; no parent
  8782. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  8783. (forward-line 1)
  8784. (re-search-forward org-not-done-heading-regexp pos t)
  8785. (setq org-block-entry-blocking (org-get-heading)))
  8786. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  8787. (defcustom org-track-ordered-property-with-tag nil
  8788. "Should the ORDERED property also be shown as a tag?
  8789. The ORDERED property decides if an entry should require subtasks to be
  8790. completed in sequence. Since a property is not very visible, setting
  8791. this option means that toggling the ORDERED property with the command
  8792. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  8793. not relevant for the behavior, but it makes things more visible.
  8794. Note that toggling the tag with tags commands will not change the property
  8795. and therefore not influence behavior!
  8796. This can be t, meaning the tag ORDERED should be used. It can also be a
  8797. string to select a different tag for this task."
  8798. :group 'org-todo
  8799. :type '(choice
  8800. (const :tag "No tracking" nil)
  8801. (const :tag "Track with ORDERED tag" t)
  8802. (string :tag "Use other tag")))
  8803. (defun org-toggle-ordered-property ()
  8804. "Toggle the ORDERED property of the current entry.
  8805. For better visibility, you can track the value of this property with a tag.
  8806. See variable `org-track-ordered-property-with-tag'."
  8807. (interactive)
  8808. (let* ((t1 org-track-ordered-property-with-tag)
  8809. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  8810. (save-excursion
  8811. (org-back-to-heading)
  8812. (if (org-entry-get nil "ORDERED")
  8813. (progn
  8814. (org-delete-property "ORDERED")
  8815. (and tag (org-toggle-tag tag 'off))
  8816. (message "Subtasks can be completed in arbitrary order"))
  8817. (org-entry-put nil "ORDERED" "t")
  8818. (and tag (org-toggle-tag tag 'on))
  8819. (message "Subtasks must be completed in sequence")))))
  8820. (defun org-block-todo-from-checkboxes (change-plist)
  8821. "Block turning an entry into a TODO, using checkboxes.
  8822. This checks whether the current task should be blocked from state
  8823. changes because there are unchecked boxes in this entry."
  8824. (if (not org-enforce-todo-checkbox-dependencies)
  8825. t ; if locally turned off don't block
  8826. (catch 'dont-block
  8827. ;; If this is not a todo state change, or if this entry is already DONE,
  8828. ;; do not block
  8829. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  8830. (member (plist-get change-plist :from)
  8831. (cons 'done org-done-keywords))
  8832. (member (plist-get change-plist :to)
  8833. (cons 'todo org-not-done-keywords))
  8834. (not (plist-get change-plist :to)))
  8835. (throw 'dont-block t))
  8836. ;; If this task has checkboxes that are not checked, it's blocked
  8837. (save-excursion
  8838. (org-back-to-heading t)
  8839. (let ((beg (point)) end)
  8840. (outline-next-heading)
  8841. (setq end (point))
  8842. (goto-char beg)
  8843. (when (org-list-search-forward
  8844. (concat (org-item-beginning-re)
  8845. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  8846. "\\[[- ]\\]")
  8847. end t)
  8848. (when (boundp 'org-blocked-by-checkboxes)
  8849. (setq org-blocked-by-checkboxes t))
  8850. (throw 'dont-block nil))))
  8851. t))) ; do not block
  8852. (defun org-entry-blocked-p ()
  8853. "Non-nil if entry at point is blocked."
  8854. (and (not (org-entry-get nil "NOBLOCKING"))
  8855. (member (org-entry-get nil "TODO") org-not-done-keywords)
  8856. (not (run-hook-with-args-until-failure
  8857. 'org-blocker-hook
  8858. (list :type 'todo-state-change
  8859. :position (point)
  8860. :from 'todo
  8861. :to 'done)))))
  8862. (defun org-update-statistics-cookies (all)
  8863. "Update the statistics cookie, either from TODO or from checkboxes.
  8864. This should be called with the cursor in a line with a statistics
  8865. cookie. When called with a \\[universal-argument] prefix, update
  8866. all statistics cookies in the buffer."
  8867. (interactive "P")
  8868. (if all
  8869. (progn
  8870. (org-update-checkbox-count 'all)
  8871. (org-map-entries 'org-update-parent-todo-statistics))
  8872. (if (not (org-at-heading-p))
  8873. (org-update-checkbox-count)
  8874. (let ((pos (point-marker))
  8875. end l1 l2)
  8876. (ignore-errors (org-back-to-heading t))
  8877. (if (not (org-at-heading-p))
  8878. (org-update-checkbox-count)
  8879. (setq l1 (org-outline-level))
  8880. (setq end (save-excursion
  8881. (outline-next-heading)
  8882. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  8883. (point)))
  8884. (if (and (save-excursion
  8885. (re-search-forward
  8886. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  8887. (not (save-excursion (re-search-forward
  8888. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  8889. (org-update-checkbox-count)
  8890. (if (and l2 (> l2 l1))
  8891. (progn
  8892. (goto-char end)
  8893. (org-update-parent-todo-statistics))
  8894. (goto-char pos)
  8895. (beginning-of-line 1)
  8896. (while (re-search-forward
  8897. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  8898. (point-at-eol) t)
  8899. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  8900. (goto-char pos)
  8901. (move-marker pos nil)))))
  8902. (defvar org-entry-property-inherited-from) ;; defined below
  8903. (defun org-update-parent-todo-statistics ()
  8904. "Update any statistics cookie in the parent of the current headline.
  8905. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  8906. the entire subtree and this will travel up the hierarchy and update
  8907. statistics everywhere."
  8908. (let* ((prop (save-excursion (org-up-heading-safe)
  8909. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  8910. (recursive (or (not org-hierarchical-todo-statistics)
  8911. (and prop (string-match "\\<recursive\\>" prop))))
  8912. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  8913. 0))
  8914. (first t)
  8915. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  8916. level ltoggle l1 new ndel
  8917. (cnt-all 0) (cnt-done 0) is-percent kwd
  8918. checkbox-beg cookie-present)
  8919. (catch 'exit
  8920. (save-excursion
  8921. (beginning-of-line 1)
  8922. (setq ltoggle (funcall outline-level))
  8923. ;; Three situations are to consider:
  8924. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  8925. ;; to the top-level ancestor on the headline;
  8926. ;; 2. If parent has "recursive" property, repeat up to the
  8927. ;; headline setting that property, taking inheritance into
  8928. ;; account;
  8929. ;; 3. Else, move up to direct parent and proceed only once.
  8930. (while (and (setq level (org-up-heading-safe))
  8931. (or recursive first)
  8932. (>= (point) lim))
  8933. (setq first nil cookie-present nil)
  8934. (unless (and level
  8935. (not (string-match
  8936. "\\<checkbox\\>"
  8937. (downcase (or (org-entry-get nil "COOKIE_DATA")
  8938. "")))))
  8939. (throw 'exit nil))
  8940. (while (re-search-forward box-re (point-at-eol) t)
  8941. (setq cnt-all 0 cnt-done 0 cookie-present t)
  8942. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  8943. (save-match-data
  8944. (unless (outline-next-heading) (throw 'exit nil))
  8945. (while (and (looking-at org-complex-heading-regexp)
  8946. (> (setq l1 (length (match-string 1))) level))
  8947. (setq kwd (and (or recursive (= l1 ltoggle))
  8948. (match-string 2)))
  8949. (if (or (eq org-provide-todo-statistics 'all-headlines)
  8950. (and (eq org-provide-todo-statistics t)
  8951. (or (member kwd org-done-keywords)))
  8952. (and (listp org-provide-todo-statistics)
  8953. (stringp (car org-provide-todo-statistics))
  8954. (or (member kwd org-provide-todo-statistics)
  8955. (member kwd org-done-keywords)))
  8956. (and (listp org-provide-todo-statistics)
  8957. (listp (car org-provide-todo-statistics))
  8958. (or (member kwd (car org-provide-todo-statistics))
  8959. (and (member kwd org-done-keywords)
  8960. (member kwd (cadr org-provide-todo-statistics))))))
  8961. (setq cnt-all (1+ cnt-all))
  8962. (and (eq org-provide-todo-statistics t)
  8963. kwd
  8964. (setq cnt-all (1+ cnt-all))))
  8965. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  8966. (member kwd org-done-keywords))
  8967. (and (listp org-provide-todo-statistics)
  8968. (listp (car org-provide-todo-statistics))
  8969. (member kwd org-done-keywords)
  8970. (member kwd (cadr org-provide-todo-statistics)))
  8971. (and (listp org-provide-todo-statistics)
  8972. (stringp (car org-provide-todo-statistics))
  8973. (member kwd org-done-keywords)))
  8974. (setq cnt-done (1+ cnt-done)))
  8975. (outline-next-heading)))
  8976. (setq new
  8977. (if is-percent
  8978. (format "[%d%%]" (floor (* 100.0 cnt-done)
  8979. (max 1 cnt-all)))
  8980. (format "[%d/%d]" cnt-done cnt-all))
  8981. ndel (- (match-end 0) checkbox-beg))
  8982. (goto-char checkbox-beg)
  8983. (insert new)
  8984. (delete-region (point) (+ (point) ndel))
  8985. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  8986. (when cookie-present
  8987. (run-hook-with-args 'org-after-todo-statistics-hook
  8988. cnt-done (- cnt-all cnt-done))))))
  8989. (run-hooks 'org-todo-statistics-hook)))
  8990. (defvar org-after-todo-statistics-hook nil
  8991. "Hook that is called after a TODO statistics cookie has been updated.
  8992. Each function is called with two arguments: the number of not-done entries
  8993. and the number of done entries.
  8994. For example, the following function, when added to this hook, will switch
  8995. an entry to DONE when all children are done, and back to TODO when new
  8996. entries are set to a TODO status. Note that this hook is only called
  8997. when there is a statistics cookie in the headline!
  8998. (defun org-summary-todo (n-done n-not-done)
  8999. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  9000. (let (org-log-done org-log-states) ; turn off logging
  9001. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  9002. ")
  9003. (defvar org-todo-statistics-hook nil
  9004. "Hook that is run whenever Org thinks TODO statistics should be updated.
  9005. This hook runs even if there is no statistics cookie present, in which case
  9006. `org-after-todo-statistics-hook' would not run.")
  9007. (defun org-todo-trigger-tag-changes (state)
  9008. "Apply the changes defined in `org-todo-state-tags-triggers'."
  9009. (let ((l org-todo-state-tags-triggers)
  9010. changes)
  9011. (when (or (not state) (equal state ""))
  9012. (setq changes (append changes (cdr (assoc "" l)))))
  9013. (when (and (stringp state) (> (length state) 0))
  9014. (setq changes (append changes (cdr (assoc state l)))))
  9015. (when (member state org-not-done-keywords)
  9016. (setq changes (append changes (cdr (assq 'todo l)))))
  9017. (when (member state org-done-keywords)
  9018. (setq changes (append changes (cdr (assq 'done l)))))
  9019. (dolist (c changes)
  9020. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  9021. (defun org-local-logging (value)
  9022. "Get logging settings from a property VALUE."
  9023. ;; Directly set the variables, they are already local.
  9024. (setq org-log-done nil
  9025. org-log-repeat nil
  9026. org-todo-log-states nil)
  9027. (dolist (w (split-string value))
  9028. (let (a)
  9029. (cond
  9030. ((setq a (assoc w org-startup-options))
  9031. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  9032. (set (nth 1 a) (nth 2 a))))
  9033. ((setq a (org-extract-log-state-settings w))
  9034. (and (member (car a) org-todo-keywords-1)
  9035. (push a org-todo-log-states)))))))
  9036. (defun org-get-todo-sequence-head (kwd)
  9037. "Return the head of the TODO sequence to which KWD belongs.
  9038. If KWD is not set, check if there is a text property remembering the
  9039. right sequence."
  9040. (let (p)
  9041. (cond
  9042. ((not kwd)
  9043. (or (get-text-property (point-at-bol) 'org-todo-head)
  9044. (progn
  9045. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  9046. nil (point-at-eol)))
  9047. (get-text-property p 'org-todo-head))))
  9048. ((not (member kwd org-todo-keywords-1))
  9049. (car org-todo-keywords-1))
  9050. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  9051. (defun org-fast-todo-selection (&optional current-state)
  9052. "Fast TODO keyword selection with single keys.
  9053. Returns the new TODO keyword, or nil if no state change should occur.
  9054. When CURRENT-STATE is given and selection letters are not unique globally,
  9055. prefer a state in the current sequence over on in another sequence."
  9056. (let* ((fulltable org-todo-key-alist)
  9057. (head (org-get-todo-sequence-head current-state))
  9058. (done-keywords org-done-keywords) ;; needed for the faces.
  9059. (maxlen (apply 'max (mapcar
  9060. (lambda (x)
  9061. (if (stringp (car x)) (string-width (car x)) 0))
  9062. fulltable)))
  9063. (expert (equal org-use-fast-todo-selection 'expert))
  9064. (prompt "")
  9065. (fwidth (+ maxlen 3 1 3))
  9066. (ncol (/ (- (window-width) 4) fwidth))
  9067. tg cnt e c tbl subtable
  9068. groups ingroup in-current-sequence)
  9069. (save-excursion
  9070. (save-window-excursion
  9071. (if expert
  9072. (set-buffer (get-buffer-create " *Org todo*"))
  9073. (delete-other-windows)
  9074. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org todo*"))
  9075. (org-switch-to-buffer-other-window " *Org todo*"))
  9076. (erase-buffer)
  9077. (setq-local org-done-keywords done-keywords)
  9078. (setq tbl fulltable cnt 0)
  9079. (while (setq e (pop tbl))
  9080. (cond
  9081. ((equal e '(:startgroup))
  9082. (push '() groups) (setq ingroup t)
  9083. (unless (= cnt 0)
  9084. (setq cnt 0)
  9085. (insert "\n"))
  9086. (setq prompt (concat prompt "{"))
  9087. (insert "{ "))
  9088. ((equal e '(:endgroup))
  9089. (setq ingroup nil cnt 0 in-current-sequence nil)
  9090. (setq prompt (concat prompt "}"))
  9091. (insert "}\n"))
  9092. ((equal e '(:newline))
  9093. (unless (= cnt 0)
  9094. (setq cnt 0)
  9095. (insert "\n")
  9096. (setq e (car tbl))
  9097. (while (equal (car tbl) '(:newline))
  9098. (insert "\n")
  9099. (setq tbl (cdr tbl)))))
  9100. (t
  9101. (setq tg (car e) c (cdr e))
  9102. (if (equal tg head) (setq in-current-sequence t))
  9103. (when ingroup (push tg (car groups)))
  9104. (when in-current-sequence (push e subtable))
  9105. (setq tg (org-add-props tg nil 'face
  9106. (org-get-todo-face tg)))
  9107. (when (and (= cnt 0) (not ingroup)) (insert " "))
  9108. (setq prompt (concat prompt "[" (char-to-string c) "] " tg " "))
  9109. (insert "[" c "] " tg (make-string
  9110. (- fwidth 4 (length tg)) ?\ ))
  9111. (when (and (= (setq cnt (1+ cnt)) ncol)
  9112. ;; Avoid lines with just a closing delimiter.
  9113. (not (equal (car tbl) '(:endgroup))))
  9114. (insert "\n")
  9115. (when ingroup (insert " "))
  9116. (setq cnt 0)))))
  9117. (insert "\n")
  9118. (goto-char (point-min))
  9119. (unless expert (org-fit-window-to-buffer))
  9120. (message (concat "[a-z..]:Set [SPC]:clear"
  9121. (if expert (concat "\n" prompt) "")))
  9122. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  9123. (setq subtable (nreverse subtable))
  9124. (cond
  9125. ((or (= c ?\C-g)
  9126. (and (= c ?q) (not (rassoc c fulltable))))
  9127. (setq quit-flag t))
  9128. ((= c ?\ ) nil)
  9129. ((setq e (or (rassoc c subtable) (rassoc c fulltable))
  9130. tg (car e))
  9131. tg)
  9132. (t (setq quit-flag t)))))))
  9133. (defun org-entry-is-todo-p ()
  9134. (member (org-get-todo-state) org-not-done-keywords))
  9135. (defun org-entry-is-done-p ()
  9136. (member (org-get-todo-state) org-done-keywords))
  9137. (defun org-get-todo-state ()
  9138. "Return the TODO keyword of the current subtree."
  9139. (save-excursion
  9140. (org-back-to-heading t)
  9141. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  9142. (match-end 2)
  9143. (match-string 2))))
  9144. (defun org-at-date-range-p (&optional inactive-ok)
  9145. "Non-nil if point is inside a date range.
  9146. When optional argument INACTIVE-OK is non-nil, also consider
  9147. inactive time ranges.
  9148. When this function returns a non-nil value, match data is set
  9149. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  9150. on INACTIVE-OK."
  9151. (interactive)
  9152. (save-excursion
  9153. (catch 'exit
  9154. (let ((pos (point)))
  9155. (skip-chars-backward "^[<\r\n")
  9156. (skip-chars-backward "<[")
  9157. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  9158. (>= (match-end 0) pos)
  9159. (throw 'exit t))
  9160. (skip-chars-backward "^<[\r\n")
  9161. (skip-chars-backward "<[")
  9162. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  9163. (>= (match-end 0) pos)
  9164. (throw 'exit t)))
  9165. nil)))
  9166. (defun org-get-repeat (&optional timestamp)
  9167. "Check if there is a time-stamp with repeater in this entry.
  9168. Return the repeater, as a string, or nil. Also return nil when
  9169. this function is called before first heading.
  9170. When optional argument TIMESTAMP is a string, extract the
  9171. repeater from there instead."
  9172. (save-match-data
  9173. (cond (timestamp
  9174. (and (string-match org-repeat-re timestamp)
  9175. (match-string-no-properties 1 timestamp)))
  9176. ((org-before-first-heading-p) nil)
  9177. (t
  9178. (save-excursion
  9179. (org-back-to-heading t)
  9180. (let ((end (org-entry-end-position)))
  9181. (catch :repeat
  9182. (while (re-search-forward org-repeat-re end t)
  9183. (when (save-match-data (org-at-timestamp-p 'agenda))
  9184. (throw :repeat (match-string-no-properties 1)))))))))))
  9185. (defvar org-last-changed-timestamp)
  9186. (defvar org-last-inserted-timestamp)
  9187. (defvar org-log-post-message)
  9188. (defvar org-log-note-purpose)
  9189. (defvar org-log-note-how nil)
  9190. (defvar org-log-note-extra)
  9191. (defun org-auto-repeat-maybe (done-word)
  9192. "Check if the current headline contains a repeated time-stamp.
  9193. If yes, set TODO state back to what it was and change the base date
  9194. of repeating deadline/scheduled time stamps to new date.
  9195. This function is run automatically after each state change to a DONE state."
  9196. (let* ((repeat (org-get-repeat))
  9197. (aa (assoc org-last-state org-todo-kwd-alist))
  9198. (interpret (nth 1 aa))
  9199. (head (nth 2 aa))
  9200. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  9201. (msg "Entry repeats: ")
  9202. (org-log-done nil)
  9203. (org-todo-log-states nil)
  9204. (end (copy-marker (org-entry-end-position))))
  9205. (when (and repeat (not (= 0 (string-to-number (substring repeat 1)))))
  9206. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  9207. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  9208. (and (stringp org-todo-repeat-to-state)
  9209. org-todo-repeat-to-state)
  9210. (and org-todo-repeat-to-state org-last-state))))
  9211. (org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
  9212. to-state)
  9213. ((eq interpret 'type) org-last-state)
  9214. (head)
  9215. (t 'none))))
  9216. (org-back-to-heading t)
  9217. (org-add-planning-info nil nil 'closed)
  9218. ;; When `org-log-repeat' is non-nil or entry contains
  9219. ;; a clock, set LAST_REPEAT property.
  9220. (when (or org-log-repeat
  9221. (catch :clock
  9222. (save-excursion
  9223. (while (re-search-forward org-clock-line-re end t)
  9224. (when (org-at-clock-log-p) (throw :clock t))))))
  9225. (org-entry-put nil "LAST_REPEAT" (format-time-string
  9226. (org-time-stamp-format t t))))
  9227. (when org-log-repeat
  9228. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  9229. (memq 'org-add-log-note post-command-hook))
  9230. ;; We are already setup for some record.
  9231. (when (eq org-log-repeat 'note)
  9232. ;; Make sure we take a note, not only a time stamp.
  9233. (setq org-log-note-how 'note))
  9234. ;; Set up for taking a record.
  9235. (org-add-log-setup 'state
  9236. (or done-word (car org-done-keywords))
  9237. org-last-state
  9238. org-log-repeat)))
  9239. ;; Time-stamps without a repeater are usually skipped. However,
  9240. ;; a SCHEDULED time-stamp without one is removed, as they are no
  9241. ;; longer relevant.
  9242. (save-excursion
  9243. (let ((scheduled (org-entry-get (point) "SCHEDULED")))
  9244. (when (and scheduled (not (string-match-p org-repeat-re scheduled)))
  9245. (org-remove-timestamp-with-keyword org-scheduled-string))))
  9246. ;; Update every time-stamp with a repeater in the entry.
  9247. (let ((planning-re (regexp-opt
  9248. (list org-scheduled-string org-deadline-string))))
  9249. (while (re-search-forward org-repeat-re end t)
  9250. (let* ((ts (match-string 0))
  9251. (type (if (not (org-at-planning-p)) "Plain:"
  9252. (save-excursion
  9253. (re-search-backward
  9254. planning-re (line-beginning-position) t)
  9255. (match-string 0)))))
  9256. (when (and (org-at-timestamp-p 'agenda)
  9257. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  9258. (let ((n (string-to-number (match-string 2 ts)))
  9259. (what (match-string 3 ts)))
  9260. (when (equal what "w") (setq n (* n 7) what "d"))
  9261. (when (and (equal what "h")
  9262. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  9263. ts)))
  9264. (user-error
  9265. "Cannot repeat in %d hour(s) because no hour has been set"
  9266. n))
  9267. ;; Preparation, see if we need to modify the start
  9268. ;; date for the change.
  9269. (when (match-end 1)
  9270. (let ((time (save-match-data (org-time-string-to-time ts)))
  9271. (repeater-type (match-string 1 ts)))
  9272. (cond
  9273. ((equal "." repeater-type)
  9274. ;; Shift starting date to today, or now if
  9275. ;; repeater is by hours.
  9276. (if (equal what "h")
  9277. (org-timestamp-change
  9278. (floor (- (org-time-stamp-to-now ts t)) 60) 'minute)
  9279. (org-timestamp-change
  9280. (- (org-today) (time-to-days time)) 'day)))
  9281. ((equal "+" repeater-type)
  9282. (let ((nshiftmax 10)
  9283. (nshift 0))
  9284. (while (or (= nshift 0)
  9285. (not (org-time-less-p nil time)))
  9286. (when (= nshiftmax (cl-incf nshift))
  9287. (or (y-or-n-p
  9288. (format "%d repeater intervals were not \
  9289. enough to shift date past today. Continue? "
  9290. nshift))
  9291. (user-error "Abort")))
  9292. (org-timestamp-change n (cdr (assoc what whata)))
  9293. (org-in-regexp org-ts-regexp3)
  9294. (setq ts (match-string 1))
  9295. (setq time
  9296. (save-match-data
  9297. (org-time-string-to-time ts)))))
  9298. (org-timestamp-change (- n) (cdr (assoc what whata)))
  9299. ;; Rematch, so that we have everything in place
  9300. ;; for the real shift.
  9301. (org-in-regexp org-ts-regexp3)
  9302. (setq ts (match-string 1))
  9303. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  9304. ts)))))
  9305. (save-excursion
  9306. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  9307. (setq msg
  9308. (concat msg type " " org-last-changed-timestamp " ")))))))
  9309. (run-hooks 'org-todo-repeat-hook)
  9310. (setq org-log-post-message msg)
  9311. (message msg))))
  9312. (defun org-show-todo-tree (arg)
  9313. "Make a compact tree which shows all headlines marked with TODO.
  9314. The tree will show the lines where the regexp matches, and all higher
  9315. headlines above the match.
  9316. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  9317. With a numeric prefix N, construct a sparse tree for the Nth element
  9318. of `org-todo-keywords-1'."
  9319. (interactive "P")
  9320. (let ((case-fold-search nil)
  9321. (kwd-re
  9322. (cond ((null arg) (concat org-not-done-regexp "\\s-"))
  9323. ((equal arg '(4))
  9324. (let ((kwd
  9325. (completing-read "Keyword (or KWD1|KWD2|...): "
  9326. (mapcar #'list org-todo-keywords-1))))
  9327. (concat "\\("
  9328. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  9329. "\\)\\>")))
  9330. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  9331. (regexp-quote (nth (1- (prefix-numeric-value arg))
  9332. org-todo-keywords-1)))
  9333. (t (user-error "Invalid prefix argument: %s" arg)))))
  9334. (message "%d TODO entries found"
  9335. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  9336. (defun org--deadline-or-schedule (arg type time)
  9337. "Insert DEADLINE or SCHEDULE information in current entry.
  9338. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  9339. `org-schedule' for information about ARG and TIME arguments."
  9340. (let* ((deadline? (eq type 'deadline))
  9341. (keyword (if deadline? org-deadline-string org-scheduled-string))
  9342. (log (if deadline? org-log-redeadline org-log-reschedule))
  9343. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  9344. (old-date-time (and old-date (org-time-string-to-time old-date)))
  9345. ;; Save repeater cookie from either TIME or current scheduled
  9346. ;; time stamp. We are going to insert it back at the end of
  9347. ;; the process.
  9348. (repeater (or (and (org-string-nw-p time)
  9349. ;; We use `org-repeat-re' because we need
  9350. ;; to tell the difference between a real
  9351. ;; repeater and a time delta, e.g. "+2d".
  9352. (string-match org-repeat-re time)
  9353. (match-string 1 time))
  9354. (and (org-string-nw-p old-date)
  9355. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  9356. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  9357. old-date)
  9358. (match-string 1 old-date)))))
  9359. (pcase arg
  9360. (`(4)
  9361. (if (not old-date)
  9362. (message (if deadline? "Entry had no deadline to remove"
  9363. "Entry was not scheduled"))
  9364. (when (and old-date log)
  9365. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  9366. nil old-date log))
  9367. (org-remove-timestamp-with-keyword keyword)
  9368. (message (if deadline? "Entry no longer has a deadline."
  9369. "Entry is no longer scheduled."))))
  9370. (`(16)
  9371. (save-excursion
  9372. (org-back-to-heading t)
  9373. (let ((regexp (if deadline? org-deadline-time-regexp
  9374. org-scheduled-time-regexp)))
  9375. (if (not (re-search-forward regexp (line-end-position 2) t))
  9376. (user-error (if deadline? "No deadline information to update"
  9377. "No scheduled information to update"))
  9378. (let* ((rpl0 (match-string 1))
  9379. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  9380. (msg (if deadline? "Warn starting from" "Delay until")))
  9381. (replace-match
  9382. (concat keyword
  9383. " <" rpl
  9384. (format " -%dd"
  9385. (abs (- (time-to-days
  9386. (save-match-data
  9387. (org-read-date
  9388. nil t nil msg old-date-time)))
  9389. (time-to-days old-date-time))))
  9390. ">") t t))))))
  9391. (_
  9392. (org-add-planning-info type time 'closed)
  9393. (when (and old-date
  9394. log
  9395. (not (equal old-date org-last-inserted-timestamp)))
  9396. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  9397. org-last-inserted-timestamp
  9398. old-date
  9399. log))
  9400. (when repeater
  9401. (save-excursion
  9402. (org-back-to-heading t)
  9403. (when (re-search-forward
  9404. (concat keyword " " org-last-inserted-timestamp)
  9405. (line-end-position 2)
  9406. t)
  9407. (goto-char (1- (match-end 0)))
  9408. (insert " " repeater)
  9409. (setq org-last-inserted-timestamp
  9410. (concat (substring org-last-inserted-timestamp 0 -1)
  9411. " " repeater
  9412. (substring org-last-inserted-timestamp -1))))))
  9413. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  9414. org-last-inserted-timestamp)))))
  9415. (defun org-deadline (arg &optional time)
  9416. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  9417. With one universal prefix argument, remove any deadline from the item.
  9418. With two universal prefix arguments, prompt for a warning delay.
  9419. With argument TIME, set the deadline at the corresponding date. TIME
  9420. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9421. (interactive "P")
  9422. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9423. (org-map-entries
  9424. (lambda () (org--deadline-or-schedule arg 'deadline time))
  9425. nil
  9426. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9427. 'region-start-level
  9428. 'region)
  9429. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9430. (org--deadline-or-schedule arg 'deadline time)))
  9431. (defun org-schedule (arg &optional time)
  9432. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  9433. With one universal prefix argument, remove any scheduling date from the item.
  9434. With two universal prefix arguments, prompt for a delay cookie.
  9435. With argument TIME, scheduled at the corresponding date. TIME can
  9436. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9437. (interactive "P")
  9438. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9439. (org-map-entries
  9440. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  9441. nil
  9442. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9443. 'region-start-level
  9444. 'region)
  9445. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9446. (org--deadline-or-schedule arg 'scheduled time)))
  9447. (defun org-get-scheduled-time (pom &optional inherit)
  9448. "Get the scheduled time as a time tuple, of a format suitable
  9449. for calling org-schedule with, or if there is no scheduling,
  9450. returns nil."
  9451. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  9452. (when time
  9453. (org-time-string-to-time time))))
  9454. (defun org-get-deadline-time (pom &optional inherit)
  9455. "Get the deadline as a time tuple, of a format suitable for
  9456. calling org-deadline with, or if there is no scheduling, returns
  9457. nil."
  9458. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  9459. (when time
  9460. (org-time-string-to-time time))))
  9461. (defun org-remove-timestamp-with-keyword (keyword)
  9462. "Remove all time stamps with KEYWORD in the current entry."
  9463. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  9464. beg)
  9465. (save-excursion
  9466. (org-back-to-heading t)
  9467. (setq beg (point))
  9468. (outline-next-heading)
  9469. (while (re-search-backward re beg t)
  9470. (replace-match "")
  9471. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  9472. (equal (char-before) ?\ ))
  9473. (backward-delete-char 1)
  9474. (when (string-match "^[ \t]*$" (buffer-substring
  9475. (point-at-bol) (point-at-eol)))
  9476. (delete-region (point-at-bol)
  9477. (min (point-max) (1+ (point-at-eol))))))))))
  9478. (defvar org-time-was-given) ; dynamically scoped parameter
  9479. (defvar org-end-time-was-given) ; dynamically scoped parameter
  9480. (defun org-at-planning-p ()
  9481. "Non-nil when point is on a planning info line."
  9482. ;; This is as accurate and faster than `org-element-at-point' since
  9483. ;; planning info location is fixed in the section.
  9484. (org-with-wide-buffer
  9485. (beginning-of-line)
  9486. (and (looking-at-p org-planning-line-re)
  9487. (eq (point)
  9488. (ignore-errors
  9489. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  9490. (org-back-to-heading t)
  9491. (org-with-limited-levels (org-back-to-heading t)))
  9492. (line-beginning-position 2))))))
  9493. (defun org-add-planning-info (what &optional time &rest remove)
  9494. "Insert new timestamp with keyword in the planning line.
  9495. WHAT indicates what kind of time stamp to add. It is a symbol
  9496. among `closed', `deadline', `scheduled' and nil. TIME indicates
  9497. the time to use. If none is given, the user is prompted for
  9498. a date. REMOVE indicates what kind of entries to remove. An old
  9499. WHAT entry will also be removed."
  9500. (let (org-time-was-given org-end-time-was-given default-time default-input)
  9501. (catch 'exit
  9502. (when (and (memq what '(scheduled deadline))
  9503. (or (not time)
  9504. (and (stringp time)
  9505. (string-match "^[-+]+[0-9]" time))))
  9506. ;; Try to get a default date/time from existing timestamp
  9507. (save-excursion
  9508. (org-back-to-heading t)
  9509. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  9510. (when (re-search-forward (if (eq what 'scheduled)
  9511. org-scheduled-time-regexp
  9512. org-deadline-time-regexp)
  9513. end t)
  9514. (setq ts (match-string 1)
  9515. default-time (org-time-string-to-time ts)
  9516. default-input (and ts (org-get-compact-tod ts)))))))
  9517. (when what
  9518. (setq time
  9519. (if (stringp time)
  9520. ;; This is a string (relative or absolute), set
  9521. ;; proper date.
  9522. (apply #'encode-time
  9523. (org-read-date-analyze
  9524. time default-time (decode-time default-time)))
  9525. ;; If necessary, get the time from the user
  9526. (or time (org-read-date nil 'to-time nil
  9527. (cl-case what
  9528. (deadline "DEADLINE")
  9529. (scheduled "SCHEDULED")
  9530. (otherwise nil))
  9531. default-time default-input)))))
  9532. (org-with-wide-buffer
  9533. (org-back-to-heading t)
  9534. (forward-line)
  9535. (unless (bolp) (insert "\n"))
  9536. (cond ((looking-at-p org-planning-line-re)
  9537. ;; Move to current indentation.
  9538. (skip-chars-forward " \t")
  9539. ;; Check if we have to remove something.
  9540. (dolist (type (if what (cons what remove) remove))
  9541. (save-excursion
  9542. (when (re-search-forward
  9543. (cl-case type
  9544. (closed org-closed-time-regexp)
  9545. (deadline org-deadline-time-regexp)
  9546. (scheduled org-scheduled-time-regexp)
  9547. (otherwise
  9548. (error "Invalid planning type: %s" type)))
  9549. (line-end-position) t)
  9550. ;; Delete until next keyword or end of line.
  9551. (delete-region
  9552. (match-beginning 0)
  9553. (if (re-search-forward org-keyword-time-not-clock-regexp
  9554. (line-end-position)
  9555. t)
  9556. (match-beginning 0)
  9557. (line-end-position))))))
  9558. ;; If there is nothing more to add and no more keyword
  9559. ;; is left, remove the line completely.
  9560. (if (and (looking-at-p "[ \t]*$") (not what))
  9561. (delete-region (line-beginning-position)
  9562. (line-beginning-position 2))
  9563. ;; If we removed last keyword, do not leave trailing
  9564. ;; white space at the end of line.
  9565. (let ((p (point)))
  9566. (save-excursion
  9567. (end-of-line)
  9568. (unless (= (skip-chars-backward " \t" p) 0)
  9569. (delete-region (point) (line-end-position)))))))
  9570. ((not what) (throw 'exit nil)) ; Nothing to do.
  9571. (t (insert-before-markers "\n")
  9572. (backward-char 1)
  9573. (when org-adapt-indentation
  9574. (indent-to-column (1+ (org-outline-level))))))
  9575. (when what
  9576. ;; Insert planning keyword.
  9577. (insert (cl-case what
  9578. (closed org-closed-string)
  9579. (deadline org-deadline-string)
  9580. (scheduled org-scheduled-string)
  9581. (otherwise (error "Invalid planning type: %s" what)))
  9582. " ")
  9583. ;; Insert associated timestamp.
  9584. (let ((ts (org-insert-time-stamp
  9585. time
  9586. (or org-time-was-given
  9587. (and (eq what 'closed) org-log-done-with-time))
  9588. (eq what 'closed)
  9589. nil nil (list org-end-time-was-given))))
  9590. (unless (eolp) (insert " "))
  9591. ts))))))
  9592. (defvar org-log-note-marker (make-marker)
  9593. "Marker pointing at the entry where the note is to be inserted.")
  9594. (defvar org-log-note-purpose nil)
  9595. (defvar org-log-note-state nil)
  9596. (defvar org-log-note-previous-state nil)
  9597. (defvar org-log-note-extra nil)
  9598. (defvar org-log-note-window-configuration nil)
  9599. (defvar org-log-note-return-to (make-marker))
  9600. (defvar org-log-note-effective-time nil
  9601. "Remembered current time so that dynamically scoped
  9602. `org-extend-today-until' affects timestamps in state change log")
  9603. (defvar org-log-post-message nil
  9604. "Message to be displayed after a log note has been stored.
  9605. The auto-repeater uses this.")
  9606. (defun org-add-note ()
  9607. "Add a note to the current entry.
  9608. This is done in the same way as adding a state change note."
  9609. (interactive)
  9610. (org-add-log-setup 'note))
  9611. (defun org-log-beginning (&optional create)
  9612. "Return expected start of log notes in current entry.
  9613. When optional argument CREATE is non-nil, the function creates
  9614. a drawer to store notes, if necessary. Returned position ignores
  9615. narrowing."
  9616. (org-with-wide-buffer
  9617. (let ((drawer (org-log-into-drawer)))
  9618. (cond
  9619. (drawer
  9620. (org-end-of-meta-data)
  9621. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  9622. (end (if (org-at-heading-p) (point)
  9623. (save-excursion (outline-next-heading) (point))))
  9624. (case-fold-search t))
  9625. (catch 'exit
  9626. ;; Try to find existing drawer.
  9627. (while (re-search-forward regexp end t)
  9628. (let ((element (org-element-at-point)))
  9629. (when (eq (org-element-type element) 'drawer)
  9630. (let ((cend (org-element-property :contents-end element)))
  9631. (when (and (not org-log-states-order-reversed) cend)
  9632. (goto-char cend)))
  9633. (throw 'exit nil))))
  9634. ;; No drawer found. Create one, if permitted.
  9635. (when create
  9636. (unless (bolp) (insert "\n"))
  9637. (let ((beg (point)))
  9638. (insert ":" drawer ":\n:END:\n")
  9639. (org-indent-region beg (point))
  9640. (org-flag-region
  9641. (line-end-position -1) (1- (point)) t 'org-hide-drawer))
  9642. (end-of-line -1)))))
  9643. (t
  9644. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  9645. (skip-chars-forward " \t\n")
  9646. (beginning-of-line)
  9647. (unless org-log-states-order-reversed
  9648. (org-skip-over-state-notes)
  9649. (skip-chars-backward " \t\n")
  9650. (forward-line)))))
  9651. (if (bolp) (point) (line-beginning-position 2))))
  9652. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  9653. "Set up the post command hook to take a note.
  9654. If this is about to TODO state change, the new state is expected in STATE.
  9655. HOW is an indicator what kind of note should be created.
  9656. EXTRA is additional text that will be inserted into the notes buffer."
  9657. (move-marker org-log-note-marker (point))
  9658. (setq org-log-note-purpose purpose
  9659. org-log-note-state state
  9660. org-log-note-previous-state prev-state
  9661. org-log-note-how how
  9662. org-log-note-extra extra
  9663. org-log-note-effective-time (org-current-effective-time))
  9664. (add-hook 'post-command-hook 'org-add-log-note 'append))
  9665. (defun org-skip-over-state-notes ()
  9666. "Skip past the list of State notes in an entry."
  9667. (when (ignore-errors (goto-char (org-in-item-p)))
  9668. (let* ((struct (org-list-struct))
  9669. (prevs (org-list-prevs-alist struct))
  9670. (regexp
  9671. (concat "[ \t]*- +"
  9672. (replace-regexp-in-string
  9673. " +" " +"
  9674. (org-replace-escapes
  9675. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  9676. `(("%d" . ,org-ts-regexp-inactive)
  9677. ("%D" . ,org-ts-regexp)
  9678. ("%s" . "\\(?:\"\\S-+\"\\)?")
  9679. ("%S" . "\\(?:\"\\S-+\"\\)?")
  9680. ("%t" . ,org-ts-regexp-inactive)
  9681. ("%T" . ,org-ts-regexp)
  9682. ("%u" . ".*?")
  9683. ("%U" . ".*?")))))))
  9684. (while (looking-at-p regexp)
  9685. (goto-char (or (org-list-get-next-item (point) struct prevs)
  9686. (org-list-get-item-end (point) struct)))))))
  9687. (defun org-add-log-note (&optional _purpose)
  9688. "Pop up a window for taking a note, and add this note later."
  9689. (remove-hook 'post-command-hook 'org-add-log-note)
  9690. (setq org-log-note-window-configuration (current-window-configuration))
  9691. (delete-other-windows)
  9692. (move-marker org-log-note-return-to (point))
  9693. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  9694. (goto-char org-log-note-marker)
  9695. (org-switch-to-buffer-other-window "*Org Note*")
  9696. (erase-buffer)
  9697. (if (memq org-log-note-how '(time state))
  9698. (org-store-log-note)
  9699. (let ((org-inhibit-startup t)) (org-mode))
  9700. (insert (format "# Insert note for %s.
  9701. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  9702. (cl-case org-log-note-purpose
  9703. (clock-out "stopped clock")
  9704. (done "closed todo item")
  9705. (reschedule "rescheduling")
  9706. (delschedule "no longer scheduled")
  9707. (redeadline "changing deadline")
  9708. (deldeadline "removing deadline")
  9709. (refile "refiling")
  9710. (note "this entry")
  9711. (state
  9712. (format "state change from \"%s\" to \"%s\""
  9713. (or org-log-note-previous-state "")
  9714. (or org-log-note-state "")))
  9715. (t (error "This should not happen")))))
  9716. (when org-log-note-extra (insert org-log-note-extra))
  9717. (setq-local org-finish-function 'org-store-log-note)
  9718. (run-hooks 'org-log-buffer-setup-hook)))
  9719. (defvar org-note-abort nil) ; dynamically scoped
  9720. (defun org-store-log-note ()
  9721. "Finish taking a log note, and insert it to where it belongs."
  9722. (let ((txt (prog1 (buffer-string)
  9723. (kill-buffer)))
  9724. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  9725. lines)
  9726. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  9727. (setq txt (replace-match "" t t txt)))
  9728. (when (string-match "\\s-+\\'" txt)
  9729. (setq txt (replace-match "" t t txt)))
  9730. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  9731. (when (org-string-nw-p note)
  9732. (setq note
  9733. (org-replace-escapes
  9734. note
  9735. (list (cons "%u" (user-login-name))
  9736. (cons "%U" user-full-name)
  9737. (cons "%t" (format-time-string
  9738. (org-time-stamp-format 'long 'inactive)
  9739. org-log-note-effective-time))
  9740. (cons "%T" (format-time-string
  9741. (org-time-stamp-format 'long nil)
  9742. org-log-note-effective-time))
  9743. (cons "%d" (format-time-string
  9744. (org-time-stamp-format nil 'inactive)
  9745. org-log-note-effective-time))
  9746. (cons "%D" (format-time-string
  9747. (org-time-stamp-format nil nil)
  9748. org-log-note-effective-time))
  9749. (cons "%s" (cond
  9750. ((not org-log-note-state) "")
  9751. ((string-match-p org-ts-regexp
  9752. org-log-note-state)
  9753. (format "\"[%s]\""
  9754. (substring org-log-note-state 1 -1)))
  9755. (t (format "\"%s\"" org-log-note-state))))
  9756. (cons "%S"
  9757. (cond
  9758. ((not org-log-note-previous-state) "")
  9759. ((string-match-p org-ts-regexp
  9760. org-log-note-previous-state)
  9761. (format "\"[%s]\""
  9762. (substring
  9763. org-log-note-previous-state 1 -1)))
  9764. (t (format "\"%s\""
  9765. org-log-note-previous-state)))))))
  9766. (when lines (setq note (concat note " \\\\")))
  9767. (push note lines))
  9768. (when (and lines (not org-note-abort))
  9769. (with-current-buffer (marker-buffer org-log-note-marker)
  9770. (org-with-wide-buffer
  9771. ;; Find location for the new note.
  9772. (goto-char org-log-note-marker)
  9773. (set-marker org-log-note-marker nil)
  9774. ;; Note associated to a clock is to be located right after
  9775. ;; the clock. Do not move point.
  9776. (unless (eq org-log-note-purpose 'clock-out)
  9777. (goto-char (org-log-beginning t)))
  9778. ;; Make sure point is at the beginning of an empty line.
  9779. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  9780. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  9781. ;; In an existing list, add a new item at the top level.
  9782. ;; Otherwise, indent line like a regular one.
  9783. (let ((itemp (org-in-item-p)))
  9784. (if itemp
  9785. (indent-line-to
  9786. (let ((struct (save-excursion
  9787. (goto-char itemp) (org-list-struct))))
  9788. (org-list-get-ind (org-list-get-top-point struct) struct)))
  9789. (org-indent-line)))
  9790. (insert (org-list-bullet-string "-") (pop lines))
  9791. (let ((ind (org-list-item-body-column (line-beginning-position))))
  9792. (dolist (line lines)
  9793. (insert "\n")
  9794. (indent-line-to ind)
  9795. (insert line)))
  9796. (message "Note stored")
  9797. (org-back-to-heading t))
  9798. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  9799. ;; from within `org-add-log-note' because `buffer-undo-list'
  9800. ;; is then modified outside of `org-with-remote-undo'.
  9801. (when (eq this-command 'org-agenda-todo)
  9802. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  9803. ;; Don't add undo information when called from `org-agenda-todo'.
  9804. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  9805. (set-window-configuration org-log-note-window-configuration)
  9806. (with-current-buffer (marker-buffer org-log-note-return-to)
  9807. (goto-char org-log-note-return-to))
  9808. (move-marker org-log-note-return-to nil)
  9809. (when org-log-post-message (message "%s" org-log-post-message))))
  9810. (defun org-remove-empty-drawer-at (pos)
  9811. "Remove an empty drawer at position POS.
  9812. POS may also be a marker."
  9813. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  9814. (org-with-wide-buffer
  9815. (goto-char pos)
  9816. (let ((drawer (org-element-at-point)))
  9817. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  9818. (not (org-element-property :contents-begin drawer)))
  9819. (delete-region (org-element-property :begin drawer)
  9820. (progn (goto-char (org-element-property :end drawer))
  9821. (skip-chars-backward " \r\t\n")
  9822. (forward-line)
  9823. (point))))))))
  9824. (defvar org-ts-type nil)
  9825. (defun org-sparse-tree (&optional arg type)
  9826. "Create a sparse tree, prompt for the details.
  9827. This command can create sparse trees. You first need to select the type
  9828. of match used to create the tree:
  9829. t Show all TODO entries.
  9830. T Show entries with a specific TODO keyword.
  9831. m Show entries selected by a tags/property match.
  9832. p Enter a property name and its value (both with completion on existing
  9833. names/values) and show entries with that property.
  9834. r Show entries matching a regular expression (`/' can be used as well).
  9835. b Show deadlines and scheduled items before a date.
  9836. a Show deadlines and scheduled items after a date.
  9837. d Show deadlines due within `org-deadline-warning-days'.
  9838. D Show deadlines and scheduled items between a date range."
  9839. (interactive "P")
  9840. (setq type (or type org-sparse-tree-default-date-type))
  9841. (setq org-ts-type type)
  9842. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  9843. [d]eadlines [b]efore-date [a]fter-date [D]ates range
  9844. [c]ycle through date types: %s"
  9845. (cl-case type
  9846. (all "all timestamps")
  9847. (scheduled "only scheduled")
  9848. (deadline "only deadline")
  9849. (active "only active timestamps")
  9850. (inactive "only inactive timestamps")
  9851. (closed "with a closed time-stamp")
  9852. (otherwise "scheduled/deadline")))
  9853. (let ((answer (read-char-exclusive)))
  9854. (cl-case answer
  9855. (?c
  9856. (org-sparse-tree
  9857. arg
  9858. (cadr
  9859. (memq type '(nil all scheduled deadline active inactive closed)))))
  9860. (?d (call-interactively 'org-check-deadlines))
  9861. (?b (call-interactively 'org-check-before-date))
  9862. (?a (call-interactively 'org-check-after-date))
  9863. (?D (call-interactively 'org-check-dates-range))
  9864. (?t (call-interactively 'org-show-todo-tree))
  9865. (?T (org-show-todo-tree '(4)))
  9866. (?m (call-interactively 'org-match-sparse-tree))
  9867. ((?p ?P)
  9868. (let* ((kwd (completing-read
  9869. "Property: " (mapcar #'list (org-buffer-property-keys))))
  9870. (value (completing-read
  9871. "Value: " (mapcar #'list (org-property-values kwd)))))
  9872. (unless (string-match "\\`{.*}\\'" value)
  9873. (setq value (concat "\"" value "\"")))
  9874. (org-match-sparse-tree arg (concat kwd "=" value))))
  9875. ((?r ?R ?/) (call-interactively 'org-occur))
  9876. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  9877. (defvar-local org-occur-highlights nil
  9878. "List of overlays used for occur matches.")
  9879. (defvar-local org-occur-parameters nil
  9880. "Parameters of the active org-occur calls.
  9881. This is a list, each call to org-occur pushes as cons cell,
  9882. containing the regular expression and the callback, onto the list.
  9883. The list can contain several entries if `org-occur' has been called
  9884. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  9885. will only contain one set of parameters. When the highlights are
  9886. removed (for example with `C-c C-c', or with the next edit (depending
  9887. on `org-remove-highlights-with-change'), this variable is emptied
  9888. as well.")
  9889. (defun org-occur (regexp &optional keep-previous callback)
  9890. "Make a compact tree which shows all matches of REGEXP.
  9891. The tree will show the lines where the regexp matches, and any other context
  9892. defined in `org-show-context-detail', which see.
  9893. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  9894. done by a previous call to `org-occur' will be kept, to allow stacking of
  9895. calls to this command.
  9896. Optional argument CALLBACK can be a function of no argument. In this case,
  9897. it is called with point at the end of the match, match data being set
  9898. accordingly. Current match is shown only if the return value is non-nil.
  9899. The function must neither move point nor alter narrowing."
  9900. (interactive "sRegexp: \nP")
  9901. (when (equal regexp "")
  9902. (user-error "Regexp cannot be empty"))
  9903. (unless keep-previous
  9904. (org-remove-occur-highlights nil nil t))
  9905. (push (cons regexp callback) org-occur-parameters)
  9906. (let ((cnt 0))
  9907. (save-excursion
  9908. (goto-char (point-min))
  9909. (when (or (not keep-previous) ; do not want to keep
  9910. (not org-occur-highlights)) ; no previous matches
  9911. ;; hide everything
  9912. (org-overview))
  9913. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  9914. (isearch-no-upper-case-p regexp t)
  9915. org-occur-case-fold-search)))
  9916. (while (re-search-forward regexp nil t)
  9917. (when (or (not callback)
  9918. (save-match-data (funcall callback)))
  9919. (setq cnt (1+ cnt))
  9920. (when org-highlight-sparse-tree-matches
  9921. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  9922. (org-show-context 'occur-tree)))))
  9923. (when org-remove-highlights-with-change
  9924. (add-hook 'before-change-functions 'org-remove-occur-highlights
  9925. nil 'local))
  9926. (unless org-sparse-tree-open-archived-trees
  9927. (org-hide-archived-subtrees (point-min) (point-max)))
  9928. (run-hooks 'org-occur-hook)
  9929. (when (called-interactively-p 'interactive)
  9930. (message "%d match(es) for regexp %s" cnt regexp))
  9931. cnt))
  9932. (defun org-occur-next-match (&optional n _reset)
  9933. "Function for `next-error-function' to find sparse tree matches.
  9934. N is the number of matches to move, when negative move backwards.
  9935. This function always goes back to the starting point when no
  9936. match is found."
  9937. (let* ((limit (if (< n 0) (point-min) (point-max)))
  9938. (search-func (if (< n 0)
  9939. 'previous-single-char-property-change
  9940. 'next-single-char-property-change))
  9941. (n (abs n))
  9942. (pos (point))
  9943. p1)
  9944. (catch 'exit
  9945. (while (setq p1 (funcall search-func (point) 'org-type))
  9946. (when (equal p1 limit)
  9947. (goto-char pos)
  9948. (user-error "No more matches"))
  9949. (when (equal (get-char-property p1 'org-type) 'org-occur)
  9950. (setq n (1- n))
  9951. (when (= n 0)
  9952. (goto-char p1)
  9953. (throw 'exit (point))))
  9954. (goto-char p1))
  9955. (goto-char p1)
  9956. (user-error "No more matches"))))
  9957. (defun org-highlight-new-match (beg end)
  9958. "Highlight from BEG to END and mark the highlight is an occur headline."
  9959. (let ((ov (make-overlay beg end)))
  9960. (overlay-put ov 'face 'secondary-selection)
  9961. (overlay-put ov 'org-type 'org-occur)
  9962. (push ov org-occur-highlights)))
  9963. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  9964. "Remove the occur highlights from the buffer.
  9965. BEG and END are ignored. If NOREMOVE is nil, remove this function
  9966. from the `before-change-functions' in the current buffer."
  9967. (interactive)
  9968. (unless org-inhibit-highlight-removal
  9969. (mapc #'delete-overlay org-occur-highlights)
  9970. (setq org-occur-highlights nil)
  9971. (setq org-occur-parameters nil)
  9972. (unless noremove
  9973. (remove-hook 'before-change-functions
  9974. 'org-remove-occur-highlights 'local))))
  9975. ;;;; Priorities
  9976. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]+\\)\\] ?\\)"
  9977. "Regular expression matching the priority indicator.
  9978. A priority indicator can be e.g. [#A] or [#1].
  9979. This regular expression matches these groups:
  9980. 0 : the whole match, e.g. \"TODO [#A] Hack\"
  9981. 1 : the priority cookie, e.g. \"[#A]\"
  9982. 2 : the value of the priority cookie, e.g. \"A\".")
  9983. (defun org-priority-up ()
  9984. "Increase the priority of the current item."
  9985. (interactive)
  9986. (org-priority 'up))
  9987. (defun org-priority-down ()
  9988. "Decrease the priority of the current item."
  9989. (interactive)
  9990. (org-priority 'down))
  9991. (defun org-priority (&optional action show)
  9992. "Change the priority of an item.
  9993. When called interactively with a `\\[universal-argument]' prefix,
  9994. show the priority in the minibuffer instead of changing it.
  9995. When called programmatically, ACTION can be `set', `up', `down',
  9996. or a character."
  9997. (interactive "P")
  9998. (when show
  9999. ;; Deprecation warning inserted for Org 9.2; once enough time has
  10000. ;; passed the SHOW argument should be removed.
  10001. (warn "`org-priority' called with deprecated SHOW argument"))
  10002. (if (equal action '(4))
  10003. (org-priority-show)
  10004. (unless org-priority-enable-commands
  10005. (user-error "Priority commands are disabled"))
  10006. (setq action (or action 'set))
  10007. (let ((nump (< org-priority-lowest 65))
  10008. current new news have remove)
  10009. (save-excursion
  10010. (org-back-to-heading t)
  10011. (when (looking-at org-priority-regexp)
  10012. (let ((ms (match-string 2)))
  10013. (setq current (org-priority-to-value ms)
  10014. have t)))
  10015. (cond
  10016. ((eq action 'remove)
  10017. (setq remove t new ?\ ))
  10018. ((or (eq action 'set)
  10019. (integerp action))
  10020. (if (not (eq action 'set))
  10021. (setq new action)
  10022. (setq
  10023. new
  10024. (if nump
  10025. (string-to-number
  10026. (read-string (format "Priority %s-%s, SPC to remove: "
  10027. (number-to-string org-priority-highest)
  10028. (number-to-string org-priority-lowest))))
  10029. (progn (message "Priority %c-%c, SPC to remove: "
  10030. org-priority-highest org-priority-lowest)
  10031. (save-match-data
  10032. (setq new (read-char-exclusive)))))))
  10033. (when (and (= (upcase org-priority-highest) org-priority-highest)
  10034. (= (upcase org-priority-lowest) org-priority-lowest))
  10035. (setq new (upcase new)))
  10036. (cond ((equal new ?\s) (setq remove t))
  10037. ((or (< (upcase new) org-priority-highest) (> (upcase new) org-priority-lowest))
  10038. (user-error
  10039. (if nump
  10040. "Priority must be between `%s' and `%s'"
  10041. "Priority must be between `%c' and `%c'")
  10042. org-priority-highest org-priority-lowest))))
  10043. ((eq action 'up)
  10044. (setq new (if have
  10045. (1- current) ; normal cycling
  10046. ;; last priority was empty
  10047. (if (eq last-command this-command)
  10048. org-priority-lowest ; wrap around empty to lowest
  10049. ;; default
  10050. (if org-priority-start-cycle-with-default
  10051. org-priority-default
  10052. (1- org-priority-default))))))
  10053. ((eq action 'down)
  10054. (setq new (if have
  10055. (1+ current) ; normal cycling
  10056. ;; last priority was empty
  10057. (if (eq last-command this-command)
  10058. org-priority-highest ; wrap around empty to highest
  10059. ;; default
  10060. (if org-priority-start-cycle-with-default
  10061. org-priority-default
  10062. (1+ org-priority-default))))))
  10063. (t (user-error "Invalid action")))
  10064. (when (or (< (upcase new) org-priority-highest)
  10065. (> (upcase new) org-priority-lowest))
  10066. (if (and (memq action '(up down))
  10067. (not have) (not (eq last-command this-command)))
  10068. ;; `new' is from default priority
  10069. (error
  10070. "The default can not be set, see `org-priority-default' why")
  10071. ;; normal cycling: `new' is beyond highest/lowest priority
  10072. ;; and is wrapped around to the empty priority
  10073. (setq remove t)))
  10074. ;; Numerical priorities are limited to 64, beyond that number,
  10075. ;; assume the priority cookie is a character.
  10076. (setq news (if (> new 64) (format "%c" new) (format "%s" new)))
  10077. (if have
  10078. (if remove
  10079. (replace-match "" t t nil 1)
  10080. (replace-match news t t nil 2))
  10081. (if remove
  10082. (user-error "No priority cookie found in line")
  10083. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  10084. (if (match-end 2)
  10085. (progn
  10086. (goto-char (match-end 2))
  10087. (insert " [#" news "]"))
  10088. (goto-char (match-beginning 3))
  10089. (insert "[#" news "] "))))
  10090. (org-align-tags))
  10091. (if remove
  10092. (message "Priority removed")
  10093. (message "Priority of current item set to %s" news)))))
  10094. (defalias 'org-show-priority 'org-priority-show)
  10095. (defun org-priority-show ()
  10096. "Show the priority of the current item.
  10097. This priority is composed of the main priority given with the [#A] cookies,
  10098. and by additional input from the age of a schedules or deadline entry."
  10099. (interactive)
  10100. (let ((pri (if (eq major-mode 'org-agenda-mode)
  10101. (org-get-at-bol 'priority)
  10102. (save-excursion
  10103. (save-match-data
  10104. (beginning-of-line)
  10105. (and (looking-at org-heading-regexp)
  10106. (org-get-priority (match-string 0))))))))
  10107. (message "Priority is %d" (if pri pri -1000))))
  10108. (defun org-get-priority (s)
  10109. "Find priority cookie and return priority.
  10110. S is a string against which you can match `org-priority-regexp'.
  10111. If `org-priority-get-priority-function' is set to a custom
  10112. function, use it. Otherwise process S and output the priority
  10113. value, an integer."
  10114. (save-match-data
  10115. (if (functionp org-priority-get-priority-function)
  10116. (funcall org-priority-get-priority-function s)
  10117. (if (not (string-match org-priority-regexp s))
  10118. (* 1000 (- org-priority-lowest org-priority-default))
  10119. (* 1000 (- org-priority-lowest
  10120. (org-priority-to-value (match-string 2 s))))))))
  10121. ;;;; Tags
  10122. (defvar org-agenda-archives-mode)
  10123. (defvar org-map-continue-from nil
  10124. "Position from where mapping should continue.
  10125. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  10126. (defvar org-scanner-tags nil
  10127. "The current tag list while the tags scanner is running.")
  10128. (defvar org-trust-scanner-tags nil
  10129. "Should `org-get-tags' use the tags for the scanner.
  10130. This is for internal dynamical scoping only.
  10131. When this is non-nil, the function `org-get-tags' will return the value
  10132. of `org-scanner-tags' instead of building the list by itself. This
  10133. can lead to large speed-ups when the tags scanner is used in a file with
  10134. many entries, and when the list of tags is retrieved, for example to
  10135. obtain a list of properties. Building the tags list for each entry in such
  10136. a file becomes an N^2 operation - but with this variable set, it scales
  10137. as N.")
  10138. (defvar org--matcher-tags-todo-only nil)
  10139. (defun org-scan-tags (action matcher todo-only &optional start-level)
  10140. "Scan headline tags with inheritance and produce output ACTION.
  10141. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  10142. or `agenda' to produce an entry list for an agenda view. It can also be
  10143. a Lisp form or a function that should be called at each matched headline, in
  10144. this case the return value is a list of all return values from these calls.
  10145. MATCHER is a function accepting three arguments, returning
  10146. a non-nil value whenever a given set of tags qualifies a headline
  10147. for inclusion. See `org-make-tags-matcher' for more information.
  10148. As a special case, it can also be set to t (respectively nil) in
  10149. order to match all (respectively none) headline.
  10150. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  10151. included in the output.
  10152. START-LEVEL can be a string with asterisks, reducing the scope to
  10153. headlines matching this string."
  10154. (require 'org-agenda)
  10155. (let* ((re (concat "^"
  10156. (if start-level
  10157. ;; Get the correct level to match
  10158. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  10159. org-outline-regexp)
  10160. " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
  10161. " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
  10162. (props (list 'face 'default
  10163. 'done-face 'org-agenda-done
  10164. 'undone-face 'default
  10165. 'mouse-face 'highlight
  10166. 'org-not-done-regexp org-not-done-regexp
  10167. 'org-todo-regexp org-todo-regexp
  10168. 'org-complex-heading-regexp org-complex-heading-regexp
  10169. 'help-echo
  10170. (format "mouse-2 or RET jump to Org file %S"
  10171. (abbreviate-file-name
  10172. (or (buffer-file-name (buffer-base-buffer))
  10173. (buffer-name (buffer-base-buffer)))))))
  10174. (org-map-continue-from nil)
  10175. lspos tags tags-list
  10176. (tags-alist (list (cons 0 org-file-tags)))
  10177. (llast 0) rtn rtn1 level category i txt
  10178. todo marker entry priority
  10179. ts-date ts-date-type ts-date-pair)
  10180. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  10181. (setq action (list 'lambda nil action)))
  10182. (save-excursion
  10183. (goto-char (point-min))
  10184. (when (eq action 'sparse-tree)
  10185. (org-overview)
  10186. (org-remove-occur-highlights))
  10187. (while (let (case-fold-search)
  10188. (re-search-forward re nil t))
  10189. (setq org-map-continue-from nil)
  10190. (catch :skip
  10191. ;; Ignore closing parts of inline tasks.
  10192. (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
  10193. (throw :skip t))
  10194. (setq todo (and (match-end 1) (match-string-no-properties 1)))
  10195. (setq tags (and (match-end 4) (org-trim (match-string-no-properties 4))))
  10196. (goto-char (setq lspos (match-beginning 0)))
  10197. (setq level (org-reduced-level (org-outline-level))
  10198. category (org-get-category))
  10199. (when (eq action 'agenda)
  10200. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  10201. ts-date (car ts-date-pair)
  10202. ts-date-type (cdr ts-date-pair)))
  10203. (setq i llast llast level)
  10204. ;; remove tag lists from same and sublevels
  10205. (while (>= i level)
  10206. (when (setq entry (assoc i tags-alist))
  10207. (setq tags-alist (delete entry tags-alist)))
  10208. (setq i (1- i)))
  10209. ;; add the next tags
  10210. (when tags
  10211. (setq tags (org-split-string tags ":")
  10212. tags-alist
  10213. (cons (cons level tags) tags-alist)))
  10214. ;; compile tags for current headline
  10215. (setq tags-list
  10216. (if org-use-tag-inheritance
  10217. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  10218. tags)
  10219. org-scanner-tags tags-list)
  10220. (when org-use-tag-inheritance
  10221. (setcdr (car tags-alist)
  10222. (mapcar (lambda (x)
  10223. (setq x (copy-sequence x))
  10224. (org-add-prop-inherited x))
  10225. (cdar tags-alist))))
  10226. (when (and tags org-use-tag-inheritance
  10227. (or (not (eq t org-use-tag-inheritance))
  10228. org-tags-exclude-from-inheritance))
  10229. ;; Selective inheritance, remove uninherited ones.
  10230. (setcdr (car tags-alist)
  10231. (org-remove-uninherited-tags (cdar tags-alist))))
  10232. (when (and
  10233. ;; eval matcher only when the todo condition is OK
  10234. (and (or (not todo-only) (member todo org-todo-keywords-1))
  10235. (if (functionp matcher)
  10236. (let ((case-fold-search t) (org-trust-scanner-tags t))
  10237. (funcall matcher todo tags-list level))
  10238. matcher))
  10239. ;; Call the skipper, but return t if it does not
  10240. ;; skip, so that the `and' form continues evaluating.
  10241. (progn
  10242. (unless (eq action 'sparse-tree) (org-agenda-skip))
  10243. t)
  10244. ;; Check if timestamps are deselecting this entry
  10245. (or (not todo-only)
  10246. (and (member todo org-todo-keywords-1)
  10247. (or (not org-agenda-tags-todo-honor-ignore-options)
  10248. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  10249. ;; select this headline
  10250. (cond
  10251. ((eq action 'sparse-tree)
  10252. (and org-highlight-sparse-tree-matches
  10253. (org-get-heading) (match-end 0)
  10254. (org-highlight-new-match
  10255. (match-beginning 1) (match-end 1)))
  10256. (org-show-context 'tags-tree))
  10257. ((eq action 'agenda)
  10258. (setq txt (org-agenda-format-item
  10259. ""
  10260. (concat
  10261. (if (eq org-tags-match-list-sublevels 'indented)
  10262. (make-string (1- level) ?.) "")
  10263. (org-get-heading))
  10264. (make-string level ?\s)
  10265. category
  10266. tags-list)
  10267. priority (org-get-priority txt))
  10268. (goto-char lspos)
  10269. (setq marker (org-agenda-new-marker))
  10270. (org-add-props txt props
  10271. 'org-marker marker 'org-hd-marker marker 'org-category category
  10272. 'todo-state todo
  10273. 'ts-date ts-date
  10274. 'priority priority
  10275. 'type (concat "tagsmatch" ts-date-type))
  10276. (push txt rtn))
  10277. ((functionp action)
  10278. (setq org-map-continue-from nil)
  10279. (save-excursion
  10280. (setq rtn1 (funcall action))
  10281. (push rtn1 rtn)))
  10282. (t (user-error "Invalid action")))
  10283. ;; if we are to skip sublevels, jump to end of subtree
  10284. (unless org-tags-match-list-sublevels
  10285. (org-end-of-subtree t)
  10286. (backward-char 1))))
  10287. ;; Get the correct position from where to continue
  10288. (if org-map-continue-from
  10289. (goto-char org-map-continue-from)
  10290. (and (= (point) lspos) (end-of-line 1)))))
  10291. (when (and (eq action 'sparse-tree)
  10292. (not org-sparse-tree-open-archived-trees))
  10293. (org-hide-archived-subtrees (point-min) (point-max)))
  10294. (nreverse rtn)))
  10295. (defun org-remove-uninherited-tags (tags)
  10296. "Remove all tags that are not inherited from the list TAGS."
  10297. (cond
  10298. ((eq org-use-tag-inheritance t)
  10299. (if org-tags-exclude-from-inheritance
  10300. (org-delete-all org-tags-exclude-from-inheritance tags)
  10301. tags))
  10302. ((not org-use-tag-inheritance) nil)
  10303. ((stringp org-use-tag-inheritance)
  10304. (delq nil (mapcar
  10305. (lambda (x)
  10306. (if (and (string-match org-use-tag-inheritance x)
  10307. (not (member x org-tags-exclude-from-inheritance)))
  10308. x nil))
  10309. tags)))
  10310. ((listp org-use-tag-inheritance)
  10311. (delq nil (mapcar
  10312. (lambda (x)
  10313. (if (member x org-use-tag-inheritance) x nil))
  10314. tags)))))
  10315. (defun org-match-sparse-tree (&optional todo-only match)
  10316. "Create a sparse tree according to tags string MATCH.
  10317. MATCH is a string with match syntax. It can contain a selection
  10318. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  10319. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  10320. those. See the manual for details.
  10321. If optional argument TODO-ONLY is non-nil, only select lines that
  10322. are also TODO tasks."
  10323. (interactive "P")
  10324. (org-agenda-prepare-buffers (list (current-buffer)))
  10325. (let ((org--matcher-tags-todo-only todo-only))
  10326. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  10327. org--matcher-tags-todo-only)))
  10328. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  10329. (defvar org-cached-props nil)
  10330. (defun org-cached-entry-get (pom property)
  10331. (if (or (eq t org-use-property-inheritance)
  10332. (and (stringp org-use-property-inheritance)
  10333. (let ((case-fold-search t))
  10334. (string-match-p org-use-property-inheritance property)))
  10335. (and (listp org-use-property-inheritance)
  10336. (member-ignore-case property org-use-property-inheritance)))
  10337. ;; Caching is not possible, check it directly.
  10338. (org-entry-get pom property 'inherit)
  10339. ;; Get all properties, so we can do complicated checks easily.
  10340. (cdr (assoc-string property
  10341. (or org-cached-props
  10342. (setq org-cached-props (org-entry-properties pom)))
  10343. t))))
  10344. (defun org-global-tags-completion-table (&optional files)
  10345. "Return the list of all tags in all agenda buffer/files.
  10346. Optional FILES argument is a list of files which can be used
  10347. instead of the agenda files."
  10348. (save-excursion
  10349. (org-uniquify
  10350. (delq nil
  10351. (apply #'append
  10352. (mapcar
  10353. (lambda (file)
  10354. (set-buffer (find-file-noselect file))
  10355. (org--tag-add-to-alist
  10356. (org-get-buffer-tags)
  10357. (mapcar (lambda (x)
  10358. (and (stringp (car-safe x))
  10359. (list (car-safe x))))
  10360. org-current-tag-alist)))
  10361. (if (car-safe files) files
  10362. (org-agenda-files))))))))
  10363. (defun org-make-tags-matcher (match)
  10364. "Create the TAGS/TODO matcher form for the selection string MATCH.
  10365. Returns a cons of the selection string MATCH and a function
  10366. implementing the matcher.
  10367. The matcher is to be called at an Org entry, with point on the
  10368. headline, and returns non-nil if the entry matches the selection
  10369. string MATCH. It must be called with three arguments: the TODO
  10370. keyword at the entry (or nil if none), the list of all tags at
  10371. the entry including inherited ones and the reduced level of the
  10372. headline. Additionally, the category of the entry, if any, must
  10373. be specified as the text property `org-category' on the headline.
  10374. This function sets the variable `org--matcher-tags-todo-only' to
  10375. a non-nil value if the matcher restricts matching to TODO
  10376. entries, otherwise it is not touched.
  10377. See also `org-scan-tags'."
  10378. (unless match
  10379. ;; Get a new match request, with completion against the global
  10380. ;; tags table and the local tags in current buffer.
  10381. (let ((org-last-tags-completion-table
  10382. (org--tag-add-to-alist
  10383. (org-get-buffer-tags)
  10384. (org-global-tags-completion-table))))
  10385. (setq match
  10386. (completing-read
  10387. "Match: "
  10388. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  10389. (let ((match0 match)
  10390. (re (concat
  10391. "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
  10392. "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
  10393. "\\([<>=]\\{1,2\\}\\)"
  10394. "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
  10395. "\\|" org-tag-re "\\)"))
  10396. (start 0)
  10397. tagsmatch todomatch tagsmatcher todomatcher)
  10398. ;; Expand group tags.
  10399. (setq match (org-tags-expand match))
  10400. ;; Check if there is a TODO part of this match, which would be the
  10401. ;; part after a "/". To make sure that this slash is not part of
  10402. ;; a property value to be matched against, we also check that
  10403. ;; there is no / after that slash. First, find the last slash.
  10404. (let ((s 0))
  10405. (while (string-match "/+" match s)
  10406. (setq start (match-beginning 0))
  10407. (setq s (match-end 0))))
  10408. (if (and (string-match "/+" match start)
  10409. (not (string-match-p "\"" match start)))
  10410. ;; Match contains also a TODO-matching request.
  10411. (progn
  10412. (setq tagsmatch (substring match 0 (match-beginning 0)))
  10413. (setq todomatch (substring match (match-end 0)))
  10414. (when (string-prefix-p "!" todomatch)
  10415. (setq org--matcher-tags-todo-only t)
  10416. (setq todomatch (substring todomatch 1)))
  10417. (when (string-match "\\`\\s-*\\'" todomatch)
  10418. (setq todomatch nil)))
  10419. ;; Only matching tags.
  10420. (setq tagsmatch match)
  10421. (setq todomatch nil))
  10422. ;; Make the tags matcher.
  10423. (when (org-string-nw-p tagsmatch)
  10424. (let ((orlist nil)
  10425. (orterms (org-split-string tagsmatch "|"))
  10426. term)
  10427. (while (setq term (pop orterms))
  10428. (while (and (equal (substring term -1) "\\") orterms)
  10429. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  10430. (while (string-match re term)
  10431. (let* ((rest (substring term (match-end 0)))
  10432. (minus (and (match-end 1)
  10433. (equal (match-string 1 term) "-")))
  10434. (tag (save-match-data
  10435. (replace-regexp-in-string
  10436. "\\\\-" "-" (match-string 2 term))))
  10437. (regexp (eq (string-to-char tag) ?{))
  10438. (levelp (match-end 4))
  10439. (propp (match-end 5))
  10440. (mm
  10441. (cond
  10442. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  10443. (levelp
  10444. `(,(org-op-to-function (match-string 3 term))
  10445. level
  10446. ,(string-to-number (match-string 4 term))))
  10447. (propp
  10448. (let* ((gv (pcase (upcase (match-string 5 term))
  10449. ("CATEGORY"
  10450. '(get-text-property (point) 'org-category))
  10451. ("TODO" 'todo)
  10452. (p `(org-cached-entry-get nil ,p))))
  10453. (pv (match-string 7 term))
  10454. (regexp (eq (string-to-char pv) ?{))
  10455. (strp (eq (string-to-char pv) ?\"))
  10456. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  10457. (po (org-op-to-function (match-string 6 term)
  10458. (if timep 'time strp))))
  10459. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  10460. (when timep (setq pv (org-matcher-time pv)))
  10461. (cond ((and regexp (eq po '/=))
  10462. `(not (string-match ,pv (or ,gv ""))))
  10463. (regexp `(string-match ,pv (or ,gv "")))
  10464. (strp `(,po (or ,gv "") ,pv))
  10465. (t
  10466. `(,po
  10467. (string-to-number (or ,gv ""))
  10468. ,(string-to-number pv))))))
  10469. (t `(member ,tag tags-list)))))
  10470. (push (if minus `(not ,mm) mm) tagsmatcher)
  10471. (setq term rest)))
  10472. (push `(and ,@tagsmatcher) orlist)
  10473. (setq tagsmatcher nil))
  10474. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  10475. ;; Make the TODO matcher.
  10476. (when (org-string-nw-p todomatch)
  10477. (let ((orlist nil))
  10478. (dolist (term (org-split-string todomatch "|"))
  10479. (while (string-match re term)
  10480. (let* ((minus (and (match-end 1)
  10481. (equal (match-string 1 term) "-")))
  10482. (kwd (match-string 2 term))
  10483. (regexp (eq (string-to-char kwd) ?{))
  10484. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  10485. `(equal todo ,kwd))))
  10486. (push (if minus `(not ,mm) mm) todomatcher))
  10487. (setq term (substring term (match-end 0))))
  10488. (push (if (> (length todomatcher) 1)
  10489. (cons 'and todomatcher)
  10490. (car todomatcher))
  10491. orlist)
  10492. (setq todomatcher nil))
  10493. (setq todomatcher (cons 'or orlist))))
  10494. ;; Return the string and function of the matcher. If no
  10495. ;; tags-specific or todo-specific matcher exists, match
  10496. ;; everything.
  10497. (let ((matcher (if (and tagsmatcher todomatcher)
  10498. `(and ,tagsmatcher ,todomatcher)
  10499. (or tagsmatcher todomatcher t))))
  10500. (when org--matcher-tags-todo-only
  10501. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  10502. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  10503. (defun org--tags-expand-group (group tag-groups expanded)
  10504. "Recursively Expand all tags in GROUP, according to TAG-GROUPS.
  10505. TAG-GROUPS is the list of groups used for expansion. EXPANDED is
  10506. an accumulator used in recursive calls."
  10507. (dolist (tag group)
  10508. (unless (member tag expanded)
  10509. (let ((group (assoc tag tag-groups)))
  10510. (push tag expanded)
  10511. (when group
  10512. (setq expanded
  10513. (org--tags-expand-group (cdr group) tag-groups expanded))))))
  10514. expanded)
  10515. (defun org-tags-expand (match &optional single-as-list downcased)
  10516. "Expand group tags in MATCH.
  10517. This replaces every group tag in MATCH with a regexp tag search.
  10518. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  10519. will be replaced like this:
  10520. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10521. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10522. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10523. Replacing by a regexp preserves the structure of the match.
  10524. E.g., this expansion
  10525. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  10526. will match anything tagged with \"Lab\" and \"Home\", or tagged
  10527. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"Home\".
  10528. A group tag in MATCH can contain regular expressions of its own.
  10529. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  10530. will be replaced like this:
  10531. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  10532. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  10533. assumed to be a single group tag, and the function will return
  10534. the list of tags in this group.
  10535. When DOWNCASED is non-nil, expand downcased TAGS."
  10536. (unless (org-string-nw-p match) (error "Invalid match tag: %S" match))
  10537. (let ((tag-groups
  10538. (let ((g (or org-tag-groups-alist-for-agenda org-tag-groups-alist)))
  10539. (if (not downcased) g
  10540. (mapcar (lambda (s) (mapcar #'downcase s)) g)))))
  10541. (cond
  10542. (single-as-list (org--tags-expand-group (list match) tag-groups nil))
  10543. (org-group-tags
  10544. (let* ((case-fold-search t)
  10545. (tag-syntax org-mode-syntax-table)
  10546. (group-keys (mapcar #'car tag-groups))
  10547. (key-regexp (concat "\\([+-]?\\)" (regexp-opt group-keys 'words)))
  10548. (return-match (if downcased (downcase match) match)))
  10549. ;; Mark regexp-expressions in the match-expression so that we
  10550. ;; do not replace them later on.
  10551. (let ((s 0))
  10552. (while (string-match "{.+?}" return-match s)
  10553. (setq s (match-end 0))
  10554. (add-text-properties
  10555. (match-beginning 0) (match-end 0) '(regexp t) return-match)))
  10556. ;; @ and _ are allowed as word-components in tags.
  10557. (modify-syntax-entry ?@ "w" tag-syntax)
  10558. (modify-syntax-entry ?_ "w" tag-syntax)
  10559. ;; For each tag token found in MATCH, compute a regexp and it
  10560. (with-syntax-table tag-syntax
  10561. (replace-regexp-in-string
  10562. key-regexp
  10563. (lambda (m)
  10564. (if (get-text-property (match-beginning 2) 'regexp m)
  10565. m ;regexp tag: ignore
  10566. (let* ((operator (match-string 1 m))
  10567. (tag-token (let ((tag (match-string 2 m)))
  10568. (list (if downcased (downcase tag) tag))))
  10569. regexp-tags regular-tags)
  10570. ;; Partition tags between regexp and regular tags.
  10571. ;; Remove curly bracket syntax from regexp tags.
  10572. (dolist (tag (org--tags-expand-group tag-token tag-groups nil))
  10573. (save-match-data
  10574. (if (string-match "{\\(.+?\\)}" tag)
  10575. (push (match-string 1 tag) regexp-tags)
  10576. (push tag regular-tags))))
  10577. ;; Replace tag token by the appropriate regexp.
  10578. ;; Regular tags need to be regexp-quoted, whereas
  10579. ;; regexp-tags are inserted as-is.
  10580. (let ((regular (regexp-opt regular-tags))
  10581. (regexp (mapconcat #'identity regexp-tags "\\|")))
  10582. (concat operator
  10583. (cond
  10584. ((null regular-tags) (format "{%s}" regexp))
  10585. ((null regexp-tags) (format "{\\<%s\\>}" regular))
  10586. (t (format "{\\<%s\\>\\|%s}" regular regexp))))))))
  10587. return-match
  10588. t t))))
  10589. (t match))))
  10590. (defun org-op-to-function (op &optional stringp)
  10591. "Turn an operator into the appropriate function."
  10592. (setq op
  10593. (cond
  10594. ((equal op "<" ) '(< org-string< org-time<))
  10595. ((equal op ">" ) '(> org-string> org-time>))
  10596. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  10597. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  10598. ((member op '("=" "==")) '(= string= org-time=))
  10599. ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
  10600. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  10601. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  10602. (defvar org-tags-overlay (make-overlay 1 1))
  10603. (delete-overlay org-tags-overlay)
  10604. (defun org-add-prop-inherited (s)
  10605. (add-text-properties 0 (length s) '(inherited t) s)
  10606. s)
  10607. (defun org-toggle-tag (tag &optional onoff)
  10608. "Toggle the tag TAG for the current line.
  10609. If ONOFF is `on' or `off', don't toggle but set to this state."
  10610. (save-excursion
  10611. (org-back-to-heading t)
  10612. (let ((current
  10613. ;; Reverse the tags list so any new tag is appended to the
  10614. ;; current list of tags.
  10615. (nreverse (org-get-tags nil t)))
  10616. res)
  10617. (pcase onoff
  10618. (`off (setq current (delete tag current)))
  10619. ((or `on (guard (not (member tag current))))
  10620. (setq res t)
  10621. (cl-pushnew tag current :test #'equal))
  10622. (_ (setq current (delete tag current))))
  10623. (org-set-tags (nreverse current))
  10624. res)))
  10625. (defun org--align-tags-here (to-col)
  10626. "Align tags on the current headline to TO-COL.
  10627. Assume point is on a headline. Preserve point when aligning
  10628. tags."
  10629. (when (org-match-line org-tag-line-re)
  10630. (let* ((tags-start (match-beginning 1))
  10631. (blank-start (save-excursion
  10632. (goto-char tags-start)
  10633. (skip-chars-backward " \t")
  10634. (point)))
  10635. (new (max (if (>= to-col 0) to-col
  10636. (- (abs to-col) (string-width (match-string 1))))
  10637. ;; Introduce at least one space after the heading
  10638. ;; or the stars.
  10639. (save-excursion
  10640. (goto-char blank-start)
  10641. (1+ (current-column)))))
  10642. (current
  10643. (save-excursion (goto-char tags-start) (current-column)))
  10644. (origin (point-marker))
  10645. (column (current-column))
  10646. (in-blank? (and (> origin blank-start) (<= origin tags-start))))
  10647. (when (/= new current)
  10648. (delete-region blank-start tags-start)
  10649. (goto-char blank-start)
  10650. (let ((indent-tabs-mode nil)) (indent-to new))
  10651. ;; Try to move back to original position. If point was in the
  10652. ;; blanks before the tags, ORIGIN marker is of no use because
  10653. ;; it now points to BLANK-START. Use COLUMN instead.
  10654. (if in-blank? (org-move-to-column column) (goto-char origin))))))
  10655. (defun org-set-tags-command (&optional arg)
  10656. "Set the tags for the current visible entry.
  10657. When called with `\\[universal-argument]' prefix argument ARG, \
  10658. realign all tags
  10659. in the current buffer.
  10660. When called with `\\[universal-argument] \\[universal-argument]' prefix argument, \
  10661. unconditionally do not
  10662. offer the fast tag selection interface.
  10663. If a region is active, set tags in the region according to the
  10664. setting of `org-loop-over-headlines-in-active-region'.
  10665. This function is for interactive use only;
  10666. in Lisp code use `org-set-tags' instead."
  10667. (interactive "P")
  10668. (let ((org-use-fast-tag-selection
  10669. (unless (equal '(16) arg) org-use-fast-tag-selection)))
  10670. (cond
  10671. ((equal '(4) arg) (org-align-tags t))
  10672. ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
  10673. (let (org-loop-over-headlines-in-active-region) ; hint: infinite recursion.
  10674. (org-map-entries
  10675. #'org-set-tags-command
  10676. nil
  10677. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  10678. 'region-start-level
  10679. 'region)
  10680. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
  10681. (t
  10682. (save-excursion
  10683. (org-back-to-heading)
  10684. (let* ((all-tags (org-get-tags))
  10685. (table (setq org-last-tags-completion-table
  10686. (org--tag-add-to-alist
  10687. (and org-complete-tags-always-offer-all-agenda-tags
  10688. (org-global-tags-completion-table
  10689. (org-agenda-files)))
  10690. (or org-current-tag-alist (org-get-buffer-tags)))))
  10691. (current-tags
  10692. (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
  10693. all-tags))
  10694. (inherited-tags
  10695. (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
  10696. all-tags))
  10697. (tags
  10698. (replace-regexp-in-string
  10699. ;; Ignore all forbidden characters in tags.
  10700. "[^[:alnum:]_@#%]+" ":"
  10701. (if (or (eq t org-use-fast-tag-selection)
  10702. (and org-use-fast-tag-selection
  10703. (delq nil (mapcar #'cdr table))))
  10704. (org-fast-tag-selection
  10705. current-tags
  10706. inherited-tags
  10707. table
  10708. (and org-fast-tag-selection-include-todo org-todo-key-alist))
  10709. (let ((org-add-colon-after-tag-completion (< 1 (length table))))
  10710. (org-trim (completing-read
  10711. "Tags: "
  10712. #'org-tags-completion-function
  10713. nil nil (org-make-tag-string current-tags)
  10714. 'org-tags-history)))))))
  10715. (org-set-tags tags)))))
  10716. ;; `save-excursion' may not replace the point at the right
  10717. ;; position.
  10718. (when (save-excursion (skip-chars-backward "*") (bolp))
  10719. (forward-char))))
  10720. (defun org-align-tags (&optional all)
  10721. "Align tags in current entry.
  10722. When optional argument ALL is non-nil, align all tags in the
  10723. visible part of the buffer."
  10724. (let ((get-indent-column
  10725. (lambda ()
  10726. (let ((offset (if (bound-and-true-p org-indent-mode)
  10727. (* (1- org-indent-indentation-per-level)
  10728. (1- (org-current-level)))
  10729. 0)))
  10730. (+ org-tags-column
  10731. (if (> org-tags-column 0) (- offset) offset))))))
  10732. (if (and (not all) (org-at-heading-p))
  10733. (org--align-tags-here (funcall get-indent-column))
  10734. (save-excursion
  10735. (if all
  10736. (progn
  10737. (goto-char (point-min))
  10738. (while (re-search-forward org-tag-line-re nil t)
  10739. (org--align-tags-here (funcall get-indent-column))))
  10740. (org-back-to-heading t)
  10741. (org--align-tags-here (funcall get-indent-column)))))))
  10742. (defun org-set-tags (tags)
  10743. "Set the tags of the current entry to TAGS, replacing current tags.
  10744. TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
  10745. If TAGS is nil or the empty string, all tags are removed.
  10746. This function assumes point is on a headline."
  10747. (org-with-wide-buffer
  10748. (let ((tags (pcase tags
  10749. ((pred listp) tags)
  10750. ((pred stringp) (split-string (org-trim tags) ":" t))
  10751. (_ (error "Invalid tag specification: %S" tags))))
  10752. (old-tags (org-get-tags nil t))
  10753. (tags-change? nil))
  10754. (when (functionp org-tags-sort-function)
  10755. (setq tags (sort tags org-tags-sort-function)))
  10756. (setq tags-change? (not (equal tags old-tags)))
  10757. (when tags-change?
  10758. ;; Delete previous tags and any trailing white space.
  10759. (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
  10760. (line-end-position)))
  10761. (skip-chars-backward " \t")
  10762. (delete-region (point) (line-end-position))
  10763. ;; Deleting white spaces may break an otherwise empty headline.
  10764. ;; Re-introduce one space in this case.
  10765. (unless (org-at-heading-p) (insert " "))
  10766. (when tags
  10767. (save-excursion (insert " " (org-make-tag-string tags)))
  10768. ;; When text is being inserted on an invisible region
  10769. ;; boundary, it can be inadvertently sucked into
  10770. ;; invisibility.
  10771. (unless (org-invisible-p (line-beginning-position))
  10772. (org-flag-region (point) (line-end-position) nil 'outline))))
  10773. ;; Align tags, if any.
  10774. (when tags (org-align-tags))
  10775. (when tags-change? (run-hooks 'org-after-tags-change-hook)))))
  10776. (defun org-change-tag-in-region (beg end tag off)
  10777. "Add or remove TAG for each entry in the region.
  10778. This works in the agenda, and also in an Org buffer."
  10779. (interactive
  10780. (list (region-beginning) (region-end)
  10781. (let ((org-last-tags-completion-table
  10782. (if (derived-mode-p 'org-mode)
  10783. (org--tag-add-to-alist
  10784. (org-get-buffer-tags)
  10785. (org-global-tags-completion-table))
  10786. (org-global-tags-completion-table))))
  10787. (completing-read
  10788. "Tag: " 'org-tags-completion-function nil nil nil
  10789. 'org-tags-history))
  10790. (progn
  10791. (message "[s]et or [r]emove? ")
  10792. (equal (read-char-exclusive) ?r))))
  10793. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10794. (let ((agendap (equal major-mode 'org-agenda-mode))
  10795. l1 l2 m buf pos newhead (cnt 0))
  10796. (goto-char end)
  10797. (setq l2 (1- (org-current-line)))
  10798. (goto-char beg)
  10799. (setq l1 (org-current-line))
  10800. (cl-loop for l from l1 to l2 do
  10801. (org-goto-line l)
  10802. (setq m (get-text-property (point) 'org-hd-marker))
  10803. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  10804. (and agendap m))
  10805. (setq buf (if agendap (marker-buffer m) (current-buffer))
  10806. pos (if agendap m (point)))
  10807. (with-current-buffer buf
  10808. (save-excursion
  10809. (save-restriction
  10810. (goto-char pos)
  10811. (setq cnt (1+ cnt))
  10812. (org-toggle-tag tag (if off 'off 'on))
  10813. (setq newhead (org-get-heading)))))
  10814. (and agendap (org-agenda-change-all-lines newhead m))))
  10815. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  10816. (defun org-tags-completion-function (string _predicate &optional flag)
  10817. "Complete tag STRING.
  10818. FLAG specifies the type of completion operation to perform. This
  10819. function is passed as a collection function to `completing-read',
  10820. which see."
  10821. (let ((completion-ignore-case nil) ;tags are case-sensitive
  10822. (confirm (lambda (x) (stringp (car x))))
  10823. (prefix ""))
  10824. (when (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  10825. (setq prefix (match-string 1 string))
  10826. (setq string (match-string 2 string)))
  10827. (pcase flag
  10828. (`t (all-completions string org-last-tags-completion-table confirm))
  10829. (`lambda (assoc string org-last-tags-completion-table)) ;exact match?
  10830. (`nil
  10831. (pcase (try-completion string org-last-tags-completion-table confirm)
  10832. ((and completion (pred stringp))
  10833. (concat prefix
  10834. completion
  10835. (if (and org-add-colon-after-tag-completion
  10836. (assoc completion org-last-tags-completion-table))
  10837. ":"
  10838. "")))
  10839. (completion completion)))
  10840. (_ nil))))
  10841. (defun org-fast-tag-insert (kwd tags face &optional end)
  10842. "Insert KWD, and the TAGS, the latter with face FACE.
  10843. Also insert END."
  10844. (insert (format "%-12s" (concat kwd ":"))
  10845. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  10846. (or end "")))
  10847. (defun org-fast-tag-show-exit (flag)
  10848. (save-excursion
  10849. (org-goto-line 3)
  10850. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  10851. (replace-match ""))
  10852. (when flag
  10853. (end-of-line 1)
  10854. (org-move-to-column (- (window-width) 19) t)
  10855. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  10856. (defun org-set-current-tags-overlay (current prefix)
  10857. "Add an overlay to CURRENT tag with PREFIX."
  10858. (let ((s (org-make-tag-string current)))
  10859. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  10860. (org-overlay-display org-tags-overlay (concat prefix s))))
  10861. (defvar org-last-tag-selection-key nil)
  10862. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  10863. "Fast tag selection with single keys.
  10864. CURRENT is the current list of tags in the headline, INHERITED is the
  10865. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  10866. possibly with grouping information. TODO-TABLE is a similar table with
  10867. TODO keywords, should these have keys assigned to them.
  10868. If the keys are nil, a-z are automatically assigned.
  10869. Returns the new tags string, or nil to not change the current settings."
  10870. (let* ((fulltable (append table todo-table))
  10871. (maxlen (if (null fulltable) 0
  10872. (apply #'max
  10873. (mapcar (lambda (x)
  10874. (if (stringp (car x)) (string-width (car x))
  10875. 0))
  10876. fulltable))))
  10877. (buf (current-buffer))
  10878. (expert (eq org-fast-tag-selection-single-key 'expert))
  10879. (buffer-tags nil)
  10880. (fwidth (+ maxlen 3 1 3))
  10881. (ncol (/ (- (window-width) 4) fwidth))
  10882. (i-face 'org-done)
  10883. (c-face 'org-todo)
  10884. tg cnt e c char c1 c2 ntable tbl rtn
  10885. ov-start ov-end ov-prefix
  10886. (exit-after-next org-fast-tag-selection-single-key)
  10887. (done-keywords org-done-keywords)
  10888. groups ingroup intaggroup)
  10889. (save-excursion
  10890. (beginning-of-line)
  10891. (if (looking-at org-tag-line-re)
  10892. (setq ov-start (match-beginning 1)
  10893. ov-end (match-end 1)
  10894. ov-prefix "")
  10895. (setq ov-start (1- (point-at-eol))
  10896. ov-end (1+ ov-start))
  10897. (skip-chars-forward "^\n\r")
  10898. (setq ov-prefix
  10899. (concat
  10900. (buffer-substring (1- (point)) (point))
  10901. (if (> (current-column) org-tags-column)
  10902. " "
  10903. (make-string (- org-tags-column (current-column)) ?\ ))))))
  10904. (move-overlay org-tags-overlay ov-start ov-end)
  10905. (save-excursion
  10906. (save-window-excursion
  10907. (if expert
  10908. (set-buffer (get-buffer-create " *Org tags*"))
  10909. (delete-other-windows)
  10910. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  10911. (org-switch-to-buffer-other-window " *Org tags*"))
  10912. (erase-buffer)
  10913. (setq-local org-done-keywords done-keywords)
  10914. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  10915. (org-fast-tag-insert "Current" current c-face "\n\n")
  10916. (org-fast-tag-show-exit exit-after-next)
  10917. (org-set-current-tags-overlay current ov-prefix)
  10918. (setq tbl fulltable char ?a cnt 0)
  10919. (while (setq e (pop tbl))
  10920. (cond
  10921. ((eq (car e) :startgroup)
  10922. (push '() groups) (setq ingroup t)
  10923. (unless (zerop cnt)
  10924. (setq cnt 0)
  10925. (insert "\n"))
  10926. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  10927. ((eq (car e) :endgroup)
  10928. (setq ingroup nil cnt 0)
  10929. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  10930. ((eq (car e) :startgrouptag)
  10931. (setq intaggroup t)
  10932. (unless (zerop cnt)
  10933. (setq cnt 0)
  10934. (insert "\n"))
  10935. (insert "[ "))
  10936. ((eq (car e) :endgrouptag)
  10937. (setq intaggroup nil cnt 0)
  10938. (insert "]\n"))
  10939. ((equal e '(:newline))
  10940. (unless (zerop cnt)
  10941. (setq cnt 0)
  10942. (insert "\n")
  10943. (setq e (car tbl))
  10944. (while (equal (car tbl) '(:newline))
  10945. (insert "\n")
  10946. (setq tbl (cdr tbl)))))
  10947. ((equal e '(:grouptags)) (insert " : "))
  10948. (t
  10949. (setq tg (copy-sequence (car e)) c2 nil)
  10950. (if (cdr e)
  10951. (setq c (cdr e))
  10952. ;; automatically assign a character.
  10953. (setq c1 (string-to-char
  10954. (downcase (substring
  10955. tg (if (= (string-to-char tg) ?@) 1 0)))))
  10956. (if (or (rassoc c1 ntable) (rassoc c1 table))
  10957. (while (or (rassoc char ntable) (rassoc char table))
  10958. (setq char (1+ char)))
  10959. (setq c2 c1))
  10960. (setq c (or c2 char)))
  10961. (when ingroup (push tg (car groups)))
  10962. (setq tg (org-add-props tg nil 'face
  10963. (cond
  10964. ((not (assoc tg table))
  10965. (org-get-todo-face tg))
  10966. ((member tg current) c-face)
  10967. ((member tg inherited) i-face))))
  10968. (when (equal (caar tbl) :grouptags)
  10969. (org-add-props tg nil 'face 'org-tag-group))
  10970. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  10971. (insert "[" c "] " tg (make-string
  10972. (- fwidth 4 (length tg)) ?\ ))
  10973. (push (cons tg c) ntable)
  10974. (when (= (cl-incf cnt) ncol)
  10975. (unless (memq (caar tbl) '(:endgroup :endgrouptag))
  10976. (insert "\n")
  10977. (when (or ingroup intaggroup) (insert " ")))
  10978. (setq cnt 0)))))
  10979. (setq ntable (nreverse ntable))
  10980. (insert "\n")
  10981. (goto-char (point-min))
  10982. (unless expert (org-fit-window-to-buffer))
  10983. (setq rtn
  10984. (catch 'exit
  10985. (while t
  10986. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  10987. (if (not groups) "no " "")
  10988. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  10989. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  10990. (setq org-last-tag-selection-key c)
  10991. (cond
  10992. ((= c ?\r) (throw 'exit t))
  10993. ((= c ?!)
  10994. (setq groups (not groups))
  10995. (goto-char (point-min))
  10996. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  10997. ((= c ?\C-c)
  10998. (if (not expert)
  10999. (org-fast-tag-show-exit
  11000. (setq exit-after-next (not exit-after-next)))
  11001. (setq expert nil)
  11002. (delete-other-windows)
  11003. (set-window-buffer (split-window-vertically) " *Org tags*")
  11004. (org-switch-to-buffer-other-window " *Org tags*")
  11005. (org-fit-window-to-buffer)))
  11006. ((or (= c ?\C-g)
  11007. (and (= c ?q) (not (rassoc c ntable))))
  11008. (delete-overlay org-tags-overlay)
  11009. (setq quit-flag t))
  11010. ((= c ?\ )
  11011. (setq current nil)
  11012. (when exit-after-next (setq exit-after-next 'now)))
  11013. ((= c ?\t)
  11014. (condition-case nil
  11015. (setq tg (completing-read
  11016. "Tag: "
  11017. (or buffer-tags
  11018. (with-current-buffer buf
  11019. (setq buffer-tags
  11020. (org-get-buffer-tags))))))
  11021. (quit (setq tg "")))
  11022. (when (string-match "\\S-" tg)
  11023. (cl-pushnew (list tg) buffer-tags :test #'equal)
  11024. (if (member tg current)
  11025. (setq current (delete tg current))
  11026. (push tg current)))
  11027. (when exit-after-next (setq exit-after-next 'now)))
  11028. ((setq e (rassoc c todo-table) tg (car e))
  11029. (with-current-buffer buf
  11030. (save-excursion (org-todo tg)))
  11031. (when exit-after-next (setq exit-after-next 'now)))
  11032. ((setq e (rassoc c ntable) tg (car e))
  11033. (if (member tg current)
  11034. (setq current (delete tg current))
  11035. (cl-loop for g in groups do
  11036. (when (member tg g)
  11037. (dolist (x g) (setq current (delete x current)))))
  11038. (push tg current))
  11039. (when exit-after-next (setq exit-after-next 'now))))
  11040. ;; Create a sorted list
  11041. (setq current
  11042. (sort current
  11043. (lambda (a b)
  11044. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  11045. (when (eq exit-after-next 'now) (throw 'exit t))
  11046. (goto-char (point-min))
  11047. (beginning-of-line 2)
  11048. (delete-region (point) (point-at-eol))
  11049. (org-fast-tag-insert "Current" current c-face)
  11050. (org-set-current-tags-overlay current ov-prefix)
  11051. (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
  11052. (while (re-search-forward tag-re nil t)
  11053. (let ((tag (match-string 1)))
  11054. (add-text-properties
  11055. (match-beginning 1) (match-end 1)
  11056. (list 'face
  11057. (cond
  11058. ((member tag current) c-face)
  11059. ((member tag inherited) i-face)
  11060. (t (get-text-property (match-beginning 1) '
  11061. face))))))))
  11062. (goto-char (point-min)))))
  11063. (delete-overlay org-tags-overlay)
  11064. (if rtn
  11065. (mapconcat 'identity current ":")
  11066. nil)))))
  11067. (defun org-make-tag-string (tags)
  11068. "Return string associated to TAGS.
  11069. TAGS is a list of strings."
  11070. (if (null tags) ""
  11071. (format ":%s:" (mapconcat #'identity tags ":"))))
  11072. (defun org--get-local-tags ()
  11073. "Return list of tags for the current headline.
  11074. Assume point is at the beginning of the headline."
  11075. (and (looking-at org-tag-line-re)
  11076. (split-string (match-string-no-properties 2) ":" t)))
  11077. (defun org-get-tags (&optional pos local)
  11078. "Get the list of tags specified in the current headline.
  11079. When argument POS is non-nil, retrieve tags for headline at POS.
  11080. According to `org-use-tag-inheritance', tags may be inherited
  11081. from parent headlines, and from the whole document, through
  11082. `org-file-tags'. In this case, the returned list of tags
  11083. contains tags in this order: file tags, tags inherited from
  11084. parent headlines, local tags.
  11085. However, when optional argument LOCAL is non-nil, only return
  11086. tags specified at the headline.
  11087. Inherited tags have the `inherited' text property."
  11088. (if (and org-trust-scanner-tags
  11089. (or (not pos) (eq pos (point)))
  11090. (not local))
  11091. org-scanner-tags
  11092. (org-with-point-at (or pos (point))
  11093. (unless (org-before-first-heading-p)
  11094. (org-back-to-heading t)
  11095. (let ((ltags (org--get-local-tags)) itags)
  11096. (if (or local (not org-use-tag-inheritance)) ltags
  11097. (while (org-up-heading-safe)
  11098. (setq itags (append (mapcar #'org-add-prop-inherited
  11099. (org--get-local-tags))
  11100. itags)))
  11101. (setq itags (append org-file-tags itags))
  11102. (delete-dups
  11103. (append (org-remove-uninherited-tags itags) ltags))))))))
  11104. (defun org-get-buffer-tags ()
  11105. "Get a table of all tags used in the buffer, for completion."
  11106. (org-with-point-at 1
  11107. (let (tags)
  11108. (while (re-search-forward org-tag-line-re nil t)
  11109. (setq tags (nconc (split-string (match-string-no-properties 2) ":")
  11110. tags)))
  11111. (mapcar #'list (delete-dups (append org-file-tags tags))))))
  11112. ;;;; The mapping API
  11113. (defvar org-agenda-skip-comment-trees)
  11114. (defvar org-agenda-skip-function)
  11115. (defun org-map-entries (func &optional match scope &rest skip)
  11116. "Call FUNC at each headline selected by MATCH in SCOPE.
  11117. FUNC is a function or a lisp form. The function will be called without
  11118. arguments, with the cursor positioned at the beginning of the headline.
  11119. The return values of all calls to the function will be collected and
  11120. returned as a list.
  11121. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  11122. does not need to preserve point. After evaluation, the cursor will be
  11123. moved to the end of the line (presumably of the headline of the
  11124. processed entry) and search continues from there. Under some
  11125. circumstances, this may not produce the wanted results. For example,
  11126. if you have removed (e.g. archived) the current (sub)tree it could
  11127. mean that the next entry will be skipped entirely. In such cases, you
  11128. can specify the position from where search should continue by making
  11129. FUNC set the variable `org-map-continue-from' to the desired buffer
  11130. position.
  11131. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  11132. Only headlines that are matched by this query will be considered during
  11133. the iteration. When MATCH is nil or t, all headlines will be
  11134. visited by the iteration.
  11135. SCOPE determines the scope of this command. It can be any of:
  11136. nil The current buffer, respecting the restriction if any
  11137. tree The subtree started with the entry at point
  11138. region The entries within the active region, if any
  11139. region-start-level
  11140. The entries within the active region, but only those at
  11141. the same level than the first one.
  11142. file The current buffer, without restriction
  11143. file-with-archives
  11144. The current buffer, and any archives associated with it
  11145. agenda All agenda files
  11146. agenda-with-archives
  11147. All agenda files with any archive files associated with them
  11148. \(file1 file2 ...)
  11149. If this is a list, all files in the list will be scanned
  11150. The remaining args are treated as settings for the skipping facilities of
  11151. the scanner. The following items can be given here:
  11152. archive skip trees with the archive tag
  11153. comment skip trees with the COMMENT keyword
  11154. function or Emacs Lisp form:
  11155. will be used as value for `org-agenda-skip-function', so
  11156. whenever the function returns a position, FUNC will not be
  11157. called for that entry and search will continue from the
  11158. position returned
  11159. If your function needs to retrieve the tags including inherited tags
  11160. at the *current* entry, you can use the value of the variable
  11161. `org-scanner-tags' which will be much faster than getting the value
  11162. with `org-get-tags'. If your function gets properties with
  11163. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  11164. to t around the call to `org-entry-properties' to get the same speedup.
  11165. Note that if your function moves around to retrieve tags and properties at
  11166. a *different* entry, you cannot use these techniques."
  11167. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  11168. (not (org-region-active-p)))
  11169. (let* ((org-agenda-archives-mode nil) ; just to make sure
  11170. (org-agenda-skip-archived-trees (memq 'archive skip))
  11171. (org-agenda-skip-comment-trees (memq 'comment skip))
  11172. (org-agenda-skip-function
  11173. (car (org-delete-all '(comment archive) skip)))
  11174. (org-tags-match-list-sublevels t)
  11175. (start-level (eq scope 'region-start-level))
  11176. matcher res
  11177. org-todo-keywords-for-agenda
  11178. org-done-keywords-for-agenda
  11179. org-todo-keyword-alist-for-agenda
  11180. org-tag-alist-for-agenda
  11181. org--matcher-tags-todo-only)
  11182. (cond
  11183. ((eq match t) (setq matcher t))
  11184. ((eq match nil) (setq matcher t))
  11185. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  11186. (save-excursion
  11187. (save-restriction
  11188. (cond ((eq scope 'tree)
  11189. (org-back-to-heading t)
  11190. (org-narrow-to-subtree)
  11191. (setq scope nil))
  11192. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  11193. (org-region-active-p))
  11194. ;; If needed, set start-level to a string like "2"
  11195. (when start-level
  11196. (save-excursion
  11197. (goto-char (region-beginning))
  11198. (unless (org-at-heading-p) (outline-next-heading))
  11199. (setq start-level (org-current-level))))
  11200. (narrow-to-region (region-beginning)
  11201. (save-excursion
  11202. (goto-char (region-end))
  11203. (unless (and (bolp) (org-at-heading-p))
  11204. (outline-next-heading))
  11205. (point)))
  11206. (setq scope nil)))
  11207. (if (not scope)
  11208. (progn
  11209. (org-agenda-prepare-buffers
  11210. (and buffer-file-name (list buffer-file-name)))
  11211. (setq res
  11212. (org-scan-tags
  11213. func matcher org--matcher-tags-todo-only start-level)))
  11214. ;; Get the right scope
  11215. (cond
  11216. ((and scope (listp scope) (symbolp (car scope)))
  11217. (setq scope (eval scope)))
  11218. ((eq scope 'agenda)
  11219. (setq scope (org-agenda-files t)))
  11220. ((eq scope 'agenda-with-archives)
  11221. (setq scope (org-agenda-files t))
  11222. (setq scope (org-add-archive-files scope)))
  11223. ((eq scope 'file)
  11224. (setq scope (and buffer-file-name (list buffer-file-name))))
  11225. ((eq scope 'file-with-archives)
  11226. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  11227. (org-agenda-prepare-buffers scope)
  11228. (dolist (file scope)
  11229. (with-current-buffer (org-find-base-buffer-visiting file)
  11230. (org-with-wide-buffer
  11231. (goto-char (point-min))
  11232. (setq res
  11233. (append
  11234. res
  11235. (org-scan-tags
  11236. func matcher org--matcher-tags-todo-only)))))))))
  11237. res)))
  11238. ;;; Properties API
  11239. (defconst org-special-properties
  11240. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  11241. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  11242. "The special properties valid in Org mode.
  11243. These are properties that are not defined in the property drawer,
  11244. but in some other way.")
  11245. (defconst org-default-properties
  11246. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  11247. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  11248. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  11249. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  11250. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  11251. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  11252. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  11253. "Some properties that are used by Org mode for various purposes.
  11254. Being in this list makes sure that they are offered for completion.")
  11255. (defun org--valid-property-p (property)
  11256. "Non-nil when string PROPERTY is a valid property name."
  11257. (not
  11258. (or (equal property "")
  11259. (string-match-p "\\s-" property))))
  11260. (defun org--update-property-plist (key val props)
  11261. "Associate KEY to VAL in alist PROPS.
  11262. Modifications are made by side-effect. Return new alist."
  11263. (let* ((appending (string= (substring key -1) "+"))
  11264. (key (if appending (substring key 0 -1) key))
  11265. (old (assoc-string key props t)))
  11266. (if (not old) (cons (cons key val) props)
  11267. (setcdr old (if appending (concat (cdr old) " " val) val))
  11268. props)))
  11269. (defun org-get-property-block (&optional beg force)
  11270. "Return the (beg . end) range of the body of the property drawer.
  11271. BEG is the beginning of the current subtree or the beginning of
  11272. the document if before the first headline. If it is not given,
  11273. it will be found. If the drawer does not exist, create it if
  11274. FORCE is non-nil, or return nil."
  11275. (org-with-wide-buffer
  11276. (let ((beg (cond (beg (goto-char beg))
  11277. ((or (not (featurep 'org-inlinetask))
  11278. (org-inlinetask-in-task-p))
  11279. (org-back-to-heading-or-point-min t) (point))
  11280. (t (org-with-limited-levels
  11281. (org-back-to-heading-or-point-min t))
  11282. (point)))))
  11283. ;; Move point to its position according to its positional rules.
  11284. (cond ((org-before-first-heading-p)
  11285. (while (and (org-at-comment-p) (bolp)) (forward-line)))
  11286. (t (forward-line)
  11287. (when (looking-at-p org-planning-line-re) (forward-line))))
  11288. (cond ((looking-at org-property-drawer-re)
  11289. (forward-line)
  11290. (cons (point) (progn (goto-char (match-end 0))
  11291. (line-beginning-position))))
  11292. (force
  11293. (goto-char beg)
  11294. (org-insert-property-drawer)
  11295. (let ((pos (save-excursion (re-search-forward org-property-drawer-re)
  11296. (line-beginning-position))))
  11297. (cons pos pos)))))))
  11298. (defun org-at-property-block-p ()
  11299. "Return t when point is at the first line of a property drawer.
  11300. The property drawer is validated according to its positional
  11301. rules using `org-get-property-block'."
  11302. (save-excursion
  11303. (beginning-of-line)
  11304. (and (looking-at org-property-start-re)
  11305. (forward-line)
  11306. (let ((property-drawer (org-get-property-block)))
  11307. (and property-drawer
  11308. (= (point) (car property-drawer)))))))
  11309. (defun org-at-property-p ()
  11310. "Non-nil when point is inside a property drawer.
  11311. See `org-property-re' for match data, if applicable."
  11312. (save-excursion
  11313. (beginning-of-line)
  11314. (and (looking-at org-property-re)
  11315. (let ((property-drawer (save-match-data (org-get-property-block))))
  11316. (and property-drawer
  11317. (>= (point) (car property-drawer))
  11318. (< (point) (cdr property-drawer)))))))
  11319. (defun org-property-action ()
  11320. "Do an action on properties."
  11321. (interactive)
  11322. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  11323. (let ((c (read-char-exclusive)))
  11324. (cl-case c
  11325. (?s (call-interactively #'org-set-property))
  11326. (?d (call-interactively #'org-delete-property))
  11327. (?D (call-interactively #'org-delete-property-globally))
  11328. (?c (call-interactively #'org-compute-property-at-point))
  11329. (otherwise (user-error "No such property action %c" c)))))
  11330. (defun org-inc-effort ()
  11331. "Increment the value of the effort property in the current entry."
  11332. (interactive)
  11333. (org-set-effort t))
  11334. (defvar org-clock-effort) ; Defined in org-clock.el.
  11335. (defvar org-clock-current-task) ; Defined in org-clock.el.
  11336. (defun org-set-effort (&optional increment value)
  11337. "Set the effort property of the current entry.
  11338. If INCREMENT is non-nil, set the property to the next allowed
  11339. value. Otherwise, if optional argument VALUE is provided, use
  11340. it. Eventually, prompt for the new value if none of the previous
  11341. variables is set."
  11342. (interactive "P")
  11343. (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
  11344. (current (org-entry-get nil org-effort-property))
  11345. (value
  11346. (cond
  11347. (increment
  11348. (unless allowed (user-error "Allowed effort values are not set"))
  11349. (or (cl-caadr (member (list current) allowed))
  11350. (user-error "Unknown value %S among allowed values" current)))
  11351. (value
  11352. (if (stringp value) value
  11353. (error "Invalid effort value: %S" value)))
  11354. (t
  11355. (let ((must-match
  11356. (and allowed
  11357. (not (get-text-property 0 'org-unrestricted
  11358. (caar allowed))))))
  11359. (completing-read "Effort: " allowed nil must-match))))))
  11360. ;; Test whether the value can be interpreted as a duration before
  11361. ;; inserting it in the buffer:
  11362. (org-duration-to-minutes value)
  11363. ;; Maybe update the effort value:
  11364. (unless (equal current value)
  11365. (org-entry-put nil org-effort-property value))
  11366. (org-refresh-property '((effort . identity)
  11367. (effort-minutes . org-duration-to-minutes))
  11368. value)
  11369. (when (equal (org-get-heading t t t t)
  11370. (bound-and-true-p org-clock-current-task))
  11371. (setq org-clock-effort value)
  11372. (org-clock-update-mode-line))
  11373. (message "%s is now %s" org-effort-property value)))
  11374. (defun org-entry-properties (&optional pom which)
  11375. "Get all properties of the current entry.
  11376. When POM is a buffer position, get all properties from the entry
  11377. there instead.
  11378. This includes the TODO keyword, the tags, time strings for
  11379. deadline, scheduled, and clocking, and any additional properties
  11380. defined in the entry.
  11381. If WHICH is nil or `all', get all properties. If WHICH is
  11382. `special' or `standard', only get that subclass. If WHICH is
  11383. a string, only get that property.
  11384. Return value is an alist. Keys are properties, as upcased
  11385. strings."
  11386. (org-with-point-at pom
  11387. (when (and (derived-mode-p 'org-mode)
  11388. (org-back-to-heading-or-point-min t))
  11389. (catch 'exit
  11390. (let* ((beg (point))
  11391. (specific (and (stringp which) (upcase which)))
  11392. (which (cond ((not specific) which)
  11393. ((member specific org-special-properties) 'special)
  11394. (t 'standard)))
  11395. props)
  11396. ;; Get the special properties, like TODO and TAGS.
  11397. (when (memq which '(nil all special))
  11398. (when (or (not specific) (string= specific "CLOCKSUM"))
  11399. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  11400. (when clocksum
  11401. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  11402. props)))
  11403. (when specific (throw 'exit props)))
  11404. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  11405. (let ((clocksumt (get-text-property (point)
  11406. :org-clock-minutes-today)))
  11407. (when clocksumt
  11408. (push (cons "CLOCKSUM_T"
  11409. (org-duration-from-minutes clocksumt))
  11410. props)))
  11411. (when specific (throw 'exit props)))
  11412. (when (or (not specific) (string= specific "ITEM"))
  11413. (let ((case-fold-search nil))
  11414. (when (looking-at org-complex-heading-regexp)
  11415. (push (cons "ITEM"
  11416. (let ((title (match-string-no-properties 4)))
  11417. (if (org-string-nw-p title)
  11418. (org-remove-tabs title)
  11419. "")))
  11420. props)))
  11421. (when specific (throw 'exit props)))
  11422. (when (or (not specific) (string= specific "TODO"))
  11423. (let ((case-fold-search nil))
  11424. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  11425. (push (cons "TODO" (match-string-no-properties 2)) props)))
  11426. (when specific (throw 'exit props)))
  11427. (when (or (not specific) (string= specific "PRIORITY"))
  11428. (push (cons "PRIORITY"
  11429. (if (looking-at org-priority-regexp)
  11430. (match-string-no-properties 2)
  11431. (char-to-string org-priority-default)))
  11432. props)
  11433. (when specific (throw 'exit props)))
  11434. (when (or (not specific) (string= specific "FILE"))
  11435. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  11436. props)
  11437. (when specific (throw 'exit props)))
  11438. (when (or (not specific) (string= specific "TAGS"))
  11439. (let ((tags (org-get-tags nil t)))
  11440. (when tags
  11441. (push (cons "TAGS" (org-make-tag-string tags))
  11442. props)))
  11443. (when specific (throw 'exit props)))
  11444. (when (or (not specific) (string= specific "ALLTAGS"))
  11445. (let ((tags (org-get-tags)))
  11446. (when tags
  11447. (push (cons "ALLTAGS" (org-make-tag-string tags))
  11448. props)))
  11449. (when specific (throw 'exit props)))
  11450. (when (or (not specific) (string= specific "BLOCKED"))
  11451. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  11452. (when specific (throw 'exit props)))
  11453. (when (or (not specific)
  11454. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  11455. (forward-line)
  11456. (when (looking-at-p org-planning-line-re)
  11457. (end-of-line)
  11458. (let ((bol (line-beginning-position))
  11459. ;; Backward compatibility: time keywords used to
  11460. ;; be configurable (before 8.3). Make sure we
  11461. ;; get the correct keyword.
  11462. (key-assoc `(("CLOSED" . ,org-closed-string)
  11463. ("DEADLINE" . ,org-deadline-string)
  11464. ("SCHEDULED" . ,org-scheduled-string))))
  11465. (dolist (pair (if specific (list (assoc specific key-assoc))
  11466. key-assoc))
  11467. (save-excursion
  11468. (when (search-backward (cdr pair) bol t)
  11469. (goto-char (match-end 0))
  11470. (skip-chars-forward " \t")
  11471. (and (looking-at org-ts-regexp-both)
  11472. (push (cons (car pair)
  11473. (match-string-no-properties 0))
  11474. props)))))))
  11475. (when specific (throw 'exit props)))
  11476. (when (or (not specific)
  11477. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  11478. (let ((find-ts
  11479. (lambda (end ts)
  11480. ;; Fix next time-stamp before END. TS is the
  11481. ;; list of time-stamps found so far.
  11482. (let ((ts ts)
  11483. (regexp (cond
  11484. ((string= specific "TIMESTAMP")
  11485. org-ts-regexp)
  11486. ((string= specific "TIMESTAMP_IA")
  11487. org-ts-regexp-inactive)
  11488. ((assoc "TIMESTAMP_IA" ts)
  11489. org-ts-regexp)
  11490. ((assoc "TIMESTAMP" ts)
  11491. org-ts-regexp-inactive)
  11492. (t org-ts-regexp-both))))
  11493. (catch 'next
  11494. (while (re-search-forward regexp end t)
  11495. (backward-char)
  11496. (let ((object (org-element-context)))
  11497. ;; Accept to match timestamps in node
  11498. ;; properties, too.
  11499. (when (memq (org-element-type object)
  11500. '(node-property timestamp))
  11501. (let ((type
  11502. (org-element-property :type object)))
  11503. (cond
  11504. ((and (memq type '(active active-range))
  11505. (not (equal specific "TIMESTAMP_IA")))
  11506. (unless (assoc "TIMESTAMP" ts)
  11507. (push (cons "TIMESTAMP"
  11508. (org-element-property
  11509. :raw-value object))
  11510. ts)
  11511. (when specific (throw 'exit ts))))
  11512. ((and (memq type '(inactive inactive-range))
  11513. (not (string= specific "TIMESTAMP")))
  11514. (unless (assoc "TIMESTAMP_IA" ts)
  11515. (push (cons "TIMESTAMP_IA"
  11516. (org-element-property
  11517. :raw-value object))
  11518. ts)
  11519. (when specific (throw 'exit ts))))))
  11520. ;; Both timestamp types are found,
  11521. ;; move to next part.
  11522. (when (= (length ts) 2) (throw 'next ts)))))
  11523. ts)))))
  11524. (goto-char beg)
  11525. ;; First look for timestamps within headline.
  11526. (let ((ts (funcall find-ts (line-end-position) nil)))
  11527. (if (= (length ts) 2) (setq props (nconc ts props))
  11528. ;; Then find timestamps in the section, skipping
  11529. ;; planning line.
  11530. (let ((end (save-excursion (outline-next-heading))))
  11531. (forward-line)
  11532. (when (looking-at-p org-planning-line-re) (forward-line))
  11533. (setq props (nconc (funcall find-ts end ts) props))))))))
  11534. ;; Get the standard properties, like :PROP:.
  11535. (when (memq which '(nil all standard))
  11536. ;; If we are looking after a specific property, delegate
  11537. ;; to `org-entry-get', which is faster. However, make an
  11538. ;; exception for "CATEGORY", since it can be also set
  11539. ;; through keywords (i.e. #+CATEGORY).
  11540. (if (and specific (not (equal specific "CATEGORY")))
  11541. (let ((value (org-entry-get beg specific nil t)))
  11542. (throw 'exit (and value (list (cons specific value)))))
  11543. (let ((range (org-get-property-block beg)))
  11544. (when range
  11545. (let ((end (cdr range)) seen-base)
  11546. (goto-char (car range))
  11547. ;; Unlike to `org--update-property-plist', we
  11548. ;; handle the case where base values is found
  11549. ;; after its extension. We also forbid standard
  11550. ;; properties to be named as special properties.
  11551. (while (re-search-forward org-property-re end t)
  11552. (let* ((key (upcase (match-string-no-properties 2)))
  11553. (extendp (string-match-p "\\+\\'" key))
  11554. (key-base (if extendp (substring key 0 -1) key))
  11555. (value (match-string-no-properties 3)))
  11556. (cond
  11557. ((member-ignore-case key-base org-special-properties))
  11558. (extendp
  11559. (setq props
  11560. (org--update-property-plist key value props)))
  11561. ((member key seen-base))
  11562. (t (push key seen-base)
  11563. (let ((p (assoc-string key props t)))
  11564. (if p (setcdr p (concat value " " (cdr p)))
  11565. (push (cons key value) props))))))))))))
  11566. (unless (assoc "CATEGORY" props)
  11567. (push (cons "CATEGORY" (org-get-category beg)) props)
  11568. (when (string= specific "CATEGORY") (throw 'exit props)))
  11569. ;; Return value.
  11570. props)))))
  11571. (defun org--property-local-values (property literal-nil)
  11572. "Return value for PROPERTY in current entry.
  11573. Value is a list whose car is the base value for PROPERTY and cdr
  11574. a list of accumulated values. Return nil if neither is found in
  11575. the entry. Also return nil when PROPERTY is set to \"nil\",
  11576. unless LITERAL-NIL is non-nil."
  11577. (let ((range (org-get-property-block)))
  11578. (when range
  11579. (goto-char (car range))
  11580. (let* ((case-fold-search t)
  11581. (end (cdr range))
  11582. (value
  11583. ;; Base value.
  11584. (save-excursion
  11585. (let ((v (and (re-search-forward
  11586. (org-re-property property nil t) end t)
  11587. (match-string-no-properties 3))))
  11588. (list (if literal-nil v (org-not-nil v)))))))
  11589. ;; Find additional values.
  11590. (let* ((property+ (org-re-property (concat property "+") nil t)))
  11591. (while (re-search-forward property+ end t)
  11592. (push (match-string-no-properties 3) value)))
  11593. ;; Return final values.
  11594. (and (not (equal value '(nil))) (nreverse value))))))
  11595. (defun org--property-global-or-keyword-value (property literal-nil)
  11596. "Return value for PROPERTY as defined by global properties or by keyword.
  11597. Return value is a string. Return nil if property is not set
  11598. globally or by keyword. Also return nil when PROPERTY is set to
  11599. \"nil\", unless LITERAL-NIL is non-nil."
  11600. (let ((global
  11601. (cdr (or (assoc-string property org-keyword-properties t)
  11602. (assoc-string property org-global-properties t)
  11603. (assoc-string property org-global-properties-fixed t)))))
  11604. (if literal-nil global (org-not-nil global))))
  11605. (defun org-entry-get (pom property &optional inherit literal-nil)
  11606. "Get value of PROPERTY for entry or content at point-or-marker POM.
  11607. If INHERIT is non-nil and the entry does not have the property,
  11608. then also check higher levels of the hierarchy. If INHERIT is
  11609. the symbol `selective', use inheritance only if the setting in
  11610. `org-use-property-inheritance' selects PROPERTY for inheritance.
  11611. If the property is present but empty, the return value is the
  11612. empty string. If the property is not present at all, nil is
  11613. returned. In any other case, return the value as a string.
  11614. Search is case-insensitive.
  11615. If LITERAL-NIL is set, return the string value \"nil\" as
  11616. a string, do not interpret it as the list atom nil. This is used
  11617. for inheritance when a \"nil\" value can supersede a non-nil
  11618. value higher up the hierarchy."
  11619. (org-with-point-at pom
  11620. (cond
  11621. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  11622. ;; We need a special property. Use `org-entry-properties' to
  11623. ;; retrieve it, but specify the wanted property.
  11624. (cdr (assoc-string property (org-entry-properties nil property))))
  11625. ((and inherit
  11626. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  11627. (org-entry-get-with-inheritance property literal-nil))
  11628. (t
  11629. (let* ((local (org--property-local-values property literal-nil))
  11630. (value (and local (mapconcat #'identity (delq nil local) " "))))
  11631. (if literal-nil value (org-not-nil value)))))))
  11632. (defun org-property-or-variable-value (var &optional inherit)
  11633. "Check if there is a property fixing the value of VAR.
  11634. If yes, return this value. If not, return the current value of the variable."
  11635. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  11636. (if (and prop (stringp prop) (string-match "\\S-" prop))
  11637. (read prop)
  11638. (symbol-value var))))
  11639. (defun org-entry-delete (pom property)
  11640. "Delete PROPERTY from entry at point-or-marker POM.
  11641. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  11642. non-nil when a property was removed."
  11643. (org-with-point-at pom
  11644. (pcase (org-get-property-block)
  11645. (`(,begin . ,origin)
  11646. (let* ((end (copy-marker origin))
  11647. (re (org-re-property
  11648. (concat (regexp-quote property) "\\+?") t t)))
  11649. (goto-char begin)
  11650. (while (re-search-forward re end t)
  11651. (delete-region (match-beginning 0) (line-beginning-position 2)))
  11652. ;; If drawer is empty, remove it altogether.
  11653. (when (= begin end)
  11654. (delete-region (line-beginning-position 0)
  11655. (line-beginning-position 2)))
  11656. ;; Return non-nil if some property was removed.
  11657. (prog1 (/= end origin) (set-marker end nil))))
  11658. (_ nil))))
  11659. ;; Multi-values properties are properties that contain multiple values
  11660. ;; These values are assumed to be single words, separated by whitespace.
  11661. (defun org-entry-add-to-multivalued-property (pom property value)
  11662. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  11663. (let* ((old (org-entry-get pom property))
  11664. (values (and old (split-string old))))
  11665. (setq value (org-entry-protect-space value))
  11666. (unless (member value values)
  11667. (setq values (append values (list value)))
  11668. (org-entry-put pom property (mapconcat #'identity values " ")))))
  11669. (defun org-entry-remove-from-multivalued-property (pom property value)
  11670. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  11671. (let* ((old (org-entry-get pom property))
  11672. (values (and old (split-string old))))
  11673. (setq value (org-entry-protect-space value))
  11674. (when (member value values)
  11675. (setq values (delete value values))
  11676. (org-entry-put pom property (mapconcat #'identity values " ")))))
  11677. (defun org-entry-member-in-multivalued-property (pom property value)
  11678. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  11679. (let* ((old (org-entry-get pom property))
  11680. (values (and old (split-string old))))
  11681. (setq value (org-entry-protect-space value))
  11682. (member value values)))
  11683. (defun org-entry-get-multivalued-property (pom property)
  11684. "Return a list of values in a multivalued property."
  11685. (let* ((value (org-entry-get pom property))
  11686. (values (and value (split-string value))))
  11687. (mapcar #'org-entry-restore-space values)))
  11688. (defun org-entry-put-multivalued-property (pom property &rest values)
  11689. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  11690. VALUES should be a list of strings. Spaces will be protected."
  11691. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  11692. (let* ((value (org-entry-get pom property))
  11693. (values (and value (split-string value))))
  11694. (mapcar #'org-entry-restore-space values)))
  11695. (defun org-entry-protect-space (s)
  11696. "Protect spaces and newline in string S."
  11697. (while (string-match " " s)
  11698. (setq s (replace-match "%20" t t s)))
  11699. (while (string-match "\n" s)
  11700. (setq s (replace-match "%0A" t t s)))
  11701. s)
  11702. (defun org-entry-restore-space (s)
  11703. "Restore spaces and newline in string S."
  11704. (while (string-match "%20" s)
  11705. (setq s (replace-match " " t t s)))
  11706. (while (string-match "%0A" s)
  11707. (setq s (replace-match "\n" t t s)))
  11708. s)
  11709. (defvar org-entry-property-inherited-from (make-marker)
  11710. "Marker pointing to the entry from where a property was inherited.
  11711. Each call to `org-entry-get-with-inheritance' will set this marker to the
  11712. location of the entry where the inheritance search matched. If there was
  11713. no match, the marker will point nowhere.
  11714. Note that also `org-entry-get' calls this function, if the INHERIT flag
  11715. is set.")
  11716. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  11717. "Get PROPERTY of entry or content at point, search higher levels if needed.
  11718. The search will stop at the first ancestor which has the property defined.
  11719. If the value found is \"nil\", return nil to show that the property
  11720. should be considered as undefined (this is the meaning of nil here).
  11721. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  11722. (move-marker org-entry-property-inherited-from nil)
  11723. (org-with-wide-buffer
  11724. (let (value)
  11725. (catch 'exit
  11726. (while t
  11727. (let ((v (org--property-local-values property literal-nil)))
  11728. (when v
  11729. (setq value
  11730. (concat (mapconcat #'identity (delq nil v) " ")
  11731. (and value " ")
  11732. value)))
  11733. (cond
  11734. ((car v)
  11735. (org-back-to-heading-or-point-min t)
  11736. (move-marker org-entry-property-inherited-from (point))
  11737. (throw 'exit nil))
  11738. ((org-up-heading-or-point-min))
  11739. (t
  11740. (let ((global (org--property-global-or-keyword-value property literal-nil)))
  11741. (cond ((not global))
  11742. (value (setq value (concat global " " value)))
  11743. (t (setq value global))))
  11744. (throw 'exit nil))))))
  11745. (if literal-nil value (org-not-nil value)))))
  11746. (defvar org-property-changed-functions nil
  11747. "Hook called when the value of a property has changed.
  11748. Each hook function should accept two arguments, the name of the property
  11749. and the new value.")
  11750. (defun org-entry-put (pom property value)
  11751. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  11752. If the value is nil, it is converted to the empty string. If it
  11753. is not a string, an error is raised. Also raise an error on
  11754. invalid property names.
  11755. PROPERTY can be any regular property (see
  11756. `org-special-properties'). It can also be \"TODO\",
  11757. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  11758. For the last two properties, VALUE may have any of the special
  11759. values \"earlier\" and \"later\". The function then increases or
  11760. decreases scheduled or deadline date by one day."
  11761. (cond ((null value) (setq value ""))
  11762. ((not (stringp value)) (error "Properties values should be strings"))
  11763. ((not (org--valid-property-p property))
  11764. (user-error "Invalid property name: \"%s\"" property)))
  11765. (org-with-point-at pom
  11766. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  11767. (org-back-to-heading-or-point-min t)
  11768. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  11769. (let ((beg (point)))
  11770. (cond
  11771. ((equal property "TODO")
  11772. (cond ((not (org-string-nw-p value)) (setq value 'none))
  11773. ((not (member value org-todo-keywords-1))
  11774. (user-error "\"%s\" is not a valid TODO state" value)))
  11775. (org-todo value)
  11776. (org-align-tags))
  11777. ((equal property "PRIORITY")
  11778. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  11779. (org-align-tags))
  11780. ((equal property "SCHEDULED")
  11781. (forward-line)
  11782. (if (and (looking-at-p org-planning-line-re)
  11783. (re-search-forward
  11784. org-scheduled-time-regexp (line-end-position) t))
  11785. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  11786. ((string= value "later") (org-timestamp-change 1 'day))
  11787. ((string= value "") (org-schedule '(4)))
  11788. (t (org-schedule nil value)))
  11789. (if (member value '("earlier" "later" ""))
  11790. (call-interactively #'org-schedule)
  11791. (org-schedule nil value))))
  11792. ((equal property "DEADLINE")
  11793. (forward-line)
  11794. (if (and (looking-at-p org-planning-line-re)
  11795. (re-search-forward
  11796. org-deadline-time-regexp (line-end-position) t))
  11797. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  11798. ((string= value "later") (org-timestamp-change 1 'day))
  11799. ((string= value "") (org-deadline '(4)))
  11800. (t (org-deadline nil value)))
  11801. (if (member value '("earlier" "later" ""))
  11802. (call-interactively #'org-deadline)
  11803. (org-deadline nil value))))
  11804. ((member property org-special-properties)
  11805. (error "The %s property cannot be set with `org-entry-put'" property))
  11806. (t
  11807. (let* ((range (org-get-property-block beg 'force))
  11808. (end (cdr range))
  11809. (case-fold-search t))
  11810. (goto-char (car range))
  11811. (if (re-search-forward (org-re-property property nil t) end t)
  11812. (progn (delete-region (match-beginning 0) (match-end 0))
  11813. (goto-char (match-beginning 0)))
  11814. (goto-char end)
  11815. (insert "\n")
  11816. (backward-char))
  11817. (insert ":" property ":")
  11818. (when value (insert " " value))
  11819. (org-indent-line)))))
  11820. (run-hook-with-args 'org-property-changed-functions property value)))
  11821. (defun org-buffer-property-keys (&optional specials defaults columns)
  11822. "Get all property keys in the current buffer.
  11823. When SPECIALS is non-nil, also list the special properties that
  11824. reflect things like tags and TODO state.
  11825. When DEFAULTS is non-nil, also include properties that has
  11826. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  11827. DESCRIPTION, LOCATION, and LOGGING and others.
  11828. When COLUMNS in non-nil, also include property names given in
  11829. COLUMN formats in the current buffer."
  11830. (let ((case-fold-search t)
  11831. (props (append
  11832. (and specials org-special-properties)
  11833. (and defaults (cons org-effort-property org-default-properties))
  11834. nil)))
  11835. (org-with-wide-buffer
  11836. (goto-char (point-min))
  11837. (while (re-search-forward org-property-start-re nil t)
  11838. (catch :skip
  11839. (let ((range (org-get-property-block)))
  11840. (unless range (throw :skip nil))
  11841. (goto-char (car range))
  11842. (let ((begin (car range))
  11843. (end (cdr range)))
  11844. ;; Make sure that found property block is not located
  11845. ;; before current point, as it would generate an infloop.
  11846. ;; It can happen, for example, in the following
  11847. ;; situation:
  11848. ;;
  11849. ;; * Headline
  11850. ;; :PROPERTIES:
  11851. ;; ...
  11852. ;; :END:
  11853. ;; *************** Inlinetask
  11854. ;; #+BEGIN_EXAMPLE
  11855. ;; :PROPERTIES:
  11856. ;; #+END_EXAMPLE
  11857. ;;
  11858. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  11859. (while (< (point) end)
  11860. (let ((p (progn (looking-at org-property-re)
  11861. (match-string-no-properties 2))))
  11862. ;; Only add true property name, not extension symbol.
  11863. (push (if (not (string-match-p "\\+\\'" p)) p
  11864. (substring p 0 -1))
  11865. props))
  11866. (forward-line))))
  11867. (outline-next-heading)))
  11868. (when columns
  11869. (goto-char (point-min))
  11870. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  11871. (let ((element (org-element-at-point)))
  11872. (when (memq (org-element-type element) '(keyword node-property))
  11873. (let ((value (org-element-property :value element))
  11874. (start 0))
  11875. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  11876. \\(?:{[^}]+}\\)?"
  11877. value start)
  11878. (setq start (match-end 0))
  11879. (let ((p (match-string-no-properties 1 value)))
  11880. (unless (member-ignore-case p org-special-properties)
  11881. (push p props))))))))))
  11882. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  11883. (defun org-property-values (key)
  11884. "List all non-nil values of property KEY in current buffer."
  11885. (org-with-wide-buffer
  11886. (goto-char (point-min))
  11887. (let ((case-fold-search t)
  11888. (re (org-re-property key))
  11889. values)
  11890. (while (re-search-forward re nil t)
  11891. (push (org-entry-get (point) key) values))
  11892. (delete-dups values))))
  11893. (defun org-insert-property-drawer ()
  11894. "Insert a property drawer into the current entry.
  11895. Do nothing if the drawer already exists. The newly created
  11896. drawer is immediately hidden."
  11897. (org-with-wide-buffer
  11898. ;; Set point to the position where the drawer should be inserted.
  11899. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  11900. (org-back-to-heading-or-point-min t)
  11901. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  11902. (if (org-before-first-heading-p)
  11903. (while (and (org-at-comment-p) (bolp)) (forward-line))
  11904. (progn
  11905. (forward-line)
  11906. (when (looking-at-p org-planning-line-re) (forward-line))))
  11907. (unless (looking-at-p org-property-drawer-re)
  11908. ;; Make sure we start editing a line from current entry, not from
  11909. ;; next one. It prevents extending text properties or overlays
  11910. ;; belonging to the latter.
  11911. (when (and (bolp) (> (point) (point-min))) (backward-char))
  11912. (let ((begin (if (bobp) (point) (1+ (point))))
  11913. (inhibit-read-only t))
  11914. (unless (bobp) (insert "\n"))
  11915. (insert ":PROPERTIES:\n:END:")
  11916. (org-flag-region (line-end-position 0) (point) t 'org-hide-drawer)
  11917. (when (or (eobp) (= begin (point-min))) (insert "\n"))
  11918. (org-indent-region begin (point))))))
  11919. (defun org-insert-drawer (&optional arg drawer)
  11920. "Insert a drawer at point.
  11921. When optional argument ARG is non-nil, insert a property drawer.
  11922. Optional argument DRAWER, when non-nil, is a string representing
  11923. drawer's name. Otherwise, the user is prompted for a name.
  11924. If a region is active, insert the drawer around that region
  11925. instead.
  11926. Point is left between drawer's boundaries."
  11927. (interactive "P")
  11928. (let* ((drawer (if arg "PROPERTIES"
  11929. (or drawer (read-from-minibuffer "Drawer: ")))))
  11930. (cond
  11931. ;; With C-u, fall back on `org-insert-property-drawer'
  11932. (arg (org-insert-property-drawer))
  11933. ;; Check validity of suggested drawer's name.
  11934. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  11935. (user-error "Invalid drawer name"))
  11936. ;; With an active region, insert a drawer at point.
  11937. ((not (org-region-active-p))
  11938. (progn
  11939. (unless (bolp) (insert "\n"))
  11940. (insert (format ":%s:\n\n:END:\n" drawer))
  11941. (forward-line -2)))
  11942. ;; Otherwise, insert the drawer at point
  11943. (t
  11944. (let ((rbeg (region-beginning))
  11945. (rend (copy-marker (region-end))))
  11946. (unwind-protect
  11947. (progn
  11948. (goto-char rbeg)
  11949. (beginning-of-line)
  11950. (when (save-excursion
  11951. (re-search-forward org-outline-regexp-bol rend t))
  11952. (user-error "Drawers cannot contain headlines"))
  11953. ;; Position point at the beginning of the first
  11954. ;; non-blank line in region. Insert drawer's opening
  11955. ;; there, then indent it.
  11956. (org-skip-whitespace)
  11957. (beginning-of-line)
  11958. (insert ":" drawer ":\n")
  11959. (forward-line -1)
  11960. (indent-for-tab-command)
  11961. ;; Move point to the beginning of the first blank line
  11962. ;; after the last non-blank line in region. Insert
  11963. ;; drawer's closing, then indent it.
  11964. (goto-char rend)
  11965. (skip-chars-backward " \r\t\n")
  11966. (insert "\n:END:")
  11967. (deactivate-mark t)
  11968. (indent-for-tab-command)
  11969. (unless (eolp) (insert "\n")))
  11970. ;; Clear marker, whatever the outcome of insertion is.
  11971. (set-marker rend nil)))))))
  11972. (defvar org-property-set-functions-alist nil
  11973. "Property set function alist.
  11974. Each entry should have the following format:
  11975. (PROPERTY . READ-FUNCTION)
  11976. The read function will be called with the same argument as
  11977. `org-completing-read'.")
  11978. (defun org-set-property-function (property)
  11979. "Get the function that should be used to set PROPERTY.
  11980. This is computed according to `org-property-set-functions-alist'."
  11981. (or (cdr (assoc property org-property-set-functions-alist))
  11982. 'org-completing-read))
  11983. (defun org-read-property-value (property &optional pom)
  11984. "Read value for PROPERTY, as a string.
  11985. When optional argument POM is non-nil, completion uses additional
  11986. information, i.e., allowed or existing values at point or marker
  11987. POM."
  11988. (let* ((completion-ignore-case t)
  11989. (allowed
  11990. (or (org-property-get-allowed-values nil property 'table)
  11991. (and pom (org-property-get-allowed-values pom property 'table))))
  11992. (current (org-entry-get nil property))
  11993. (prompt (format "%s value%s: "
  11994. property
  11995. (if (org-string-nw-p current)
  11996. (format " [%s]" current)
  11997. "")))
  11998. (set-function (org-set-property-function property)))
  11999. (org-trim
  12000. (if allowed
  12001. (funcall set-function
  12002. prompt allowed nil
  12003. (not (get-text-property 0 'org-unrestricted (caar allowed))))
  12004. (let ((all (mapcar #'list
  12005. (append (org-property-values property)
  12006. (and pom
  12007. (org-with-point-at pom
  12008. (org-property-values property)))))))
  12009. (funcall set-function prompt all nil nil "" nil current))))))
  12010. (defvar org-last-set-property nil)
  12011. (defvar org-last-set-property-value nil)
  12012. (defun org-read-property-name ()
  12013. "Read a property name."
  12014. (let ((completion-ignore-case t)
  12015. (default-prop (or (and (org-at-property-p)
  12016. (match-string-no-properties 2))
  12017. org-last-set-property)))
  12018. (org-completing-read
  12019. (concat "Property"
  12020. (if default-prop (concat " [" default-prop "]") "")
  12021. ": ")
  12022. (mapcar #'list (org-buffer-property-keys nil t t))
  12023. nil nil nil nil default-prop)))
  12024. (defun org-set-property-and-value (use-last)
  12025. "Allow to set [PROPERTY]: [value] direction from prompt.
  12026. When use-default, don't even ask, just use the last
  12027. \"[PROPERTY]: [value]\" string from the history."
  12028. (interactive "P")
  12029. (let* ((completion-ignore-case t)
  12030. (pv (or (and use-last org-last-set-property-value)
  12031. (org-completing-read
  12032. "Enter a \"[Property]: [value]\" pair: "
  12033. nil nil nil nil nil
  12034. org-last-set-property-value)))
  12035. prop val)
  12036. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  12037. (setq prop (match-string 1 pv)
  12038. val (match-string 2 pv))
  12039. (org-set-property prop val))))
  12040. (defun org-set-property (property value)
  12041. "In the current entry, set PROPERTY to VALUE.
  12042. When called interactively, this will prompt for a property name, offering
  12043. completion on existing and default properties. And then it will prompt
  12044. for a value, offering completion either on allowed values (via an inherited
  12045. xxx_ALL property) or on existing values in other instances of this property
  12046. in the current file.
  12047. Throw an error when trying to set a property with an invalid name."
  12048. (interactive (list nil nil))
  12049. (let ((property (or property (org-read-property-name))))
  12050. ;; `org-entry-put' also makes the following check, but this one
  12051. ;; avoids polluting `org-last-set-property' and
  12052. ;; `org-last-set-property-value' needlessly.
  12053. (unless (org--valid-property-p property)
  12054. (user-error "Invalid property name: \"%s\"" property))
  12055. (let ((value (or value (org-read-property-value property)))
  12056. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  12057. (setq org-last-set-property property)
  12058. (setq org-last-set-property-value (concat property ": " value))
  12059. ;; Possibly postprocess the inserted value:
  12060. (when fn (setq value (funcall fn value)))
  12061. (unless (equal (org-entry-get nil property) value)
  12062. (org-entry-put nil property value)))))
  12063. (defun org-find-property (property &optional value)
  12064. "Find first entry in buffer that sets PROPERTY.
  12065. When optional argument VALUE is non-nil, only consider an entry
  12066. if it contains PROPERTY set to this value. If PROPERTY should be
  12067. explicitly set to nil, use string \"nil\" for VALUE.
  12068. Return position where the entry begins, or nil if there is no
  12069. such entry. If narrowing is in effect, only search the visible
  12070. part of the buffer."
  12071. (save-excursion
  12072. (goto-char (point-min))
  12073. (let ((case-fold-search t)
  12074. (re (org-re-property property nil (not value) value)))
  12075. (catch 'exit
  12076. (while (re-search-forward re nil t)
  12077. (when (if value (org-at-property-p)
  12078. (org-entry-get (point) property nil t))
  12079. (throw 'exit (progn (org-back-to-heading-or-point-min t)
  12080. (point)))))))))
  12081. (defun org-delete-property (property)
  12082. "In the current entry, delete PROPERTY."
  12083. (interactive
  12084. (let* ((completion-ignore-case t)
  12085. (cat (org-entry-get (point) "CATEGORY"))
  12086. (props0 (org-entry-properties nil 'standard))
  12087. (props (if cat props0
  12088. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  12089. (prop (if (< 1 (length props))
  12090. (completing-read "Property: " props nil t)
  12091. (caar props))))
  12092. (list prop)))
  12093. (if (not property)
  12094. (message "No property to delete in this entry")
  12095. (org-entry-delete nil property)
  12096. (message "Property \"%s\" deleted" property)))
  12097. (defun org-delete-property-globally (property)
  12098. "Remove PROPERTY globally, from all entries.
  12099. This function ignores narrowing, if any."
  12100. (interactive
  12101. (let* ((completion-ignore-case t)
  12102. (prop (completing-read
  12103. "Globally remove property: "
  12104. (mapcar #'list (org-buffer-property-keys)))))
  12105. (list prop)))
  12106. (org-with-wide-buffer
  12107. (goto-char (point-min))
  12108. (let ((count 0)
  12109. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  12110. (while (re-search-forward re nil t)
  12111. (when (org-entry-delete (point) property) (cl-incf count)))
  12112. (message "Property \"%s\" removed from %d entries" property count))))
  12113. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  12114. (defun org-compute-property-at-point ()
  12115. "Compute the property at point.
  12116. This looks for an enclosing column format, extracts the operator and
  12117. then applies it to the property in the column format's scope."
  12118. (interactive)
  12119. (unless (org-at-property-p)
  12120. (user-error "Not at a property"))
  12121. (let ((prop (match-string-no-properties 2)))
  12122. (org-columns-get-format-and-top-level)
  12123. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  12124. (user-error "No operator defined for property %s" prop))
  12125. (org-columns-compute prop)))
  12126. (defvar org-property-allowed-value-functions nil
  12127. "Hook for functions supplying allowed values for a specific property.
  12128. The functions must take a single argument, the name of the property, and
  12129. return a flat list of allowed values. If \":ETC\" is one of
  12130. the values, this means that these values are intended as defaults for
  12131. completion, but that other values should be allowed too.
  12132. The functions must return nil if they are not responsible for this
  12133. property.")
  12134. (defun org-property-get-allowed-values (pom property &optional table)
  12135. "Get allowed values for the property PROPERTY.
  12136. When TABLE is non-nil, return an alist that can directly be used for
  12137. completion."
  12138. (let (vals)
  12139. (cond
  12140. ((equal property "TODO")
  12141. (setq vals (org-with-point-at pom
  12142. (append org-todo-keywords-1 '("")))))
  12143. ((equal property "PRIORITY")
  12144. (let ((n org-priority-lowest))
  12145. (while (>= n org-priority-highest)
  12146. (push (char-to-string n) vals)
  12147. (setq n (1- n)))))
  12148. ((equal property "CATEGORY"))
  12149. ((member property org-special-properties))
  12150. ((setq vals (run-hook-with-args-until-success
  12151. 'org-property-allowed-value-functions property)))
  12152. (t
  12153. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  12154. (when (and vals (string-match "\\S-" vals))
  12155. (setq vals (car (read-from-string (concat "(" vals ")"))))
  12156. (setq vals (mapcar (lambda (x)
  12157. (cond ((stringp x) x)
  12158. ((numberp x) (number-to-string x))
  12159. ((symbolp x) (symbol-name x))
  12160. (t "???")))
  12161. vals)))))
  12162. (when (member ":ETC" vals)
  12163. (setq vals (remove ":ETC" vals))
  12164. (org-add-props (car vals) '(org-unrestricted t)))
  12165. (if table (mapcar 'list vals) vals)))
  12166. (defun org-property-previous-allowed-value (&optional _previous)
  12167. "Switch to the next allowed value for this property."
  12168. (interactive)
  12169. (org-property-next-allowed-value t))
  12170. (defun org-property-next-allowed-value (&optional previous)
  12171. "Switch to the next allowed value for this property."
  12172. (interactive)
  12173. (unless (org-at-property-p)
  12174. (user-error "Not at a property"))
  12175. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  12176. (key (match-string 2))
  12177. (value (match-string 3))
  12178. (allowed (or (org-property-get-allowed-values (point) key)
  12179. (and (member value '("[ ]" "[-]" "[X]"))
  12180. '("[ ]" "[X]"))))
  12181. (heading (save-match-data (nth 4 (org-heading-components))))
  12182. nval)
  12183. (unless allowed
  12184. (user-error "Allowed values for this property have not been defined"))
  12185. (when previous (setq allowed (reverse allowed)))
  12186. (when (member value allowed)
  12187. (setq nval (car (cdr (member value allowed)))))
  12188. (setq nval (or nval (car allowed)))
  12189. (when (equal nval value)
  12190. (user-error "Only one allowed value for this property"))
  12191. (org-at-property-p)
  12192. (replace-match (concat " :" key ": " nval) t t)
  12193. (org-indent-line)
  12194. (beginning-of-line 1)
  12195. (skip-chars-forward " \t")
  12196. (when (equal prop org-effort-property)
  12197. (org-refresh-property
  12198. '((effort . identity)
  12199. (effort-minutes . org-duration-to-minutes))
  12200. nval)
  12201. (when (string= org-clock-current-task heading)
  12202. (setq org-clock-effort nval)
  12203. (org-clock-update-mode-line)))
  12204. (run-hook-with-args 'org-property-changed-functions key nval)))
  12205. (defun org-find-olp (path &optional this-buffer)
  12206. "Return a marker pointing to the entry at outline path OLP.
  12207. If anything goes wrong, throw an error.
  12208. You can wrap this call to catch the error like this:
  12209. (condition-case msg
  12210. (org-mobile-locate-entry (match-string 4))
  12211. (error (nth 1 msg)))
  12212. The return value will then be either a string with the error message,
  12213. or a marker if everything is OK.
  12214. If THIS-BUFFER is set, the outline path does not contain a file,
  12215. only headings."
  12216. (let* ((file (if this-buffer buffer-file-name (pop path)))
  12217. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  12218. (level 1)
  12219. (lmin 1)
  12220. (lmax 1)
  12221. end found flevel)
  12222. (unless buffer (error "File not found :%s" file))
  12223. (with-current-buffer buffer
  12224. (unless (derived-mode-p 'org-mode)
  12225. (error "Buffer %s needs to be in Org mode" buffer))
  12226. (org-with-wide-buffer
  12227. (goto-char (point-min))
  12228. (dolist (heading path)
  12229. (let ((re (format org-complex-heading-regexp-format
  12230. (regexp-quote heading)))
  12231. (cnt 0))
  12232. (while (re-search-forward re end t)
  12233. (setq level (- (match-end 1) (match-beginning 1)))
  12234. (when (and (>= level lmin) (<= level lmax))
  12235. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  12236. (when (= cnt 0)
  12237. (error "Heading not found on level %d: %s" lmax heading))
  12238. (when (> cnt 1)
  12239. (error "Heading not unique on level %d: %s" lmax heading))
  12240. (goto-char found)
  12241. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  12242. (setq end (save-excursion (org-end-of-subtree t t)))))
  12243. (when (org-at-heading-p)
  12244. (point-marker))))))
  12245. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  12246. "Find node HEADING in BUFFER.
  12247. Return a marker to the heading if it was found, or nil if not.
  12248. If POS-ONLY is set, return just the position instead of a marker.
  12249. The heading text must match exact, but it may have a TODO keyword,
  12250. a priority cookie and tags in the standard locations."
  12251. (with-current-buffer (or buffer (current-buffer))
  12252. (org-with-wide-buffer
  12253. (goto-char (point-min))
  12254. (let (case-fold-search)
  12255. (when (re-search-forward
  12256. (format org-complex-heading-regexp-format
  12257. (regexp-quote heading)) nil t)
  12258. (if pos-only
  12259. (match-beginning 0)
  12260. (move-marker (make-marker) (match-beginning 0))))))))
  12261. (defun org-find-exact-heading-in-directory (heading &optional dir)
  12262. "Find Org node headline HEADING in all \".org\" files in directory DIR.
  12263. When the target headline is found, return a marker to this location."
  12264. (let ((files (directory-files (or dir default-directory)
  12265. t "\\`[^.#].*\\.org\\'"))
  12266. visiting m buffer)
  12267. (catch 'found
  12268. (dolist (file files)
  12269. (message "trying %s" file)
  12270. (setq visiting (org-find-base-buffer-visiting file))
  12271. (setq buffer (or visiting (find-file-noselect file)))
  12272. (setq m (org-find-exact-headline-in-buffer
  12273. heading buffer))
  12274. (when (and (not m) (not visiting)) (kill-buffer buffer))
  12275. (and m (throw 'found m))))))
  12276. (defun org-find-entry-with-id (ident)
  12277. "Locate the entry that contains the ID property with exact value IDENT.
  12278. IDENT can be a string, a symbol or a number, this function will search for
  12279. the string representation of it.
  12280. Return the position where this entry starts, or nil if there is no such entry."
  12281. (interactive "sID: ")
  12282. (let ((id (cond
  12283. ((stringp ident) ident)
  12284. ((symbolp ident) (symbol-name ident))
  12285. ((numberp ident) (number-to-string ident))
  12286. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  12287. (org-with-wide-buffer (org-find-property "ID" id))))
  12288. ;;;; Timestamps
  12289. (defvar org-last-changed-timestamp nil)
  12290. (defvar org-last-inserted-timestamp nil
  12291. "The last time stamp inserted with `org-insert-time-stamp'.")
  12292. (defun org-time-stamp (arg &optional inactive)
  12293. "Prompt for a date/time and insert a time stamp.
  12294. If the user specifies a time like HH:MM or if this command is
  12295. called with at least one prefix argument, the time stamp contains
  12296. the date and the time. Otherwise, only the date is included.
  12297. All parts of a date not specified by the user are filled in from
  12298. the timestamp at point, if any, or the current date/time
  12299. otherwise.
  12300. If there is already a timestamp at the cursor, it is replaced.
  12301. With two universal prefix arguments, insert an active timestamp
  12302. with the current time without prompting the user.
  12303. When called from lisp, the timestamp is inactive if INACTIVE is
  12304. non-nil."
  12305. (interactive "P")
  12306. (let* ((ts (cond
  12307. ((org-at-date-range-p t)
  12308. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  12309. ((org-at-timestamp-p 'lax) (match-string 0))))
  12310. ;; Default time is either the timestamp at point or today.
  12311. ;; When entering a range, only the range start is considered.
  12312. (default-time (and ts (org-time-string-to-time ts)))
  12313. (default-input (and ts (org-get-compact-tod ts)))
  12314. (repeater (and ts
  12315. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  12316. (match-string 0 ts)))
  12317. org-time-was-given
  12318. org-end-time-was-given
  12319. (time
  12320. (if (equal arg '(16)) (current-time)
  12321. ;; Preserve `this-command' and `last-command'.
  12322. (let ((this-command this-command)
  12323. (last-command last-command))
  12324. (org-read-date
  12325. arg 'totime nil nil default-time default-input
  12326. inactive)))))
  12327. (cond
  12328. ((and ts
  12329. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  12330. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  12331. (insert "--")
  12332. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  12333. (ts
  12334. ;; Make sure we're on a timestamp. When in the middle of a date
  12335. ;; range, move arbitrarily to range end.
  12336. (unless (org-at-timestamp-p 'lax)
  12337. (skip-chars-forward "-")
  12338. (org-at-timestamp-p 'lax))
  12339. (replace-match "")
  12340. (setq org-last-changed-timestamp
  12341. (org-insert-time-stamp
  12342. time (or org-time-was-given arg)
  12343. inactive nil nil (list org-end-time-was-given)))
  12344. (when repeater
  12345. (backward-char)
  12346. (insert " " repeater)
  12347. (setq org-last-changed-timestamp
  12348. (concat (substring org-last-inserted-timestamp 0 -1)
  12349. " " repeater ">")))
  12350. (message "Timestamp updated"))
  12351. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  12352. (t (org-insert-time-stamp
  12353. time (or org-time-was-given arg) inactive nil nil
  12354. (list org-end-time-was-given))))))
  12355. ;; FIXME: can we use this for something else, like computing time differences?
  12356. (defun org-get-compact-tod (s)
  12357. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  12358. (let* ((t1 (match-string 1 s))
  12359. (h1 (string-to-number (match-string 2 s)))
  12360. (m1 (string-to-number (match-string 3 s)))
  12361. (t2 (and (match-end 4) (match-string 5 s)))
  12362. (h2 (and t2 (string-to-number (match-string 6 s))))
  12363. (m2 (and t2 (string-to-number (match-string 7 s))))
  12364. dh dm)
  12365. (if (not t2)
  12366. t1
  12367. (setq dh (- h2 h1) dm (- m2 m1))
  12368. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  12369. (concat t1 "+" (number-to-string dh)
  12370. (and (/= 0 dm) (format ":%02d" dm)))))))
  12371. (defun org-time-stamp-inactive (&optional arg)
  12372. "Insert an inactive time stamp.
  12373. An inactive time stamp is enclosed in square brackets instead of
  12374. angle brackets. It is inactive in the sense that it does not
  12375. trigger agenda entries. So these are more for recording a
  12376. certain time/date.
  12377. If the user specifies a time like HH:MM or if this command is called with
  12378. at least one prefix argument, the time stamp contains the date and the time.
  12379. Otherwise, only the date is included.
  12380. When called with two universal prefix arguments, insert an inactive time stamp
  12381. with the current time without prompting the user."
  12382. (interactive "P")
  12383. (org-time-stamp arg 'inactive))
  12384. (defvar org-date-ovl (make-overlay 1 1))
  12385. (overlay-put org-date-ovl 'face 'org-date-selected)
  12386. (delete-overlay org-date-ovl)
  12387. (defvar org-ans1) ; dynamically scoped parameter
  12388. (defvar org-ans2) ; dynamically scoped parameter
  12389. (defvar org-plain-time-of-day-regexp) ; defined below
  12390. (defvar org-overriding-default-time nil) ; dynamically scoped
  12391. (defvar org-read-date-overlay nil)
  12392. (defvar org-read-date-history nil)
  12393. (defvar org-read-date-final-answer nil)
  12394. (defvar org-read-date-analyze-futurep nil)
  12395. (defvar org-read-date-analyze-forced-year nil)
  12396. (defvar org-read-date-inactive)
  12397. (defvar org-def)
  12398. (defvar org-defdecode)
  12399. (defvar org-with-time)
  12400. (defvar calendar-setup) ; Dynamically scoped.
  12401. (defun org-read-date (&optional with-time to-time from-string prompt
  12402. default-time default-input inactive)
  12403. "Read a date, possibly a time, and make things smooth for the user.
  12404. The prompt will suggest to enter an ISO date, but you can also enter anything
  12405. which will at least partially be understood by `parse-time-string'.
  12406. Unrecognized parts of the date will default to the current day, month, year,
  12407. hour and minute. If this command is called to replace a timestamp at point,
  12408. or to enter the second timestamp of a range, the default time is taken
  12409. from the existing stamp. Furthermore, the command prefers the future,
  12410. so if you are giving a date where the year is not given, and the day-month
  12411. combination is already past in the current year, it will assume you
  12412. mean next year. For details, see the manual. A few examples:
  12413. 3-2-5 --> 2003-02-05
  12414. feb 15 --> currentyear-02-15
  12415. 2/15 --> currentyear-02-15
  12416. sep 12 9 --> 2009-09-12
  12417. 12:45 --> today 12:45
  12418. 22 sept 0:34 --> currentyear-09-22 0:34
  12419. 12 --> currentyear-currentmonth-12
  12420. Fri --> nearest Friday after today
  12421. -Tue --> last Tuesday
  12422. etc.
  12423. Furthermore you can specify a relative date by giving, as the *first* thing
  12424. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  12425. change in days weeks, months, years.
  12426. With a single plus or minus, the date is relative to today. With a double
  12427. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  12428. +4d --> four days from today
  12429. +4 --> same as above
  12430. +2w --> two weeks from today
  12431. ++5 --> five days from default date
  12432. The function understands only English month and weekday abbreviations.
  12433. While prompting, a calendar is popped up - you can also select the
  12434. date with the mouse (button 1). The calendar shows a period of three
  12435. months. To scroll it to other months, use the keys `>' and `<'.
  12436. If you don't like the calendar, turn it off with
  12437. (setq org-read-date-popup-calendar nil)
  12438. With optional argument TO-TIME, the date will immediately be converted
  12439. to an internal time.
  12440. With an optional argument WITH-TIME, the prompt will suggest to
  12441. also insert a time. Note that when WITH-TIME is not set, you can
  12442. still enter a time, and this function will inform the calling routine
  12443. about this change. The calling routine may then choose to change the
  12444. format used to insert the time stamp into the buffer to include the time.
  12445. With optional argument FROM-STRING, read from this string instead from
  12446. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  12447. the time/date that is used for everything that is not specified by the
  12448. user."
  12449. (require 'parse-time)
  12450. (let* ((org-with-time with-time)
  12451. (org-time-stamp-rounding-minutes
  12452. (if (equal org-with-time '(16))
  12453. '(0 0)
  12454. org-time-stamp-rounding-minutes))
  12455. (ct (org-current-time))
  12456. (org-def (or org-overriding-default-time default-time ct))
  12457. (org-defdecode (decode-time org-def))
  12458. (cur-frame (selected-frame))
  12459. (mouse-autoselect-window nil) ; Don't let the mouse jump
  12460. (calendar-setup
  12461. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  12462. (calendar-move-hook nil)
  12463. (calendar-view-diary-initially-flag nil)
  12464. (calendar-view-holidays-initially-flag nil)
  12465. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  12466. ;; Rationalize `org-def' and `org-defdecode', if required.
  12467. (when (< (nth 2 org-defdecode) org-extend-today-until)
  12468. (setf (nth 2 org-defdecode) -1)
  12469. (setf (nth 1 org-defdecode) 59)
  12470. (setq org-def (apply #'encode-time org-defdecode))
  12471. (setq org-defdecode (decode-time org-def)))
  12472. (let* ((timestr (format-time-string
  12473. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  12474. org-def))
  12475. (prompt (concat (if prompt (concat prompt " ") "")
  12476. (format "Date+time [%s]: " timestr))))
  12477. (cond
  12478. (from-string (setq ans from-string))
  12479. (org-read-date-popup-calendar
  12480. (save-excursion
  12481. (save-window-excursion
  12482. (calendar)
  12483. (when (eq calendar-setup 'calendar-only)
  12484. (setq cal-frame
  12485. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  12486. (select-frame cal-frame))
  12487. (org-eval-in-calendar '(setq cursor-type nil) t)
  12488. (unwind-protect
  12489. (progn
  12490. (calendar-forward-day (- (time-to-days org-def)
  12491. (calendar-absolute-from-gregorian
  12492. (calendar-current-date))))
  12493. (org-eval-in-calendar nil t)
  12494. (let* ((old-map (current-local-map))
  12495. (map (copy-keymap calendar-mode-map))
  12496. (minibuffer-local-map
  12497. (copy-keymap org-read-date-minibuffer-local-map)))
  12498. (org-defkey map (kbd "RET") 'org-calendar-select)
  12499. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  12500. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  12501. (unwind-protect
  12502. (progn
  12503. (use-local-map map)
  12504. (setq org-read-date-inactive inactive)
  12505. (add-hook 'post-command-hook 'org-read-date-display)
  12506. (setq org-ans0
  12507. (read-string prompt
  12508. default-input
  12509. 'org-read-date-history
  12510. nil))
  12511. ;; org-ans0: from prompt
  12512. ;; org-ans1: from mouse click
  12513. ;; org-ans2: from calendar motion
  12514. (setq ans
  12515. (concat org-ans0 " " (or org-ans1 org-ans2))))
  12516. (remove-hook 'post-command-hook 'org-read-date-display)
  12517. (use-local-map old-map)
  12518. (when org-read-date-overlay
  12519. (delete-overlay org-read-date-overlay)
  12520. (setq org-read-date-overlay nil)))))
  12521. (bury-buffer "*Calendar*")
  12522. (when cal-frame
  12523. (delete-frame cal-frame)
  12524. (select-frame-set-input-focus cur-frame))))))
  12525. (t ; Naked prompt only
  12526. (unwind-protect
  12527. (setq ans (read-string prompt default-input
  12528. 'org-read-date-history timestr))
  12529. (when org-read-date-overlay
  12530. (delete-overlay org-read-date-overlay)
  12531. (setq org-read-date-overlay nil))))))
  12532. (setq final (org-read-date-analyze ans org-def org-defdecode))
  12533. (when org-read-date-analyze-forced-year
  12534. (message "Year was forced into %s"
  12535. (if org-read-date-force-compatible-dates
  12536. "compatible range (1970-2037)"
  12537. "range representable on this machine"))
  12538. (ding))
  12539. (setq final (apply #'encode-time final))
  12540. (setq org-read-date-final-answer ans)
  12541. (if to-time
  12542. final
  12543. ;; This round-trip gets rid of 34th of August and stuff like that....
  12544. (setq final (decode-time final))
  12545. (if (and (boundp 'org-time-was-given) org-time-was-given)
  12546. (format "%04d-%02d-%02d %02d:%02d"
  12547. (nth 5 final) (nth 4 final) (nth 3 final)
  12548. (nth 2 final) (nth 1 final))
  12549. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  12550. (defun org-read-date-display ()
  12551. "Display the current date prompt interpretation in the minibuffer."
  12552. (when org-read-date-display-live
  12553. (when org-read-date-overlay
  12554. (delete-overlay org-read-date-overlay))
  12555. (when (minibufferp (current-buffer))
  12556. (save-excursion
  12557. (end-of-line 1)
  12558. (while (not (equal (buffer-substring
  12559. (max (point-min) (- (point) 4)) (point))
  12560. " "))
  12561. (insert " ")))
  12562. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  12563. " " (or org-ans1 org-ans2)))
  12564. (org-end-time-was-given nil)
  12565. (f (org-read-date-analyze ans org-def org-defdecode))
  12566. (fmts (if org-display-custom-times
  12567. org-time-stamp-custom-formats
  12568. org-time-stamp-formats))
  12569. (fmt (if (or org-with-time
  12570. (and (boundp 'org-time-was-given) org-time-was-given))
  12571. (cdr fmts)
  12572. (car fmts)))
  12573. (txt (format-time-string fmt (apply #'encode-time f)))
  12574. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  12575. (txt (concat "=> " txt)))
  12576. (when (and org-end-time-was-given
  12577. (string-match org-plain-time-of-day-regexp txt))
  12578. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  12579. org-end-time-was-given
  12580. (substring txt (match-end 0)))))
  12581. (when org-read-date-analyze-futurep
  12582. (setq txt (concat txt " (=>F)")))
  12583. (setq org-read-date-overlay
  12584. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  12585. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  12586. (defun org-read-date-analyze (ans def defdecode)
  12587. "Analyze the combined answer of the date prompt."
  12588. ;; FIXME: cleanup and comment
  12589. (let ((org-def def)
  12590. (org-defdecode defdecode)
  12591. (nowdecode (decode-time))
  12592. delta deltan deltaw deltadef year month day
  12593. hour minute second wday pm h2 m2 tl wday1
  12594. iso-year iso-weekday iso-week iso-date futurep kill-year)
  12595. (setq org-read-date-analyze-futurep nil
  12596. org-read-date-analyze-forced-year nil)
  12597. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  12598. (setq ans "+0"))
  12599. (when (setq delta (org-read-date-get-relative ans nil org-def))
  12600. (setq ans (replace-match "" t t ans)
  12601. deltan (car delta)
  12602. deltaw (nth 1 delta)
  12603. deltadef (nth 2 delta)))
  12604. ;; Check if there is an iso week date in there. If yes, store the
  12605. ;; info and postpone interpreting it until the rest of the parsing
  12606. ;; is done.
  12607. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  12608. (setq iso-year (when (match-end 1)
  12609. (org-small-year-to-year
  12610. (string-to-number (match-string 1 ans))))
  12611. iso-weekday (when (match-end 3)
  12612. (string-to-number (match-string 3 ans)))
  12613. iso-week (string-to-number (match-string 2 ans)))
  12614. (setq ans (replace-match "" t t ans)))
  12615. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  12616. (when (string-match
  12617. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  12618. (setq year (if (match-end 2)
  12619. (string-to-number (match-string 2 ans))
  12620. (progn (setq kill-year t)
  12621. (string-to-number (format-time-string "%Y"))))
  12622. month (string-to-number (match-string 3 ans))
  12623. day (string-to-number (match-string 4 ans)))
  12624. (setq year (org-small-year-to-year year))
  12625. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  12626. t nil ans)))
  12627. ;; Help matching dotted european dates
  12628. (when (string-match
  12629. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  12630. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  12631. (setq kill-year t)
  12632. (string-to-number (format-time-string "%Y")))
  12633. day (string-to-number (match-string 1 ans))
  12634. month (string-to-number (match-string 2 ans))
  12635. ans (replace-match (format "%04d-%02d-%02d" year month day)
  12636. t nil ans)))
  12637. ;; Help matching american dates, like 5/30 or 5/30/7
  12638. (when (string-match
  12639. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  12640. (setq year (if (match-end 4)
  12641. (string-to-number (match-string 4 ans))
  12642. (progn (setq kill-year t)
  12643. (string-to-number (format-time-string "%Y"))))
  12644. month (string-to-number (match-string 1 ans))
  12645. day (string-to-number (match-string 2 ans)))
  12646. (setq year (org-small-year-to-year year))
  12647. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  12648. t nil ans)))
  12649. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  12650. ;; If there is a time with am/pm, and *no* time without it, we convert
  12651. ;; so that matching will be successful.
  12652. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  12653. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  12654. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  12655. (setq hour (string-to-number (match-string 1 ans))
  12656. minute (if (match-end 3)
  12657. (string-to-number (match-string 3 ans))
  12658. 0)
  12659. pm (equal ?p
  12660. (string-to-char (downcase (match-string 4 ans)))))
  12661. (if (and (= hour 12) (not pm))
  12662. (setq hour 0)
  12663. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  12664. (setq ans (replace-match (format "%02d:%02d" hour minute)
  12665. t t ans))))
  12666. ;; Check if a time range is given as a duration
  12667. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  12668. (setq hour (string-to-number (match-string 1 ans))
  12669. h2 (+ hour (string-to-number (match-string 3 ans)))
  12670. minute (string-to-number (match-string 2 ans))
  12671. m2 (+ minute (if (match-end 5) (string-to-number
  12672. (match-string 5 ans))0)))
  12673. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  12674. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  12675. t t ans)))
  12676. ;; Check if there is a time range
  12677. (when (boundp 'org-end-time-was-given)
  12678. (setq org-time-was-given nil)
  12679. (when (and (string-match org-plain-time-of-day-regexp ans)
  12680. (match-end 8))
  12681. (setq org-end-time-was-given (match-string 8 ans))
  12682. (setq ans (concat (substring ans 0 (match-beginning 7))
  12683. (substring ans (match-end 7))))))
  12684. (setq tl (parse-time-string ans)
  12685. day (or (nth 3 tl) (nth 3 org-defdecode))
  12686. month
  12687. (cond ((nth 4 tl))
  12688. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  12689. ;; Day was specified. Make sure DAY+MONTH
  12690. ;; combination happens in the future.
  12691. ((nth 3 tl)
  12692. (setq futurep t)
  12693. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  12694. (nth 4 nowdecode)))
  12695. (t (nth 4 org-defdecode)))
  12696. year
  12697. (cond ((and (not kill-year) (nth 5 tl)))
  12698. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  12699. ;; Month was guessed in the future and is at least
  12700. ;; equal to NOWDECODE's. Fix year accordingly.
  12701. (futurep
  12702. (if (or (> month (nth 4 nowdecode))
  12703. (>= day (nth 3 nowdecode)))
  12704. (nth 5 nowdecode)
  12705. (1+ (nth 5 nowdecode))))
  12706. ;; Month was specified. Make sure MONTH+YEAR
  12707. ;; combination happens in the future.
  12708. ((nth 4 tl)
  12709. (setq futurep t)
  12710. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  12711. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  12712. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  12713. (t (nth 5 nowdecode))))
  12714. (t (nth 5 org-defdecode)))
  12715. hour (or (nth 2 tl) (nth 2 org-defdecode))
  12716. minute (or (nth 1 tl) (nth 1 org-defdecode))
  12717. second (or (nth 0 tl) 0)
  12718. wday (nth 6 tl))
  12719. (when (and (eq org-read-date-prefer-future 'time)
  12720. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  12721. (equal day (nth 3 nowdecode))
  12722. (equal month (nth 4 nowdecode))
  12723. (equal year (nth 5 nowdecode))
  12724. (nth 2 tl)
  12725. (or (< (nth 2 tl) (nth 2 nowdecode))
  12726. (and (= (nth 2 tl) (nth 2 nowdecode))
  12727. (nth 1 tl)
  12728. (< (nth 1 tl) (nth 1 nowdecode)))))
  12729. (setq day (1+ day)
  12730. futurep t))
  12731. ;; Special date definitions below
  12732. (cond
  12733. (iso-week
  12734. ;; There was an iso week
  12735. (require 'cal-iso)
  12736. (setq futurep nil)
  12737. (setq year (or iso-year year)
  12738. day (or iso-weekday wday 1)
  12739. wday nil ; to make sure that the trigger below does not match
  12740. iso-date (calendar-gregorian-from-absolute
  12741. (calendar-iso-to-absolute
  12742. (list iso-week day year))))
  12743. ; FIXME: Should we also push ISO weeks into the future?
  12744. ; (when (and org-read-date-prefer-future
  12745. ; (not iso-year)
  12746. ; (< (calendar-absolute-from-gregorian iso-date)
  12747. ; (time-to-days nil)))
  12748. ; (setq year (1+ year)
  12749. ; iso-date (calendar-gregorian-from-absolute
  12750. ; (calendar-iso-to-absolute
  12751. ; (list iso-week day year)))))
  12752. (setq month (car iso-date)
  12753. year (nth 2 iso-date)
  12754. day (nth 1 iso-date)))
  12755. (deltan
  12756. (setq futurep nil)
  12757. (unless deltadef
  12758. (let ((now (decode-time)))
  12759. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  12760. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  12761. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  12762. ((equal deltaw "m") (setq month (+ month deltan)))
  12763. ((equal deltaw "y") (setq year (+ year deltan)))))
  12764. ((and wday (not (nth 3 tl)))
  12765. ;; Weekday was given, but no day, so pick that day in the week
  12766. ;; on or after the derived date.
  12767. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  12768. (unless (equal wday wday1)
  12769. (setq day (+ day (% (- wday wday1 -7) 7))))))
  12770. (when (and (boundp 'org-time-was-given)
  12771. (nth 2 tl))
  12772. (setq org-time-was-given t))
  12773. (when (< year 100) (setq year (+ 2000 year)))
  12774. ;; Check of the date is representable
  12775. (if org-read-date-force-compatible-dates
  12776. (progn
  12777. (when (< year 1970)
  12778. (setq year 1970 org-read-date-analyze-forced-year t))
  12779. (when (> year 2037)
  12780. (setq year 2037 org-read-date-analyze-forced-year t)))
  12781. (condition-case nil
  12782. (ignore (encode-time second minute hour day month year))
  12783. (error
  12784. (setq year (nth 5 org-defdecode))
  12785. (setq org-read-date-analyze-forced-year t))))
  12786. (setq org-read-date-analyze-futurep futurep)
  12787. (list second minute hour day month year)))
  12788. (defvar parse-time-weekdays)
  12789. (defun org-read-date-get-relative (s today default)
  12790. "Check string S for special relative date string.
  12791. TODAY and DEFAULT are internal times, for today and for a default.
  12792. Return shift list (N what def-flag)
  12793. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  12794. N is the number of WHATs to shift.
  12795. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  12796. the DEFAULT date rather than TODAY."
  12797. (require 'parse-time)
  12798. (when (and
  12799. (string-match
  12800. (concat
  12801. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  12802. "\\([0-9]+\\)?"
  12803. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  12804. "\\([ \t]\\|$\\)") s)
  12805. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  12806. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  12807. (string-to-char (substring (match-string 1 s) -1))
  12808. ?+))
  12809. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  12810. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  12811. (what (if (match-end 3) (match-string 3 s) "d"))
  12812. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  12813. (date (if rel default today))
  12814. (wday (nth 6 (decode-time date)))
  12815. delta)
  12816. (if wday1
  12817. (progn
  12818. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  12819. (when (= delta 0) (setq delta 7))
  12820. (when (= dir ?-)
  12821. (setq delta (- delta 7))
  12822. (when (= delta 0) (setq delta -7)))
  12823. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  12824. (list delta "d" rel))
  12825. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  12826. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  12827. "Turn a user-specified date into the internal representation.
  12828. The internal representation needed by the calendar is (month day year).
  12829. This is a wrapper to handle the brain-dead convention in calendar that
  12830. user function argument order change dependent on argument order."
  12831. (pcase calendar-date-style
  12832. (`american (list arg1 arg2 arg3))
  12833. (`european (list arg2 arg1 arg3))
  12834. (`iso (list arg2 arg3 arg1))))
  12835. (defun org-eval-in-calendar (form &optional keepdate)
  12836. "Eval FORM in the calendar window and return to current window.
  12837. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  12838. (let ((sf (selected-frame))
  12839. (sw (selected-window)))
  12840. (select-window (get-buffer-window "*Calendar*" t))
  12841. (eval form)
  12842. (when (and (not keepdate) (calendar-cursor-to-date))
  12843. (let* ((date (calendar-cursor-to-date))
  12844. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  12845. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  12846. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  12847. (select-window sw)
  12848. (select-frame-set-input-focus sf)))
  12849. (defun org-calendar-select ()
  12850. "Return to `org-read-date' with the date currently selected.
  12851. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  12852. (interactive)
  12853. (when (calendar-cursor-to-date)
  12854. (let* ((date (calendar-cursor-to-date))
  12855. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  12856. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  12857. (when (active-minibuffer-window) (exit-minibuffer))))
  12858. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  12859. "Insert a date stamp for the date given by the internal TIME.
  12860. See `format-time-string' for the format of TIME.
  12861. WITH-HM means use the stamp format that includes the time of the day.
  12862. INACTIVE means use square brackets instead of angular ones, so that the
  12863. stamp will not contribute to the agenda.
  12864. PRE and POST are optional strings to be inserted before and after the
  12865. stamp.
  12866. The command returns the inserted time stamp."
  12867. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  12868. stamp)
  12869. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  12870. (insert-before-markers (or pre ""))
  12871. (when (listp extra)
  12872. (setq extra (car extra))
  12873. (if (and (stringp extra)
  12874. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  12875. (setq extra (format "-%02d:%02d"
  12876. (string-to-number (match-string 1 extra))
  12877. (string-to-number (match-string 2 extra))))
  12878. (setq extra nil)))
  12879. (when extra
  12880. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  12881. (insert-before-markers (setq stamp (format-time-string fmt time)))
  12882. (insert-before-markers (or post ""))
  12883. (setq org-last-inserted-timestamp stamp)))
  12884. (defun org-toggle-time-stamp-overlays ()
  12885. "Toggle the use of custom time stamp formats."
  12886. (interactive)
  12887. (setq org-display-custom-times (not org-display-custom-times))
  12888. (unless org-display-custom-times
  12889. (let ((p (point-min)) (bmp (buffer-modified-p)))
  12890. (while (setq p (next-single-property-change p 'display))
  12891. (when (and (get-text-property p 'display)
  12892. (eq (get-text-property p 'face) 'org-date))
  12893. (remove-text-properties
  12894. p (setq p (next-single-property-change p 'display))
  12895. '(display t))))
  12896. (set-buffer-modified-p bmp)))
  12897. (org-restart-font-lock)
  12898. (setq org-table-may-need-update t)
  12899. (if org-display-custom-times
  12900. (message "Time stamps are overlaid with custom format")
  12901. (message "Time stamp overlays removed")))
  12902. (defun org-display-custom-time (beg end)
  12903. "Overlay modified time stamp format over timestamp between BEG and END."
  12904. (let* ((ts (buffer-substring beg end))
  12905. t1 with-hm tf time str (off 0))
  12906. (save-match-data
  12907. (setq t1 (org-parse-time-string ts t))
  12908. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  12909. (setq off (- (match-end 0) (match-beginning 0)))))
  12910. (setq end (- end off))
  12911. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  12912. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  12913. time (org-fix-decoded-time t1)
  12914. str (org-add-props
  12915. (format-time-string
  12916. (substring tf 1 -1) (apply 'encode-time time))
  12917. nil 'mouse-face 'highlight))
  12918. (put-text-property beg end 'display str)))
  12919. (defun org-fix-decoded-time (time)
  12920. "Set 0 instead of nil for the first 6 elements of time.
  12921. Don't touch the rest."
  12922. (let ((n 0))
  12923. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  12924. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  12925. "Difference between TIMESTAMP-STRING and now in days.
  12926. If SECONDS is non-nil, return the difference in seconds."
  12927. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  12928. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  12929. (funcall fdiff nil))))
  12930. (defun org-deadline-close-p (timestamp-string &optional ndays)
  12931. "Is the time in TIMESTAMP-STRING close to the current date?"
  12932. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  12933. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  12934. (not (org-entry-is-done-p))))
  12935. (defun org-get-wdays (ts &optional delay zero-delay)
  12936. "Get the deadline lead time appropriate for timestring TS.
  12937. When DELAY is non-nil, get the delay time for scheduled items
  12938. instead of the deadline lead time. When ZERO-DELAY is non-nil
  12939. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  12940. don't try to find the delay cookie in the scheduled timestamp."
  12941. (let ((tv (if delay org-scheduled-delay-days
  12942. org-deadline-warning-days)))
  12943. (cond
  12944. ((or (and delay (< tv 0))
  12945. (and delay zero-delay (<= tv 0))
  12946. (and (not delay) (<= tv 0)))
  12947. ;; Enforce this value no matter what
  12948. (- tv))
  12949. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  12950. ;; lead time is specified.
  12951. (floor (* (string-to-number (match-string 1 ts))
  12952. (cdr (assoc (match-string 2 ts)
  12953. '(("d" . 1) ("w" . 7)
  12954. ("m" . 30.4) ("y" . 365.25)
  12955. ("h" . 0.041667)))))))
  12956. ;; go for the default.
  12957. (t tv))))
  12958. (defun org-calendar-select-mouse (ev)
  12959. "Return to `org-read-date' with the date currently selected.
  12960. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  12961. (interactive "e")
  12962. (mouse-set-point ev)
  12963. (when (calendar-cursor-to-date)
  12964. (let* ((date (calendar-cursor-to-date))
  12965. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  12966. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  12967. (when (active-minibuffer-window) (exit-minibuffer))))
  12968. (defun org-check-deadlines (ndays)
  12969. "Check if there are any deadlines due or past due.
  12970. A deadline is considered due if it happens within `org-deadline-warning-days'
  12971. days from today's date. If the deadline appears in an entry marked DONE,
  12972. it is not shown. A numeric prefix argument NDAYS can be used to test that
  12973. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  12974. are shown."
  12975. (interactive "P")
  12976. (let* ((org-warn-days
  12977. (cond
  12978. ((equal ndays '(4)) 100000)
  12979. (ndays (prefix-numeric-value ndays))
  12980. (t (abs org-deadline-warning-days))))
  12981. (case-fold-search nil)
  12982. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  12983. (callback
  12984. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  12985. (message "%d deadlines past-due or due within %d days"
  12986. (org-occur regexp nil callback)
  12987. org-warn-days)))
  12988. (defsubst org-re-timestamp (type)
  12989. "Return a regexp for timestamp TYPE.
  12990. Allowed values for TYPE are:
  12991. all: all timestamps
  12992. active: only active timestamps (<...>)
  12993. inactive: only inactive timestamps ([...])
  12994. scheduled: only scheduled timestamps
  12995. deadline: only deadline timestamps
  12996. closed: only closed time-stamps
  12997. When TYPE is nil, fall back on returning a regexp that matches
  12998. both scheduled and deadline timestamps."
  12999. (cl-case type
  13000. (all org-ts-regexp-both)
  13001. (active org-ts-regexp)
  13002. (inactive org-ts-regexp-inactive)
  13003. (scheduled org-scheduled-time-regexp)
  13004. (deadline org-deadline-time-regexp)
  13005. (closed org-closed-time-regexp)
  13006. (otherwise
  13007. (concat "\\<"
  13008. (regexp-opt (list org-deadline-string org-scheduled-string))
  13009. " *<\\([^>]+\\)>"))))
  13010. (defun org-check-before-date (d)
  13011. "Check if there are deadlines or scheduled entries before date D."
  13012. (interactive (list (org-read-date)))
  13013. (let* ((case-fold-search nil)
  13014. (regexp (org-re-timestamp org-ts-type))
  13015. (ts-type org-ts-type)
  13016. (callback
  13017. (lambda ()
  13018. (let ((match (match-string 1)))
  13019. (and (if (memq ts-type '(active inactive all))
  13020. (eq (org-element-type (save-excursion
  13021. (backward-char)
  13022. (org-element-context)))
  13023. 'timestamp)
  13024. (org-at-planning-p))
  13025. (time-less-p
  13026. (org-time-string-to-time match)
  13027. (org-time-string-to-time d)))))))
  13028. (message "%d entries before %s"
  13029. (org-occur regexp nil callback)
  13030. d)))
  13031. (defun org-check-after-date (d)
  13032. "Check if there are deadlines or scheduled entries after date D."
  13033. (interactive (list (org-read-date)))
  13034. (let* ((case-fold-search nil)
  13035. (regexp (org-re-timestamp org-ts-type))
  13036. (ts-type org-ts-type)
  13037. (callback
  13038. (lambda ()
  13039. (let ((match (match-string 1)))
  13040. (and (if (memq ts-type '(active inactive all))
  13041. (eq (org-element-type (save-excursion
  13042. (backward-char)
  13043. (org-element-context)))
  13044. 'timestamp)
  13045. (org-at-planning-p))
  13046. (not (time-less-p
  13047. (org-time-string-to-time match)
  13048. (org-time-string-to-time d))))))))
  13049. (message "%d entries after %s"
  13050. (org-occur regexp nil callback)
  13051. d)))
  13052. (defun org-check-dates-range (start-date end-date)
  13053. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  13054. (interactive (list (org-read-date nil nil nil "Range starts")
  13055. (org-read-date nil nil nil "Range end")))
  13056. (let ((case-fold-search nil)
  13057. (regexp (org-re-timestamp org-ts-type))
  13058. (callback
  13059. (let ((type org-ts-type))
  13060. (lambda ()
  13061. (let ((match (match-string 1)))
  13062. (and
  13063. (if (memq type '(active inactive all))
  13064. (eq (org-element-type (save-excursion
  13065. (backward-char)
  13066. (org-element-context)))
  13067. 'timestamp)
  13068. (org-at-planning-p))
  13069. (not (time-less-p
  13070. (org-time-string-to-time match)
  13071. (org-time-string-to-time start-date)))
  13072. (time-less-p
  13073. (org-time-string-to-time match)
  13074. (org-time-string-to-time end-date))))))))
  13075. (message "%d entries between %s and %s"
  13076. (org-occur regexp nil callback) start-date end-date)))
  13077. (defun org-evaluate-time-range (&optional to-buffer)
  13078. "Evaluate a time range by computing the difference between start and end.
  13079. Normally the result is just printed in the echo area, but with prefix arg
  13080. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  13081. If the time range is actually in a table, the result is inserted into the
  13082. next column.
  13083. For time difference computation, a year is assumed to be exactly 365
  13084. days in order to avoid rounding problems."
  13085. (interactive "P")
  13086. (or
  13087. (org-clock-update-time-maybe)
  13088. (save-excursion
  13089. (unless (org-at-date-range-p t)
  13090. (goto-char (point-at-bol))
  13091. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  13092. (unless (org-at-date-range-p t)
  13093. (user-error "Not at a time-stamp range, and none found in current line")))
  13094. (let* ((ts1 (match-string 1))
  13095. (ts2 (match-string 2))
  13096. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  13097. (match-end (match-end 0))
  13098. (time1 (org-time-string-to-time ts1))
  13099. (time2 (org-time-string-to-time ts2))
  13100. (diff (abs (float-time (time-subtract time2 time1))))
  13101. (negative (time-less-p time2 time1))
  13102. ;; (ys (floor (* 365 24 60 60)))
  13103. (ds (* 24 60 60))
  13104. (hs (* 60 60))
  13105. (fy "%dy %dd %02d:%02d")
  13106. (fy1 "%dy %dd")
  13107. (fd "%dd %02d:%02d")
  13108. (fd1 "%dd")
  13109. (fh "%02d:%02d")
  13110. y d h m align)
  13111. (if havetime
  13112. (setq ; y (floor diff ys) diff (mod diff ys)
  13113. y 0
  13114. d (floor diff ds) diff (mod diff ds)
  13115. h (floor diff hs) diff (mod diff hs)
  13116. m (floor diff 60))
  13117. (setq ; y (floor diff ys) diff (mod diff ys)
  13118. y 0
  13119. d (round diff ds)
  13120. h 0 m 0))
  13121. (if (not to-buffer)
  13122. (message "%s" (org-make-tdiff-string y d h m))
  13123. (if (org-at-table-p)
  13124. (progn
  13125. (goto-char match-end)
  13126. (setq align t)
  13127. (and (looking-at " *|") (goto-char (match-end 0))))
  13128. (goto-char match-end))
  13129. (when (looking-at
  13130. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  13131. (replace-match ""))
  13132. (when negative (insert " -"))
  13133. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  13134. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  13135. (insert " " (format fh h m))))
  13136. (when align (org-table-align))
  13137. (message "Time difference inserted")))))
  13138. (defun org-make-tdiff-string (y d h m)
  13139. (let ((fmt "")
  13140. (l nil))
  13141. (when (> y 0)
  13142. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  13143. (push y l))
  13144. (when (> d 0)
  13145. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  13146. (push d l))
  13147. (when (> h 0)
  13148. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  13149. (push h l))
  13150. (when (> m 0)
  13151. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  13152. (push m l))
  13153. (apply 'format fmt (nreverse l))))
  13154. (defun org-time-string-to-time (s)
  13155. "Convert timestamp string S into internal time."
  13156. (apply #'encode-time (org-parse-time-string s)))
  13157. (defun org-time-string-to-seconds (s)
  13158. "Convert a timestamp string S into a number of seconds."
  13159. (float-time (org-time-string-to-time s)))
  13160. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  13161. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  13162. "Convert time stamp S to an absolute day number.
  13163. If DAYNR in non-nil, and there is a specifier for a cyclic time
  13164. stamp, get the closest date to DAYNR. If PREFER is
  13165. `past' (respectively `future') return a date past (respectively
  13166. after) or equal to DAYNR.
  13167. POS is the location of time stamp S, as a buffer position in
  13168. BUFFER.
  13169. Diary sexp timestamps are matched against DAYNR, when non-nil.
  13170. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  13171. signaled."
  13172. (cond
  13173. ((string-match "\\`%%\\((.*)\\)" s)
  13174. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  13175. ;; only able to match individual dates. If it fails, raise an
  13176. ;; error.
  13177. (if (and daynr
  13178. (org-diary-sexp-entry
  13179. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  13180. daynr
  13181. (signal 'org-diary-sexp-no-match (list s))))
  13182. (daynr (org-closest-date s daynr prefer))
  13183. (t (time-to-days
  13184. (condition-case errdata
  13185. (org-time-string-to-time s)
  13186. (error (error "Bad timestamp `%s'%s\nError was: %s"
  13187. s
  13188. (if (not (and buffer pos)) ""
  13189. (format-message " at %d in buffer `%s'" pos buffer))
  13190. (cdr errdata))))))))
  13191. (defun org-days-to-iso-week (days)
  13192. "Return the iso week number."
  13193. (require 'cal-iso)
  13194. (car (calendar-iso-from-absolute days)))
  13195. (defun org-small-year-to-year (year)
  13196. "Convert 2-digit years into 4-digit years.
  13197. YEAR is expanded into one of the 30 next years, if possible, or
  13198. into a past one. Any year larger than 99 is returned unchanged."
  13199. (if (>= year 100) year
  13200. (let* ((current (string-to-number (format-time-string "%Y")))
  13201. (century (/ current 100))
  13202. (offset (- year (% current 100))))
  13203. (cond ((> offset 30) (+ (* (1- century) 100) year))
  13204. ((> offset -70) (+ (* century 100) year))
  13205. (t (+ (* (1+ century) 100) year))))))
  13206. (defun org-time-from-absolute (d)
  13207. "Return the time corresponding to date D.
  13208. D may be an absolute day number, or a calendar-type list (month day year)."
  13209. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  13210. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  13211. (defvar org-agenda-current-date)
  13212. (defun org-calendar-holiday ()
  13213. "List of holidays, for Diary display in Org mode."
  13214. (require 'holidays)
  13215. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  13216. (and hl (mapconcat #'identity hl "; "))))
  13217. (defun org-diary-sexp-entry (sexp entry d)
  13218. "Process a SEXP diary ENTRY for date D."
  13219. (require 'diary-lib)
  13220. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  13221. ;; dynamically.
  13222. (let* ((sexp `(let ((entry ,entry)
  13223. (date ',d))
  13224. ,(car (read-from-string sexp))))
  13225. (result (if calendar-debug-sexp (eval sexp)
  13226. (condition-case nil
  13227. (eval sexp)
  13228. (error
  13229. (beep)
  13230. (message "Bad sexp at line %d in %s: %s"
  13231. (org-current-line)
  13232. (buffer-file-name) sexp)
  13233. (sleep-for 2))))))
  13234. (cond ((stringp result) (split-string result "; "))
  13235. ((and (consp result)
  13236. (not (consp (cdr result)))
  13237. (stringp (cdr result))) (cdr result))
  13238. ((and (consp result)
  13239. (stringp (car result))) result)
  13240. (result entry))))
  13241. (defun org-diary-to-ical-string (frombuf)
  13242. "Get iCalendar entries from diary entries in buffer FROMBUF.
  13243. This uses the icalendar.el library."
  13244. (let* ((tmpdir temporary-file-directory)
  13245. (tmpfile (make-temp-name
  13246. (expand-file-name "orgics" tmpdir)))
  13247. buf rtn b e)
  13248. (with-current-buffer frombuf
  13249. (icalendar-export-region (point-min) (point-max) tmpfile)
  13250. (setq buf (find-buffer-visiting tmpfile))
  13251. (set-buffer buf)
  13252. (goto-char (point-min))
  13253. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  13254. (setq b (match-beginning 0)))
  13255. (goto-char (point-max))
  13256. (when (re-search-backward "^END:VEVENT" nil t)
  13257. (setq e (match-end 0)))
  13258. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  13259. (kill-buffer buf)
  13260. (delete-file tmpfile)
  13261. rtn))
  13262. (defun org-closest-date (start current prefer)
  13263. "Return closest date to CURRENT starting from START.
  13264. CURRENT and START are both time stamps.
  13265. When PREFER is `past', return a date that is either CURRENT or
  13266. past. When PREFER is `future', return a date that is either
  13267. CURRENT or future.
  13268. Only time stamps with a repeater are modified. Any other time
  13269. stamp stay unchanged. In any case, return value is an absolute
  13270. day number."
  13271. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  13272. ;; No repeater. Do not shift time stamp.
  13273. (time-to-days (org-time-string-to-time start))
  13274. (let ((value (string-to-number (match-string 1 start)))
  13275. (type (match-string 2 start)))
  13276. (if (= 0 value)
  13277. ;; Repeater with a 0-value is considered as void.
  13278. (time-to-days (org-time-string-to-time start))
  13279. (let* ((base (org-date-to-gregorian start))
  13280. (target (org-date-to-gregorian current))
  13281. (sday (calendar-absolute-from-gregorian base))
  13282. (cday (calendar-absolute-from-gregorian target))
  13283. n1 n2)
  13284. ;; If START is already past CURRENT, just return START.
  13285. (if (<= cday sday) sday
  13286. ;; Compute closest date before (N1) and closest date past
  13287. ;; (N2) CURRENT.
  13288. (pcase type
  13289. ("h"
  13290. (let ((missing-hours
  13291. (mod (+ (- (* 24 (- cday sday))
  13292. (nth 2 (org-parse-time-string start)))
  13293. org-extend-today-until)
  13294. value)))
  13295. (setf n1 (if (= missing-hours 0) cday
  13296. (- cday (1+ (/ missing-hours 24)))))
  13297. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  13298. ((or "d" "w")
  13299. (let ((value (if (equal type "w") (* 7 value) value)))
  13300. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  13301. (setf n2 (+ n1 value))))
  13302. ("m"
  13303. (let* ((add-months
  13304. (lambda (d n)
  13305. ;; Add N months to gregorian date D, i.e.,
  13306. ;; a list (MONTH DAY YEAR). Return a valid
  13307. ;; gregorian date.
  13308. (let ((m (+ (nth 0 d) n)))
  13309. (list (mod m 12)
  13310. (nth 1 d)
  13311. (+ (/ m 12) (nth 2 d))))))
  13312. (months ; Complete months to TARGET.
  13313. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  13314. (- (nth 0 target) (nth 0 base))
  13315. ;; If START's day is greater than
  13316. ;; TARGET's, remove incomplete month.
  13317. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  13318. value)
  13319. value))
  13320. (before (funcall add-months base months)))
  13321. (setf n1 (calendar-absolute-from-gregorian before))
  13322. (setf n2
  13323. (calendar-absolute-from-gregorian
  13324. (funcall add-months before value)))))
  13325. (_
  13326. (let* ((d (nth 1 base))
  13327. (m (nth 0 base))
  13328. (y (nth 2 base))
  13329. (years ; Complete years to TARGET.
  13330. (* (/ (- (nth 2 target)
  13331. y
  13332. ;; If START's month and day are
  13333. ;; greater than TARGET's, remove
  13334. ;; incomplete year.
  13335. (if (or (> (nth 0 target) m)
  13336. (and (= (nth 0 target) m)
  13337. (> (nth 1 target) d)))
  13338. 0
  13339. 1))
  13340. value)
  13341. value))
  13342. (before (list m d (+ y years))))
  13343. (setf n1 (calendar-absolute-from-gregorian before))
  13344. (setf n2 (calendar-absolute-from-gregorian
  13345. (list m d (+ (nth 2 before) value)))))))
  13346. ;; Handle PREFER parameter, if any.
  13347. (cond
  13348. ((eq prefer 'past) (if (= cday n2) n2 n1))
  13349. ((eq prefer 'future) (if (= cday n1) n1 n2))
  13350. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  13351. (defun org-date-to-gregorian (d)
  13352. "Turn any specification of date D into a Gregorian date for the calendar."
  13353. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  13354. ((and (listp d) (= (length d) 3)) d)
  13355. ((stringp d)
  13356. (let ((d (org-parse-time-string d)))
  13357. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  13358. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  13359. (defun org-timestamp-up (&optional arg)
  13360. "Increase the date item at the cursor by one.
  13361. If the cursor is on the year, change the year. If it is on the month,
  13362. the day or the time, change that. If the cursor is on the enclosing
  13363. bracket, change the timestamp type.
  13364. With prefix ARG, change by that many units."
  13365. (interactive "p")
  13366. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  13367. (defun org-timestamp-down (&optional arg)
  13368. "Decrease the date item at the cursor by one.
  13369. If the cursor is on the year, change the year. If it is on the month,
  13370. the day or the time, change that. If the cursor is on the enclosing
  13371. bracket, change the timestamp type.
  13372. With prefix ARG, change by that many units."
  13373. (interactive "p")
  13374. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  13375. (defun org-timestamp-up-day (&optional arg)
  13376. "Increase the date in the time stamp by one day.
  13377. With prefix ARG, change that many days."
  13378. (interactive "p")
  13379. (if (and (not (org-at-timestamp-p 'lax))
  13380. (org-at-heading-p))
  13381. (org-todo 'up)
  13382. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  13383. (defun org-timestamp-down-day (&optional arg)
  13384. "Decrease the date in the time stamp by one day.
  13385. With prefix ARG, change that many days."
  13386. (interactive "p")
  13387. (if (and (not (org-at-timestamp-p 'lax))
  13388. (org-at-heading-p))
  13389. (org-todo 'down)
  13390. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  13391. (defun org-at-timestamp-p (&optional extended)
  13392. "Non-nil if point is inside a timestamp.
  13393. By default, the function only consider syntactically valid active
  13394. timestamps. However, the caller may have a broader definition
  13395. for timestamps. As a consequence, optional argument EXTENDED can
  13396. be set to the following values
  13397. `inactive'
  13398. Include also syntactically valid inactive timestamps.
  13399. `agenda'
  13400. Include timestamps allowed in Agenda, i.e., those in
  13401. properties drawers, planning lines and clock lines.
  13402. `lax'
  13403. Ignore context. The function matches any part of the
  13404. document looking like a timestamp. This includes comments,
  13405. example blocks...
  13406. For backward-compatibility with Org 9.0, every other non-nil
  13407. value is equivalent to `inactive'.
  13408. When at a timestamp, return the position of the point as a symbol
  13409. among `bracket', `after', `year', `month', `hour', `minute',
  13410. `day' or a number of character from the last know part of the
  13411. time stamp.
  13412. When matching, the match groups are the following:
  13413. group 1: year
  13414. group 2: month
  13415. group 3: day number
  13416. group 4: day name
  13417. group 5: hours, if any
  13418. group 6: minutes, if any"
  13419. (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
  13420. (pos (point))
  13421. (match?
  13422. (let ((boundaries (org-in-regexp regexp)))
  13423. (save-match-data
  13424. (cond ((null boundaries) nil)
  13425. ((eq extended 'lax) t)
  13426. (t
  13427. (or (and (eq extended 'agenda)
  13428. (or (org-at-planning-p)
  13429. (org-at-property-p)
  13430. (and (bound-and-true-p
  13431. org-agenda-include-inactive-timestamps)
  13432. (org-at-clock-log-p))))
  13433. (eq 'timestamp
  13434. (save-excursion
  13435. (when (= pos (cdr boundaries)) (forward-char -1))
  13436. (org-element-type (org-element-context)))))))))))
  13437. (cond
  13438. ((not match?) nil)
  13439. ((= pos (match-beginning 0)) 'bracket)
  13440. ;; Distinguish location right before the closing bracket from
  13441. ;; right after it.
  13442. ((= pos (1- (match-end 0))) 'bracket)
  13443. ((= pos (match-end 0)) 'after)
  13444. ((org-pos-in-match-range pos 2) 'year)
  13445. ((org-pos-in-match-range pos 3) 'month)
  13446. ((org-pos-in-match-range pos 7) 'hour)
  13447. ((org-pos-in-match-range pos 8) 'minute)
  13448. ((or (org-pos-in-match-range pos 4)
  13449. (org-pos-in-match-range pos 5)) 'day)
  13450. ((and (> pos (or (match-end 8) (match-end 5)))
  13451. (< pos (match-end 0)))
  13452. (- pos (or (match-end 8) (match-end 5))))
  13453. (t 'day))))
  13454. (defun org-toggle-timestamp-type ()
  13455. "Toggle the type (<active> or [inactive]) of a time stamp."
  13456. (interactive)
  13457. (when (org-at-timestamp-p 'lax)
  13458. (let ((beg (match-beginning 0)) (end (match-end 0))
  13459. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  13460. (save-excursion
  13461. (goto-char beg)
  13462. (while (re-search-forward "[][<>]" end t)
  13463. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  13464. t t)))
  13465. (message "Timestamp is now %sactive"
  13466. (if (equal (char-after beg) ?<) "" "in")))))
  13467. (defun org-at-clock-log-p ()
  13468. "Non-nil if point is on a clock log line."
  13469. (and (org-match-line org-clock-line-re)
  13470. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  13471. (defvar org-clock-history) ; defined in org-clock.el
  13472. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  13473. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  13474. "Change the date in the time stamp at point.
  13475. The date is changed by N times WHAT. WHAT can be `day', `month',
  13476. `year', `hour', or `minute'. If WHAT is not given, the cursor
  13477. position in the timestamp determines what is changed.
  13478. When optional argument UPDOWN is non-nil, minutes are rounded
  13479. according to `org-time-stamp-rounding-minutes'.
  13480. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like
  13481. \"--2d\"."
  13482. (let ((origin (point))
  13483. (timestamp? (org-at-timestamp-p 'lax))
  13484. origin-cat
  13485. with-hm inactive
  13486. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  13487. extra rem
  13488. ts time time0 fixnext clrgx)
  13489. (unless timestamp? (user-error "Not at a timestamp"))
  13490. (if (and (not what) (eq timestamp? 'bracket))
  13491. (org-toggle-timestamp-type)
  13492. ;; Point isn't on brackets. Remember the part of the time-stamp
  13493. ;; the point was in. Indeed, size of time-stamps may change,
  13494. ;; but point must be kept in the same category nonetheless.
  13495. (setq origin-cat timestamp?)
  13496. (when (and (not what) (not (eq timestamp? 'day))
  13497. org-display-custom-times
  13498. (get-text-property (point) 'display)
  13499. (not (get-text-property (1- (point)) 'display)))
  13500. (setq timestamp? 'day))
  13501. (setq timestamp? (or what timestamp?)
  13502. inactive (= (char-after (match-beginning 0)) ?\[)
  13503. ts (match-string 0))
  13504. (replace-match "")
  13505. (when (string-match
  13506. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  13507. ts)
  13508. (setq extra (match-string 1 ts))
  13509. (when suppress-tmp-delay
  13510. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  13511. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  13512. (setq with-hm t))
  13513. (setq time0 (org-parse-time-string ts))
  13514. (when (and updown
  13515. (eq timestamp? 'minute)
  13516. (not current-prefix-arg))
  13517. ;; This looks like s-up and s-down. Change by one rounding step.
  13518. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  13519. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  13520. (setcar (cdr time0) (+ (nth 1 time0)
  13521. (if (> n 0) (- rem) (- dm rem))))))
  13522. (setq time
  13523. (apply #'encode-time
  13524. (or (car time0) 0)
  13525. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  13526. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  13527. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  13528. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  13529. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  13530. (nthcdr 6 time0)))
  13531. (when (and (memq timestamp? '(hour minute))
  13532. extra
  13533. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  13534. (setq extra (org-modify-ts-extra
  13535. extra
  13536. (if (eq timestamp? 'hour) 2 5)
  13537. n dm)))
  13538. (when (integerp timestamp?)
  13539. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  13540. (when (eq what 'calendar)
  13541. (let ((cal-date (org-get-date-from-calendar)))
  13542. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  13543. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  13544. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  13545. (setcar time0 (or (car time0) 0))
  13546. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  13547. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  13548. (setq time (apply 'encode-time time0))))
  13549. ;; Insert the new time-stamp, and ensure point stays in the same
  13550. ;; category as before (i.e. not after the last position in that
  13551. ;; category).
  13552. (let ((pos (point)))
  13553. ;; Stay before inserted string. `save-excursion' is of no use.
  13554. (setq org-last-changed-timestamp
  13555. (org-insert-time-stamp time with-hm inactive nil nil extra))
  13556. (goto-char pos))
  13557. (save-match-data
  13558. (looking-at org-ts-regexp3)
  13559. (goto-char
  13560. (pcase origin-cat
  13561. ;; `day' category ends before `hour' if any, or at the end
  13562. ;; of the day name.
  13563. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  13564. (`hour (min (match-end 7) origin))
  13565. (`minute (min (1- (match-end 8)) origin))
  13566. ((pred integerp) (min (1- (match-end 0)) origin))
  13567. ;; Point was right after the time-stamp. However, the
  13568. ;; time-stamp length might have changed, so refer to
  13569. ;; (match-end 0) instead.
  13570. (`after (match-end 0))
  13571. ;; `year' and `month' have both fixed size: point couldn't
  13572. ;; have moved into another part.
  13573. (_ origin))))
  13574. ;; Update clock if on a CLOCK line.
  13575. (org-clock-update-time-maybe)
  13576. ;; Maybe adjust the closest clock in `org-clock-history'
  13577. (when org-clock-adjust-closest
  13578. (if (not (and (org-at-clock-log-p)
  13579. (< 1 (length (delq nil (mapcar 'marker-position
  13580. org-clock-history))))))
  13581. (message "No clock to adjust")
  13582. (cond ((save-excursion ; fix previous clock?
  13583. (re-search-backward org-ts-regexp0 nil t)
  13584. (looking-back (concat org-clock-string " \\[")
  13585. (line-beginning-position)))
  13586. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  13587. ((save-excursion ; fix next clock?
  13588. (re-search-backward org-ts-regexp0 nil t)
  13589. (looking-at (concat org-ts-regexp0 "\\] =>")))
  13590. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  13591. (save-window-excursion
  13592. ;; Find closest clock to point, adjust the previous/next one in history
  13593. (let* ((p (save-excursion (org-back-to-heading t)))
  13594. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  13595. (clfixnth
  13596. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  13597. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  13598. (if (not clfixpos)
  13599. (message "No clock to adjust")
  13600. (save-excursion
  13601. (org-goto-marker-or-bmk clfixpos)
  13602. (org-show-subtree)
  13603. (when (re-search-forward clrgx nil t)
  13604. (goto-char (match-beginning 1))
  13605. (let (org-clock-adjust-closest)
  13606. (org-timestamp-change n timestamp? updown))
  13607. (message "Clock adjusted in %s for heading: %s"
  13608. (file-name-nondirectory (buffer-file-name))
  13609. (org-get-heading t t)))))))))
  13610. ;; Try to recenter the calendar window, if any.
  13611. (when (and org-calendar-follow-timestamp-change
  13612. (get-buffer-window "*Calendar*" t)
  13613. (memq timestamp? '(day month year)))
  13614. (org-recenter-calendar (time-to-days time))))))
  13615. (defun org-modify-ts-extra (s pos n dm)
  13616. "Change the different parts of the lead-time and repeat fields in timestamp."
  13617. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  13618. ng h m new rem)
  13619. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  13620. (cond
  13621. ((or (org-pos-in-match-range pos 2)
  13622. (org-pos-in-match-range pos 3))
  13623. (setq m (string-to-number (match-string 3 s))
  13624. h (string-to-number (match-string 2 s)))
  13625. (if (org-pos-in-match-range pos 2)
  13626. (setq h (+ h n))
  13627. (setq n (* dm (with-no-warnings (cl-signum n))))
  13628. (unless (= 0 (setq rem (% m dm)))
  13629. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  13630. (setq m (+ m n)))
  13631. (when (< m 0) (setq m (+ m 60) h (1- h)))
  13632. (when (> m 59) (setq m (- m 60) h (1+ h)))
  13633. (setq h (mod h 24))
  13634. (setq ng 1 new (format "-%02d:%02d" h m)))
  13635. ((org-pos-in-match-range pos 6)
  13636. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  13637. ((org-pos-in-match-range pos 5)
  13638. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  13639. ((org-pos-in-match-range pos 9)
  13640. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  13641. ((org-pos-in-match-range pos 8)
  13642. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  13643. (when ng
  13644. (setq s (concat
  13645. (substring s 0 (match-beginning ng))
  13646. new
  13647. (substring s (match-end ng))))))
  13648. s))
  13649. (defun org-recenter-calendar (d)
  13650. "If the calendar is visible, recenter it to date D."
  13651. (let ((cwin (get-buffer-window "*Calendar*" t)))
  13652. (when cwin
  13653. (let ((calendar-move-hook nil))
  13654. (with-selected-window cwin
  13655. (calendar-goto-date
  13656. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  13657. (defun org-goto-calendar (&optional arg)
  13658. "Go to the Emacs calendar at the current date.
  13659. If there is a time stamp in the current line, go to that date.
  13660. A prefix ARG can be used to force the current date."
  13661. (interactive "P")
  13662. (let ((calendar-move-hook nil)
  13663. (calendar-view-holidays-initially-flag nil)
  13664. (calendar-view-diary-initially-flag nil)
  13665. diff)
  13666. (when (or (org-at-timestamp-p 'lax)
  13667. (org-match-line (concat ".*" org-ts-regexp)))
  13668. (let ((d1 (time-to-days nil))
  13669. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  13670. (setq diff (- d2 d1))))
  13671. (calendar)
  13672. (calendar-goto-today)
  13673. (when (and diff (not arg)) (calendar-forward-day diff))))
  13674. (defun org-get-date-from-calendar ()
  13675. "Return a list (month day year) of date at point in calendar."
  13676. (with-current-buffer "*Calendar*"
  13677. (save-match-data
  13678. (calendar-cursor-to-date))))
  13679. (defun org-date-from-calendar ()
  13680. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  13681. If there is already a time stamp at the cursor position, update it."
  13682. (interactive)
  13683. (if (org-at-timestamp-p 'lax)
  13684. (org-timestamp-change 0 'calendar)
  13685. (let ((cal-date (org-get-date-from-calendar)))
  13686. (org-insert-time-stamp
  13687. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  13688. (defcustom org-image-actual-width t
  13689. "When non-nil, use the actual width of images when inlining them.
  13690. When set to a number, use imagemagick (when available) to set the
  13691. image's width to this value.
  13692. When set to a number in a list, try to get the width from any
  13693. #+ATTR.* keyword if it matches a width specification like
  13694. #+ATTR_HTML: :width 300px
  13695. and fall back on that number if none is found.
  13696. When set to nil, try to get the width from an #+ATTR.* keyword
  13697. and fall back on the original width if none is found.
  13698. When set to any other non-nil value, always use the image width.
  13699. This requires Emacs >= 24.1, built with imagemagick support."
  13700. :group 'org-appearance
  13701. :version "24.4"
  13702. :package-version '(Org . "8.0")
  13703. :type '(choice
  13704. (const :tag "Use the image width" t)
  13705. (integer :tag "Use a number of pixels")
  13706. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  13707. (const :tag "Use #+ATTR* or don't resize" nil)))
  13708. (defcustom org-agenda-inhibit-startup nil
  13709. "Inhibit startup when preparing agenda buffers.
  13710. When this variable is t, the initialization of the Org agenda
  13711. buffers is inhibited: e.g. the visibility state is not set, the
  13712. tables are not re-aligned, etc."
  13713. :type 'boolean
  13714. :version "24.3"
  13715. :group 'org-agenda)
  13716. (defcustom org-agenda-ignore-properties nil
  13717. "Avoid updating text properties when building the agenda.
  13718. Properties are used to prepare buffers for effort estimates,
  13719. appointments, statistics and subtree-local categories.
  13720. If you don't use these in the agenda, you can add them to this
  13721. list and agenda building will be a bit faster.
  13722. The value is a list, with zero or more of the symbols `effort', `appt',
  13723. `stats' or `category'."
  13724. :type '(set :greedy t
  13725. (const effort)
  13726. (const appt)
  13727. (const stats)
  13728. (const category))
  13729. :version "26.1"
  13730. :package-version '(Org . "8.3")
  13731. :group 'org-agenda)
  13732. ;;;; Files
  13733. (defun org-save-all-org-buffers ()
  13734. "Save all Org buffers without user confirmation."
  13735. (interactive)
  13736. (message "Saving all Org buffers...")
  13737. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  13738. (when (featurep 'org-id) (org-id-locations-save))
  13739. (message "Saving all Org buffers... done"))
  13740. (defun org-revert-all-org-buffers ()
  13741. "Revert all Org buffers.
  13742. Prompt for confirmation when there are unsaved changes.
  13743. Be sure you know what you are doing before letting this function
  13744. overwrite your changes.
  13745. This function is useful in a setup where one tracks Org files
  13746. with a version control system, to revert on one machine after pulling
  13747. changes from another. I believe the procedure must be like this:
  13748. 1. M-x org-save-all-org-buffers
  13749. 2. Pull changes from the other machine, resolve conflicts
  13750. 3. M-x org-revert-all-org-buffers"
  13751. (interactive)
  13752. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  13753. (user-error "Abort"))
  13754. (save-excursion
  13755. (save-window-excursion
  13756. (dolist (b (buffer-list))
  13757. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  13758. (with-current-buffer b buffer-file-name))
  13759. (pop-to-buffer-same-window b)
  13760. (revert-buffer t 'no-confirm)))
  13761. (when (and (featurep 'org-id) org-id-track-globally)
  13762. (org-id-locations-load)))))
  13763. ;;;; Agenda files
  13764. ;;;###autoload
  13765. (defun org-switchb (&optional arg)
  13766. "Switch between Org buffers.
  13767. With `\\[universal-argument]' prefix, restrict available buffers to files.
  13768. With `\\[universal-argument] \\[universal-argument]' \
  13769. prefix, restrict available buffers to agenda files."
  13770. (interactive "P")
  13771. (let ((blist (org-buffer-list
  13772. (cond ((equal arg '(4)) 'files)
  13773. ((equal arg '(16)) 'agenda)))))
  13774. (pop-to-buffer-same-window
  13775. (completing-read "Org buffer: "
  13776. (mapcar #'list (mapcar #'buffer-name blist))
  13777. nil t))))
  13778. (defun org-buffer-list (&optional predicate exclude-tmp)
  13779. "Return a list of Org buffers.
  13780. PREDICATE can be `export', `files' or `agenda'.
  13781. export restrict the list to Export buffers.
  13782. files restrict the list to buffers visiting Org files.
  13783. agenda restrict the list to buffers visiting agenda files.
  13784. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  13785. (let* ((bfn nil)
  13786. (agenda-files (and (eq predicate 'agenda)
  13787. (mapcar 'file-truename (org-agenda-files t))))
  13788. (filter
  13789. (cond
  13790. ((eq predicate 'files)
  13791. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  13792. ((eq predicate 'export)
  13793. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  13794. ((eq predicate 'agenda)
  13795. (lambda (b)
  13796. (with-current-buffer b
  13797. (and (derived-mode-p 'org-mode)
  13798. (setq bfn (buffer-file-name b))
  13799. (member (file-truename bfn) agenda-files)))))
  13800. (t (lambda (b) (with-current-buffer b
  13801. (or (derived-mode-p 'org-mode)
  13802. (string-match "\\*Org .*Export"
  13803. (buffer-name b)))))))))
  13804. (delq nil
  13805. (mapcar
  13806. (lambda(b)
  13807. (if (and (funcall filter b)
  13808. (or (not exclude-tmp)
  13809. (not (string-match "tmp" (buffer-name b)))))
  13810. b
  13811. nil))
  13812. (buffer-list)))))
  13813. (defun org-agenda-files (&optional unrestricted archives)
  13814. "Get the list of agenda files.
  13815. Optional UNRESTRICTED means return the full list even if a restriction
  13816. is currently in place.
  13817. When ARCHIVES is t, include all archive files that are really being
  13818. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  13819. `org-agenda-archives-mode' is t."
  13820. (let ((files
  13821. (cond
  13822. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  13823. ((stringp org-agenda-files) (org-read-agenda-file-list))
  13824. ((listp org-agenda-files) org-agenda-files)
  13825. (t (error "Invalid value of `org-agenda-files'")))))
  13826. (setq files (apply 'append
  13827. (mapcar (lambda (f)
  13828. (if (file-directory-p f)
  13829. (directory-files
  13830. f t org-agenda-file-regexp)
  13831. (list f)))
  13832. files)))
  13833. (when org-agenda-skip-unavailable-files
  13834. (setq files (delq nil
  13835. (mapcar (function
  13836. (lambda (file)
  13837. (and (file-readable-p file) file)))
  13838. files))))
  13839. (when (or (eq archives t)
  13840. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  13841. (setq files (org-add-archive-files files)))
  13842. files))
  13843. (defun org-agenda-file-p (&optional file)
  13844. "Return non-nil, if FILE is an agenda file.
  13845. If FILE is omitted, use the file associated with the current
  13846. buffer."
  13847. (let ((fname (or file (buffer-file-name))))
  13848. (and fname
  13849. (member (file-truename fname)
  13850. (mapcar #'file-truename (org-agenda-files t))))))
  13851. (defun org-edit-agenda-file-list ()
  13852. "Edit the list of agenda files.
  13853. Depending on setup, this either uses customize to edit the variable
  13854. `org-agenda-files', or it visits the file that is holding the list. In the
  13855. latter case, the buffer is set up in a way that saving it automatically kills
  13856. the buffer and restores the previous window configuration."
  13857. (interactive)
  13858. (if (stringp org-agenda-files)
  13859. (let ((cw (current-window-configuration)))
  13860. (find-file org-agenda-files)
  13861. (setq-local org-window-configuration cw)
  13862. (add-hook 'after-save-hook
  13863. (lambda ()
  13864. (set-window-configuration
  13865. (prog1 org-window-configuration
  13866. (kill-buffer (current-buffer))))
  13867. (org-install-agenda-files-menu)
  13868. (message "New agenda file list installed"))
  13869. nil 'local)
  13870. (message "%s" (substitute-command-keys
  13871. "Edit list and finish with \\[save-buffer]")))
  13872. (customize-variable 'org-agenda-files)))
  13873. (defun org-store-new-agenda-file-list (list)
  13874. "Set new value for the agenda file list and save it correctly."
  13875. (if (stringp org-agenda-files)
  13876. (let ((fe (org-read-agenda-file-list t)) b u)
  13877. (while (setq b (find-buffer-visiting org-agenda-files))
  13878. (kill-buffer b))
  13879. (with-temp-file org-agenda-files
  13880. (insert
  13881. (mapconcat
  13882. (lambda (f) ;; Keep un-expanded entries.
  13883. (if (setq u (assoc f fe))
  13884. (cdr u)
  13885. f))
  13886. list "\n")
  13887. "\n")))
  13888. (let ((org-mode-hook nil) (org-inhibit-startup t)
  13889. (org-insert-mode-line-in-empty-file nil))
  13890. (setq org-agenda-files list)
  13891. (customize-save-variable 'org-agenda-files org-agenda-files))))
  13892. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  13893. "Read the list of agenda files from a file.
  13894. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  13895. filenames, used by `org-store-new-agenda-file-list' to write back
  13896. un-expanded file names."
  13897. (when (file-directory-p org-agenda-files)
  13898. (error "`org-agenda-files' cannot be a single directory"))
  13899. (when (stringp org-agenda-files)
  13900. (with-temp-buffer
  13901. (insert-file-contents org-agenda-files)
  13902. (mapcar
  13903. (lambda (f)
  13904. (let ((e (expand-file-name (substitute-in-file-name f)
  13905. org-directory)))
  13906. (if pair-with-expansion
  13907. (cons e f)
  13908. e)))
  13909. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  13910. ;;;###autoload
  13911. (defun org-cycle-agenda-files ()
  13912. "Cycle through the files in `org-agenda-files'.
  13913. If the current buffer visits an agenda file, find the next one in the list.
  13914. If the current buffer does not, find the first agenda file."
  13915. (interactive)
  13916. (let* ((fs (or (org-agenda-files t)
  13917. (user-error "No agenda files")))
  13918. (files (copy-sequence fs))
  13919. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  13920. file)
  13921. (when tcf
  13922. (while (and (setq file (pop files))
  13923. (not (equal (file-truename file) tcf)))))
  13924. (find-file (car (or files fs)))
  13925. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  13926. (defun org-agenda-file-to-front (&optional to-end)
  13927. "Move/add the current file to the top of the agenda file list.
  13928. If the file is not present in the list, it is added to the front. If it is
  13929. present, it is moved there. With optional argument TO-END, add/move to the
  13930. end of the list."
  13931. (interactive "P")
  13932. (let ((org-agenda-skip-unavailable-files nil)
  13933. (file-alist (mapcar (lambda (x)
  13934. (cons (file-truename x) x))
  13935. (org-agenda-files t)))
  13936. (ctf (file-truename
  13937. (or buffer-file-name
  13938. (user-error "Please save the current buffer to a file"))))
  13939. x had)
  13940. (setq x (assoc ctf file-alist) had x)
  13941. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  13942. (if to-end
  13943. (setq file-alist (append (delq x file-alist) (list x)))
  13944. (setq file-alist (cons x (delq x file-alist))))
  13945. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  13946. (org-install-agenda-files-menu)
  13947. (message "File %s to %s of agenda file list"
  13948. (if had "moved" "added") (if to-end "end" "front"))))
  13949. (defun org-remove-file (&optional file)
  13950. "Remove current file from the list of files in variable `org-agenda-files'.
  13951. These are the files which are being checked for agenda entries.
  13952. Optional argument FILE means use this file instead of the current."
  13953. (interactive)
  13954. (let* ((org-agenda-skip-unavailable-files nil)
  13955. (file (or file buffer-file-name
  13956. (user-error "Current buffer does not visit a file")))
  13957. (true-file (file-truename file))
  13958. (afile (abbreviate-file-name file))
  13959. (files (delq nil (mapcar
  13960. (lambda (x)
  13961. (unless (equal true-file
  13962. (file-truename x))
  13963. x))
  13964. (org-agenda-files t)))))
  13965. (if (not (= (length files) (length (org-agenda-files t))))
  13966. (progn
  13967. (org-store-new-agenda-file-list files)
  13968. (org-install-agenda-files-menu)
  13969. (message "Removed from Org Agenda list: %s" afile))
  13970. (message "File was not in list: %s (not removed)" afile))))
  13971. (defun org-file-menu-entry (file)
  13972. (vector file (list 'find-file file) t))
  13973. (defun org-check-agenda-file (file)
  13974. "Make sure FILE exists. If not, ask user what to do."
  13975. (unless (file-exists-p file)
  13976. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  13977. (abbreviate-file-name file))
  13978. (let ((r (downcase (read-char-exclusive))))
  13979. (cond
  13980. ((equal r ?r)
  13981. (org-remove-file file)
  13982. (throw 'nextfile t))
  13983. (t (user-error "Abort"))))))
  13984. (defun org-get-agenda-file-buffer (file)
  13985. "Get an agenda buffer visiting FILE.
  13986. If the buffer needs to be created, add it to the list of buffers
  13987. which might be released later."
  13988. (let ((buf (org-find-base-buffer-visiting file)))
  13989. (if buf
  13990. buf ; just return it
  13991. ;; Make a new buffer and remember it
  13992. (setq buf (find-file-noselect file))
  13993. (when buf (push buf org-agenda-new-buffers))
  13994. buf)))
  13995. (defun org-release-buffers (blist)
  13996. "Release all buffers in list, asking the user for confirmation when needed.
  13997. When a buffer is unmodified, it is just killed. When modified, it is saved
  13998. \(if the user agrees) and then killed."
  13999. (let (file)
  14000. (dolist (buf blist)
  14001. (setq file (buffer-file-name buf))
  14002. (when (and (buffer-modified-p buf)
  14003. file
  14004. (y-or-n-p (format "Save file %s? " file)))
  14005. (with-current-buffer buf (save-buffer)))
  14006. (kill-buffer buf))))
  14007. (defun org-agenda-prepare-buffers (files)
  14008. "Create buffers for all agenda files, protect archived trees and comments."
  14009. (interactive)
  14010. (let ((pa '(:org-archived t))
  14011. (pc '(:org-comment t))
  14012. (pall '(:org-archived t :org-comment t))
  14013. (inhibit-read-only t)
  14014. (org-inhibit-startup org-agenda-inhibit-startup)
  14015. (rea (org-make-tag-string (list org-archive-tag)))
  14016. re pos)
  14017. (setq org-tag-alist-for-agenda nil
  14018. org-tag-groups-alist-for-agenda nil)
  14019. (save-excursion
  14020. (save-restriction
  14021. (dolist (file files)
  14022. (catch 'nextfile
  14023. (if (bufferp file)
  14024. (set-buffer file)
  14025. (org-check-agenda-file file)
  14026. (set-buffer (org-get-agenda-file-buffer file)))
  14027. (widen)
  14028. (org-set-regexps-and-options 'tags-only)
  14029. (setq pos (point))
  14030. (or (memq 'category org-agenda-ignore-properties)
  14031. (org-refresh-category-properties))
  14032. (or (memq 'stats org-agenda-ignore-properties)
  14033. (org-refresh-stats-properties))
  14034. (or (memq 'effort org-agenda-ignore-properties)
  14035. (org-refresh-effort-properties))
  14036. (or (memq 'appt org-agenda-ignore-properties)
  14037. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  14038. (setq org-todo-keywords-for-agenda
  14039. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  14040. (setq org-done-keywords-for-agenda
  14041. (append org-done-keywords-for-agenda org-done-keywords))
  14042. (setq org-todo-keyword-alist-for-agenda
  14043. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  14044. (setq org-tag-alist-for-agenda
  14045. (org--tag-add-to-alist
  14046. org-tag-alist-for-agenda
  14047. org-current-tag-alist))
  14048. ;; Merge current file's tag groups into global
  14049. ;; `org-tag-groups-alist-for-agenda'.
  14050. (when org-group-tags
  14051. (dolist (alist org-tag-groups-alist)
  14052. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  14053. (if old
  14054. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  14055. (push alist org-tag-groups-alist-for-agenda)))))
  14056. (with-silent-modifications
  14057. (save-excursion
  14058. (remove-text-properties (point-min) (point-max) pall)
  14059. (when org-agenda-skip-archived-trees
  14060. (goto-char (point-min))
  14061. (while (re-search-forward rea nil t)
  14062. (when (org-at-heading-p t)
  14063. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  14064. (goto-char (point-min))
  14065. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  14066. (while (re-search-forward re nil t)
  14067. (when (save-match-data (org-in-commented-heading-p t))
  14068. (add-text-properties
  14069. (match-beginning 0) (org-end-of-subtree t) pc)))))
  14070. (goto-char pos)))))
  14071. (setq org-todo-keywords-for-agenda
  14072. (org-uniquify org-todo-keywords-for-agenda))
  14073. (setq org-todo-keyword-alist-for-agenda
  14074. (org-uniquify org-todo-keyword-alist-for-agenda))))
  14075. ;;;; CDLaTeX minor mode
  14076. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  14077. "Keymap for the minor `org-cdlatex-mode'.")
  14078. (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
  14079. (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
  14080. (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
  14081. (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
  14082. (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
  14083. (defvar org-cdlatex-texmathp-advice-is-done nil
  14084. "Flag remembering if we have applied the advice to texmathp already.")
  14085. (define-minor-mode org-cdlatex-mode
  14086. "Toggle the minor `org-cdlatex-mode'.
  14087. This mode supports entering LaTeX environment and math in LaTeX fragments
  14088. in Org mode.
  14089. \\{org-cdlatex-mode-map}"
  14090. nil " OCDL" nil
  14091. (when org-cdlatex-mode
  14092. (require 'cdlatex)
  14093. (run-hooks 'cdlatex-mode-hook)
  14094. (cdlatex-compute-tables))
  14095. (unless org-cdlatex-texmathp-advice-is-done
  14096. (setq org-cdlatex-texmathp-advice-is-done t)
  14097. (defadvice texmathp (around org-math-always-on activate)
  14098. "Always return t in Org buffers.
  14099. This is because we want to insert math symbols without dollars even outside
  14100. the LaTeX math segments. If Org mode thinks that point is actually inside
  14101. an embedded LaTeX fragment, let `texmathp' do its job.
  14102. `\\[org-cdlatex-mode-map]'"
  14103. (interactive)
  14104. (let (p)
  14105. (cond
  14106. ((not (derived-mode-p 'org-mode)) ad-do-it)
  14107. ((eq this-command 'cdlatex-math-symbol)
  14108. (setq ad-return-value t
  14109. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  14110. (t
  14111. (let ((p (org-inside-LaTeX-fragment-p)))
  14112. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  14113. (setq ad-return-value t
  14114. texmathp-why '("Org mode embedded math" . 0))
  14115. (when p ad-do-it)))))))))
  14116. (defun turn-on-org-cdlatex ()
  14117. "Unconditionally turn on `org-cdlatex-mode'."
  14118. (org-cdlatex-mode 1))
  14119. (defun org-try-cdlatex-tab ()
  14120. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  14121. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  14122. - inside a LaTeX fragment, or
  14123. - after the first word in a line, where an abbreviation expansion could
  14124. insert a LaTeX environment."
  14125. (when org-cdlatex-mode
  14126. (cond
  14127. ;; Before any word on the line: No expansion possible.
  14128. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  14129. ;; Just after first word on the line: Expand it. Make sure it
  14130. ;; cannot happen on headlines, though.
  14131. ((save-excursion
  14132. (skip-chars-backward "a-zA-Z0-9*")
  14133. (skip-chars-backward " \t")
  14134. (and (bolp) (not (org-at-heading-p))))
  14135. (cdlatex-tab) t)
  14136. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  14137. (defun org-cdlatex-underscore-caret (&optional _arg)
  14138. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  14139. Revert to the normal definition outside of these fragments."
  14140. (interactive "P")
  14141. (if (org-inside-LaTeX-fragment-p)
  14142. (call-interactively 'cdlatex-sub-superscript)
  14143. (let (org-cdlatex-mode)
  14144. (call-interactively (key-binding (vector last-input-event))))))
  14145. (defun org-cdlatex-math-modify (&optional _arg)
  14146. "Execute `cdlatex-math-modify' in LaTeX fragments.
  14147. Revert to the normal definition outside of these fragments."
  14148. (interactive "P")
  14149. (if (org-inside-LaTeX-fragment-p)
  14150. (call-interactively 'cdlatex-math-modify)
  14151. (let (org-cdlatex-mode)
  14152. (call-interactively (key-binding (vector last-input-event))))))
  14153. (defun org-cdlatex-environment-indent (&optional environment item)
  14154. "Execute `cdlatex-environment' and indent the inserted environment.
  14155. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  14156. The inserted environment is indented to current indentation
  14157. unless point is at the beginning of the line, in which the
  14158. environment remains unintended."
  14159. (interactive)
  14160. ;; cdlatex-environment always return nil. Therefore, capture output
  14161. ;; first and determine if an environment was selected.
  14162. (let* ((beg (point-marker))
  14163. (end (copy-marker (point) t))
  14164. (inserted (progn
  14165. (ignore-errors (cdlatex-environment environment item))
  14166. (< beg end)))
  14167. ;; Figure out how many lines to move forward after the
  14168. ;; environment has been inserted.
  14169. (lines (when inserted
  14170. (save-excursion
  14171. (- (cl-loop while (< beg (point))
  14172. with x = 0
  14173. do (forward-line -1)
  14174. (cl-incf x)
  14175. finally return x)
  14176. (if (progn (goto-char beg)
  14177. (and (progn (skip-chars-forward " \t") (eolp))
  14178. (progn (skip-chars-backward " \t") (bolp))))
  14179. 1 0)))))
  14180. (env (org-trim (delete-and-extract-region beg end))))
  14181. (when inserted
  14182. ;; Get indentation of next line unless at column 0.
  14183. (let ((ind (if (bolp) 0
  14184. (save-excursion
  14185. (org-return-indent)
  14186. (prog1 (current-indentation)
  14187. (when (progn (skip-chars-forward " \t") (eolp))
  14188. (delete-region beg (point)))))))
  14189. (bol (progn (skip-chars-backward " \t") (bolp))))
  14190. ;; Insert a newline before environment unless at column zero
  14191. ;; to "escape" the current line. Insert a newline if
  14192. ;; something is one the same line as \end{ENVIRONMENT}.
  14193. (insert
  14194. (concat (unless bol "\n") env
  14195. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  14196. (unless (zerop ind)
  14197. (save-excursion
  14198. (goto-char beg)
  14199. (while (< (point) end)
  14200. (unless (eolp) (indent-line-to ind))
  14201. (forward-line))))
  14202. (goto-char beg)
  14203. (forward-line lines)
  14204. (indent-line-to ind)))
  14205. (set-marker beg nil)
  14206. (set-marker end nil)))
  14207. ;;;; LaTeX fragments
  14208. (defun org-inside-LaTeX-fragment-p ()
  14209. "Test if point is inside a LaTeX fragment.
  14210. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  14211. sequence appearing also before point.
  14212. Even though the matchers for math are configurable, this function assumes
  14213. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  14214. delimiters are skipped when they have been removed by customization.
  14215. The return value is nil, or a cons cell with the delimiter and the
  14216. position of this delimiter.
  14217. This function does a reasonably good job, but can locally be fooled by
  14218. for example currency specifications. For example it will assume being in
  14219. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  14220. fragments that are properly closed, but during editing, we have to live
  14221. with the uncertainty caused by missing closing delimiters. This function
  14222. looks only before point, not after."
  14223. (catch 'exit
  14224. (let ((pos (point))
  14225. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  14226. (lim (progn
  14227. (re-search-backward (concat "^\\(" paragraph-start "\\)") nil
  14228. 'move)
  14229. (point)))
  14230. dd-on str (start 0) m re)
  14231. (goto-char pos)
  14232. (when dodollar
  14233. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  14234. re (nth 1 (assoc "$" org-latex-regexps)))
  14235. (while (string-match re str start)
  14236. (cond
  14237. ((= (match-end 0) (length str))
  14238. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  14239. ((= (match-end 0) (- (length str) 5))
  14240. (throw 'exit nil))
  14241. (t (setq start (match-end 0))))))
  14242. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  14243. (goto-char pos)
  14244. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  14245. (and (match-beginning 2) (throw 'exit nil))
  14246. ;; count $$
  14247. (while (re-search-backward "\\$\\$" lim t)
  14248. (setq dd-on (not dd-on)))
  14249. (goto-char pos)
  14250. (when dd-on (cons "$$" m))))))
  14251. (defun org-inside-latex-macro-p ()
  14252. "Is point inside a LaTeX macro or its arguments?"
  14253. (save-match-data
  14254. (org-in-regexp
  14255. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  14256. (defun org--make-preview-overlay (beg end image &optional imagetype)
  14257. "Build an overlay between BEG and END using IMAGE file.
  14258. Argument IMAGETYPE is the extension of the displayed image,
  14259. as a string. It defaults to \"png\"."
  14260. (let ((ov (make-overlay beg end))
  14261. (imagetype (or (intern imagetype) 'png)))
  14262. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  14263. (overlay-put ov 'evaporate t)
  14264. (overlay-put ov
  14265. 'modification-hooks
  14266. (list (lambda (o _flag _beg _end &optional _l)
  14267. (delete-overlay o))))
  14268. (overlay-put ov
  14269. 'display
  14270. (list 'image :type imagetype :file image :ascent 'center))))
  14271. (defun org-clear-latex-preview (&optional beg end)
  14272. "Remove all overlays with LaTeX fragment images in current buffer.
  14273. When optional arguments BEG and END are non-nil, remove all
  14274. overlays between them instead. Return a non-nil value when some
  14275. overlays were removed, nil otherwise."
  14276. (let ((overlays
  14277. (cl-remove-if-not
  14278. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  14279. (overlays-in (or beg (point-min)) (or end (point-max))))))
  14280. (mapc #'delete-overlay overlays)
  14281. overlays))
  14282. (defun org--latex-preview-region (beg end)
  14283. "Preview LaTeX fragments between BEG and END.
  14284. BEG and END are buffer positions."
  14285. (let ((file (buffer-file-name (buffer-base-buffer))))
  14286. (save-excursion
  14287. (org-format-latex
  14288. (concat org-preview-latex-image-directory "org-ltximg")
  14289. beg end
  14290. ;; Emacs cannot overlay images from remote hosts. Create it in
  14291. ;; `temporary-file-directory' instead.
  14292. (if (or (not file) (file-remote-p file))
  14293. temporary-file-directory
  14294. default-directory)
  14295. 'overlays nil 'forbuffer org-preview-latex-default-process))))
  14296. (defun org-latex-preview (&optional arg)
  14297. "Toggle preview of the LaTeX fragment at point.
  14298. If the cursor is on a LaTeX fragment, create the image and
  14299. overlay it over the source code, if there is none. Remove it
  14300. otherwise. If there is no fragment at point, display images for
  14301. all fragments in the current section.
  14302. With a `\\[universal-argument]' prefix argument ARG, clear images \
  14303. for all fragments
  14304. in the current section.
  14305. With a `\\[universal-argument] \\[universal-argument]' prefix \
  14306. argument ARG, display image for all
  14307. fragments in the buffer.
  14308. With a `\\[universal-argument] \\[universal-argument] \
  14309. \\[universal-argument]' prefix argument ARG, clear image for all
  14310. fragments in the buffer."
  14311. (interactive "P")
  14312. (cond
  14313. ((not (display-graphic-p)) nil)
  14314. ;; Clear whole buffer.
  14315. ((equal arg '(64))
  14316. (org-clear-latex-preview (point-min) (point-max))
  14317. (message "LaTeX previews removed from buffer"))
  14318. ;; Preview whole buffer.
  14319. ((equal arg '(16))
  14320. (message "Creating LaTeX previews in buffer...")
  14321. (org--latex-preview-region (point-min) (point-max))
  14322. (message "Creating LaTeX previews in buffer... done."))
  14323. ;; Clear current section.
  14324. ((equal arg '(4))
  14325. (org-clear-latex-preview
  14326. (if (org-before-first-heading-p) (point-min)
  14327. (save-excursion
  14328. (org-with-limited-levels (org-back-to-heading t) (point))))
  14329. (org-with-limited-levels (org-entry-end-position))))
  14330. ;; Toggle preview on LaTeX code at point.
  14331. ((let ((datum (org-element-context)))
  14332. (and (memq (org-element-type datum) '(latex-environment latex-fragment))
  14333. (let ((beg (org-element-property :begin datum))
  14334. (end (org-element-property :end datum)))
  14335. (if (org-clear-latex-preview beg end)
  14336. (message "LaTeX preview removed")
  14337. (message "Creating LaTeX preview...")
  14338. (org--latex-preview-region beg end)
  14339. (message "Creating LaTeX preview... done."))
  14340. t))))
  14341. ;; Preview current section.
  14342. (t
  14343. (let ((beg (if (org-before-first-heading-p) (point-min)
  14344. (save-excursion
  14345. (org-with-limited-levels (org-back-to-heading t) (point)))))
  14346. (end (org-with-limited-levels (org-entry-end-position))))
  14347. (message "Creating LaTeX previews in section...")
  14348. (org--latex-preview-region beg end)
  14349. (message "Creating LaTeX previews in section... done.")))))
  14350. (defun org-format-latex
  14351. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  14352. "Replace LaTeX fragments with links to an image.
  14353. The function takes care of creating the replacement image.
  14354. Only consider fragments between BEG and END when those are
  14355. provided.
  14356. When optional argument OVERLAYS is non-nil, display the image on
  14357. top of the fragment instead of replacing it.
  14358. PROCESSING-TYPE is the conversion method to use, as a symbol.
  14359. Some of the options can be changed using the variable
  14360. `org-format-latex-options', which see."
  14361. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  14362. (unless (eq processing-type 'verbatim)
  14363. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  14364. (cnt 0)
  14365. checkdir-flag)
  14366. (goto-char (or beg (point-min)))
  14367. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  14368. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  14369. (overlay-recenter (or end (point-max))))
  14370. (while (re-search-forward math-regexp end t)
  14371. (unless (and overlays
  14372. (eq (get-char-property (point) 'org-overlay-type)
  14373. 'org-latex-overlay))
  14374. (let* ((context (org-element-context))
  14375. (type (org-element-type context)))
  14376. (when (memq type '(latex-environment latex-fragment))
  14377. (let ((block-type (eq type 'latex-environment))
  14378. (value (org-element-property :value context))
  14379. (beg (org-element-property :begin context))
  14380. (end (save-excursion
  14381. (goto-char (org-element-property :end context))
  14382. (skip-chars-backward " \r\t\n")
  14383. (point))))
  14384. (cond
  14385. ((eq processing-type 'mathjax)
  14386. ;; Prepare for MathJax processing.
  14387. (if (not (string-match "\\`\\$\\$?" value))
  14388. (goto-char end)
  14389. (delete-region beg end)
  14390. (if (string= (match-string 0 value) "$$")
  14391. (insert "\\[" (substring value 2 -2) "\\]")
  14392. (insert "\\(" (substring value 1 -1) "\\)"))))
  14393. ((eq processing-type 'html)
  14394. (goto-char beg)
  14395. (delete-region beg end)
  14396. (insert (org-format-latex-as-html value)))
  14397. ((assq processing-type org-preview-latex-process-alist)
  14398. ;; Process to an image.
  14399. (cl-incf cnt)
  14400. (goto-char beg)
  14401. (let* ((processing-info
  14402. (cdr (assq processing-type org-preview-latex-process-alist)))
  14403. (face (face-at-point))
  14404. ;; Get the colors from the face at point.
  14405. (fg
  14406. (let ((color (plist-get org-format-latex-options
  14407. :foreground)))
  14408. (if (and forbuffer (eq color 'auto))
  14409. (face-attribute face :foreground nil 'default)
  14410. color)))
  14411. (bg
  14412. (let ((color (plist-get org-format-latex-options
  14413. :background)))
  14414. (if (and forbuffer (eq color 'auto))
  14415. (face-attribute face :background nil 'default)
  14416. color)))
  14417. (hash (sha1 (prin1-to-string
  14418. (list org-format-latex-header
  14419. org-latex-default-packages-alist
  14420. org-latex-packages-alist
  14421. org-format-latex-options
  14422. forbuffer value fg bg))))
  14423. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  14424. (absprefix (expand-file-name prefix dir))
  14425. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  14426. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  14427. (sep (and block-type "\n\n"))
  14428. (link (concat sep "[[file:" linkfile "]]" sep))
  14429. (options
  14430. (org-combine-plists
  14431. org-format-latex-options
  14432. `(:foreground ,fg :background ,bg))))
  14433. (when msg (message msg cnt))
  14434. (unless checkdir-flag ; Ensure the directory exists.
  14435. (setq checkdir-flag t)
  14436. (let ((todir (file-name-directory absprefix)))
  14437. (unless (file-directory-p todir)
  14438. (make-directory todir t))))
  14439. (unless (file-exists-p movefile)
  14440. (org-create-formula-image
  14441. value movefile options forbuffer processing-type))
  14442. (if overlays
  14443. (progn
  14444. (dolist (o (overlays-in beg end))
  14445. (when (eq (overlay-get o 'org-overlay-type)
  14446. 'org-latex-overlay)
  14447. (delete-overlay o)))
  14448. (org--make-preview-overlay beg end movefile imagetype)
  14449. (goto-char end))
  14450. (delete-region beg end)
  14451. (insert
  14452. (org-add-props link
  14453. (list 'org-latex-src
  14454. (replace-regexp-in-string "\"" "" value)
  14455. 'org-latex-src-embed-type
  14456. (if block-type 'paragraph 'character)))))))
  14457. ((eq processing-type 'mathml)
  14458. ;; Process to MathML.
  14459. (unless (org-format-latex-mathml-available-p)
  14460. (user-error "LaTeX to MathML converter not configured"))
  14461. (cl-incf cnt)
  14462. (when msg (message msg cnt))
  14463. (goto-char beg)
  14464. (delete-region beg end)
  14465. (insert (org-format-latex-as-mathml
  14466. value block-type prefix dir)))
  14467. (t
  14468. (error "Unknown conversion process %s for LaTeX fragments"
  14469. processing-type)))))))))))
  14470. (defun org-create-math-formula (latex-frag &optional mathml-file)
  14471. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  14472. Use `org-latex-to-mathml-convert-command'. If the conversion is
  14473. successful, return the portion between \"<math...> </math>\"
  14474. elements otherwise return nil. When MATHML-FILE is specified,
  14475. write the results in to that file. When invoked as an
  14476. interactive command, prompt for LATEX-FRAG, with initial value
  14477. set to the current active region and echo the results for user
  14478. inspection."
  14479. (interactive (list (let ((frag (when (org-region-active-p)
  14480. (buffer-substring-no-properties
  14481. (region-beginning) (region-end)))))
  14482. (read-string "LaTeX Fragment: " frag nil frag))))
  14483. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  14484. (let* ((tmp-in-file
  14485. (let ((file (file-relative-name
  14486. (make-temp-name (expand-file-name "ltxmathml-in")))))
  14487. (write-region latex-frag nil file)
  14488. file))
  14489. (tmp-out-file (file-relative-name
  14490. (make-temp-name (expand-file-name "ltxmathml-out"))))
  14491. (cmd (format-spec
  14492. org-latex-to-mathml-convert-command
  14493. `((?j . ,(and org-latex-to-mathml-jar-file
  14494. (shell-quote-argument
  14495. (expand-file-name
  14496. org-latex-to-mathml-jar-file))))
  14497. (?I . ,(shell-quote-argument tmp-in-file))
  14498. (?i . ,latex-frag)
  14499. (?o . ,(shell-quote-argument tmp-out-file)))))
  14500. mathml shell-command-output)
  14501. (when (called-interactively-p 'any)
  14502. (unless (org-format-latex-mathml-available-p)
  14503. (user-error "LaTeX to MathML converter not configured")))
  14504. (message "Running %s" cmd)
  14505. (setq shell-command-output (shell-command-to-string cmd))
  14506. (setq mathml
  14507. (when (file-readable-p tmp-out-file)
  14508. (with-current-buffer (find-file-noselect tmp-out-file t)
  14509. (goto-char (point-min))
  14510. (when (re-search-forward
  14511. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  14512. (regexp-quote
  14513. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  14514. nil t)
  14515. (prog1 (match-string 0) (kill-buffer))))))
  14516. (cond
  14517. (mathml
  14518. (setq mathml
  14519. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  14520. (when mathml-file
  14521. (write-region mathml nil mathml-file))
  14522. (when (called-interactively-p 'any)
  14523. (message mathml)))
  14524. ((warn "LaTeX to MathML conversion failed")
  14525. (message shell-command-output)))
  14526. (delete-file tmp-in-file)
  14527. (when (file-exists-p tmp-out-file)
  14528. (delete-file tmp-out-file))
  14529. mathml))
  14530. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  14531. prefix &optional dir)
  14532. "Use `org-create-math-formula' but check local cache first."
  14533. (let* ((absprefix (expand-file-name prefix dir))
  14534. (print-length nil) (print-level nil)
  14535. (formula-id (concat
  14536. "formula-"
  14537. (sha1
  14538. (prin1-to-string
  14539. (list latex-frag
  14540. org-latex-to-mathml-convert-command)))))
  14541. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  14542. (formula-cache-dir (file-name-directory formula-cache)))
  14543. (unless (file-directory-p formula-cache-dir)
  14544. (make-directory formula-cache-dir t))
  14545. (unless (file-exists-p formula-cache)
  14546. (org-create-math-formula latex-frag formula-cache))
  14547. (if (file-exists-p formula-cache)
  14548. ;; Successful conversion. Return the link to MathML file.
  14549. (org-add-props
  14550. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  14551. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  14552. 'org-latex-src-embed-type (if latex-frag-type
  14553. 'paragraph 'character)))
  14554. ;; Failed conversion. Return the LaTeX fragment verbatim
  14555. latex-frag)))
  14556. (defun org-format-latex-as-html (latex-fragment)
  14557. "Convert LATEX-FRAGMENT to HTML.
  14558. This uses `org-latex-to-html-convert-command', which see."
  14559. (let ((cmd (format-spec org-latex-to-html-convert-command
  14560. `((?i . ,latex-fragment)))))
  14561. (message "Running %s" cmd)
  14562. (shell-command-to-string cmd)))
  14563. (defun org--get-display-dpi ()
  14564. "Get the DPI of the display.
  14565. The function assumes that the display has the same pixel width in
  14566. the horizontal and vertical directions."
  14567. (if (display-graphic-p)
  14568. (round (/ (display-pixel-height)
  14569. (/ (display-mm-height) 25.4)))
  14570. (error "Attempt to calculate the dpi of a non-graphic display")))
  14571. (defun org-create-formula-image
  14572. (string tofile options buffer &optional processing-type)
  14573. "Create an image from LaTeX source using external processes.
  14574. The LaTeX STRING is saved to a temporary LaTeX file, then
  14575. converted to an image file by process PROCESSING-TYPE defined in
  14576. `org-preview-latex-process-alist'. A nil value defaults to
  14577. `org-preview-latex-default-process'.
  14578. The generated image file is eventually moved to TOFILE.
  14579. The OPTIONS argument controls the size, foreground color and
  14580. background color of the generated image.
  14581. When BUFFER non-nil, this function is used for LaTeX previewing.
  14582. Otherwise, it is used to deal with LaTeX snippets showed in
  14583. a HTML file."
  14584. (let* ((processing-type (or processing-type
  14585. org-preview-latex-default-process))
  14586. (processing-info
  14587. (cdr (assq processing-type org-preview-latex-process-alist)))
  14588. (programs (plist-get processing-info :programs))
  14589. (error-message (or (plist-get processing-info :message) ""))
  14590. (image-input-type (plist-get processing-info :image-input-type))
  14591. (image-output-type (plist-get processing-info :image-output-type))
  14592. (post-clean (or (plist-get processing-info :post-clean)
  14593. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  14594. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  14595. (latex-header
  14596. (or (plist-get processing-info :latex-header)
  14597. (org-latex-make-preamble
  14598. (org-export-get-environment (org-export-get-backend 'latex))
  14599. org-format-latex-header
  14600. 'snippet)))
  14601. (latex-compiler (plist-get processing-info :latex-compiler))
  14602. (image-converter (plist-get processing-info :image-converter))
  14603. (tmpdir temporary-file-directory)
  14604. (texfilebase (make-temp-name
  14605. (expand-file-name "orgtex" tmpdir)))
  14606. (texfile (concat texfilebase ".tex"))
  14607. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  14608. '(1.0 . 1.0)))
  14609. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  14610. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  14611. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  14612. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  14613. "Black"))
  14614. (bg (or (plist-get options (if buffer :background :html-background))
  14615. "Transparent"))
  14616. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  14617. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  14618. (dolist (program programs)
  14619. (org-check-external-command program error-message))
  14620. (if (eq fg 'default)
  14621. (setq fg (org-latex-color :foreground))
  14622. (setq fg (org-latex-color-format fg)))
  14623. (if (eq bg 'default)
  14624. (setq bg (org-latex-color :background))
  14625. (setq bg (org-latex-color-format
  14626. (if (string= bg "Transparent") "white" bg))))
  14627. ;; Remove TeX \par at end of snippet to avoid trailing space.
  14628. (if (string-suffix-p string "\n")
  14629. (aset string (1- (length string)) ?%)
  14630. (setq string (concat string "%")))
  14631. (with-temp-file texfile
  14632. (insert latex-header)
  14633. (insert "\n\\begin{document}\n"
  14634. "\\definecolor{fg}{rgb}{" fg "}%\n"
  14635. "\\definecolor{bg}{rgb}{" bg "}%\n"
  14636. "\n\\pagecolor{bg}%\n"
  14637. "\n{\\color{fg}\n"
  14638. string
  14639. "\n}\n"
  14640. "\n\\end{document}\n"))
  14641. (let* ((err-msg (format "Please adjust `%s' part of \
  14642. `org-preview-latex-process-alist'."
  14643. processing-type))
  14644. (image-input-file
  14645. (org-compile-file
  14646. texfile latex-compiler image-input-type err-msg log-buf))
  14647. (image-output-file
  14648. (org-compile-file
  14649. image-input-file image-converter image-output-type err-msg log-buf
  14650. `((?D . ,(shell-quote-argument (format "%s" dpi)))
  14651. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  14652. (copy-file image-output-file tofile 'replace)
  14653. (dolist (e post-clean)
  14654. (when (file-exists-p (concat texfilebase e))
  14655. (delete-file (concat texfilebase e))))
  14656. image-output-file)))
  14657. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  14658. "Fill a LaTeX header template TPL.
  14659. In the template, the following place holders will be recognized:
  14660. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  14661. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  14662. [PACKAGES] \\usepackage statements for PKG
  14663. [NO-PACKAGES] do not include PKG
  14664. [EXTRA] the string EXTRA
  14665. [NO-EXTRA] do not include EXTRA
  14666. For backward compatibility, if both the positive and the negative place
  14667. holder is missing, the positive one (without the \"NO-\") will be
  14668. assumed to be present at the end of the template.
  14669. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  14670. EXTRA is a string.
  14671. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  14672. (let (rpl (end ""))
  14673. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  14674. (setq rpl (if (or (match-end 1) (not def-pkg))
  14675. "" (org-latex-packages-to-string def-pkg snippets-p t))
  14676. tpl (replace-match rpl t t tpl))
  14677. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  14678. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  14679. (setq rpl (if (or (match-end 1) (not pkg))
  14680. "" (org-latex-packages-to-string pkg snippets-p t))
  14681. tpl (replace-match rpl t t tpl))
  14682. (when pkg (setq end
  14683. (concat end "\n"
  14684. (org-latex-packages-to-string pkg snippets-p)))))
  14685. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  14686. (setq rpl (if (or (match-end 1) (not extra))
  14687. "" (concat extra "\n"))
  14688. tpl (replace-match rpl t t tpl))
  14689. (when (and extra (string-match "\\S-" extra))
  14690. (setq end (concat end "\n" extra))))
  14691. (if (string-match "\\S-" end)
  14692. (concat tpl "\n" end)
  14693. tpl)))
  14694. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  14695. "Turn an alist of packages into a string with the \\usepackage macros."
  14696. (setq pkg (mapconcat (lambda(p)
  14697. (cond
  14698. ((stringp p) p)
  14699. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  14700. (format "%% Package %s omitted" (cadr p)))
  14701. ((equal "" (car p))
  14702. (format "\\usepackage{%s}" (cadr p)))
  14703. (t
  14704. (format "\\usepackage[%s]{%s}"
  14705. (car p) (cadr p)))))
  14706. pkg
  14707. "\n"))
  14708. (if newline (concat pkg "\n") pkg))
  14709. (defun org-dvipng-color (attr)
  14710. "Return a RGB color specification for dvipng."
  14711. (org-dvipng-color-format (face-attribute 'default attr nil)))
  14712. (defun org-dvipng-color-format (color-name)
  14713. "Convert COLOR-NAME to a RGB color value for dvipng."
  14714. (apply #'format "rgb %s %s %s"
  14715. (mapcar 'org-normalize-color
  14716. (color-values color-name))))
  14717. (defun org-latex-color (attr)
  14718. "Return a RGB color for the LaTeX color package."
  14719. (org-latex-color-format (face-attribute 'default attr nil)))
  14720. (defun org-latex-color-format (color-name)
  14721. "Convert COLOR-NAME to a RGB color value."
  14722. (apply #'format "%s,%s,%s"
  14723. (mapcar 'org-normalize-color
  14724. (color-values color-name))))
  14725. (defun org-normalize-color (value)
  14726. "Return string to be used as color value for an RGB component."
  14727. (format "%g" (/ value 65535.0)))
  14728. ;; Image display
  14729. (defvar-local org-inline-image-overlays nil)
  14730. (defun org-toggle-inline-images (&optional include-linked)
  14731. "Toggle the display of inline images.
  14732. INCLUDE-LINKED is passed to `org-display-inline-images'."
  14733. (interactive "P")
  14734. (if org-inline-image-overlays
  14735. (progn
  14736. (org-remove-inline-images)
  14737. (when (called-interactively-p 'interactive)
  14738. (message "Inline image display turned off")))
  14739. (org-display-inline-images include-linked)
  14740. (when (called-interactively-p 'interactive)
  14741. (message (if org-inline-image-overlays
  14742. (format "%d images displayed inline"
  14743. (length org-inline-image-overlays))
  14744. "No images to display inline")))))
  14745. (defun org-redisplay-inline-images ()
  14746. "Assure display of inline images and refresh them."
  14747. (interactive)
  14748. (org-toggle-inline-images)
  14749. (unless org-inline-image-overlays
  14750. (org-toggle-inline-images)))
  14751. ;; For without-x builds.
  14752. (declare-function image-refresh "image" (spec &optional frame))
  14753. (defcustom org-display-remote-inline-images 'skip
  14754. "How to display remote inline images.
  14755. Possible values of this option are:
  14756. skip Don't display remote images.
  14757. download Always download and display remote images.
  14758. cache Display remote images, and open them in separate buffers
  14759. for cacheing. Silently update the image buffer when a file
  14760. change is detected."
  14761. :group 'org-appearance
  14762. :package-version '(Org . "9.4")
  14763. :type '(choice
  14764. (const :tag "Ignore remote images" skip)
  14765. (const :tag "Always display remote images" download)
  14766. (const :tag "Display and silently update remote images" cache))
  14767. :safe #'symbolp)
  14768. (defun org--create-inline-image (file width)
  14769. "Create image located at FILE, or return nil.
  14770. WIDTH is the width of the image. The image may not be created
  14771. according to the value of `org-display-remote-inline-images'."
  14772. (let* ((remote? (file-remote-p file))
  14773. (file-or-data
  14774. (pcase org-display-remote-inline-images
  14775. ((guard (not remote?)) file)
  14776. (`download (with-temp-buffer
  14777. (set-buffer-multibyte nil)
  14778. (insert-file-contents-literally file)
  14779. (buffer-string)))
  14780. (`cache (let ((revert-without-query '(".")))
  14781. (with-current-buffer (find-file-noselect file)
  14782. (buffer-string))))
  14783. (`skip nil)
  14784. (other
  14785. (message "Invalid value of `org-display-remote-inline-images': %S"
  14786. other)
  14787. nil))))
  14788. (when file-or-data
  14789. (create-image file-or-data
  14790. (and (image-type-available-p 'imagemagick)
  14791. width
  14792. 'imagemagick)
  14793. remote?
  14794. :width width))))
  14795. (defun org-display-inline-images (&optional include-linked refresh beg end)
  14796. "Display inline images.
  14797. An inline image is a link which follows either of these
  14798. conventions:
  14799. 1. Its path is a file with an extension matching return value
  14800. from `image-file-name-regexp' and it has no contents.
  14801. 2. Its description consists in a single link of the previous
  14802. type. In this case, that link must be a well-formed plain
  14803. or angle link, i.e., it must have an explicit \"file\" type.
  14804. Equip each image with the key-map `image-map'.
  14805. When optional argument INCLUDE-LINKED is non-nil, also links with
  14806. a text description part will be inlined. This can be nice for
  14807. a quick look at those images, but it does not reflect what
  14808. exported files will look like.
  14809. When optional argument REFRESH is non-nil, refresh existing
  14810. images between BEG and END. This will create new image displays
  14811. only if necessary.
  14812. BEG and END define the considered part. They default to the
  14813. buffer boundaries with possible narrowing."
  14814. (interactive "P")
  14815. (when (display-graphic-p)
  14816. (unless refresh
  14817. (org-remove-inline-images)
  14818. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  14819. (let ((end (or end (point-max))))
  14820. (org-with-point-at (or beg (point-min))
  14821. (let* ((case-fold-search t)
  14822. (file-extension-re (image-file-name-regexp))
  14823. (link-abbrevs (mapcar #'car
  14824. (append org-link-abbrev-alist-local
  14825. org-link-abbrev-alist)))
  14826. ;; Check absolute, relative file names and explicit
  14827. ;; "file:" links. Also check link abbreviations since
  14828. ;; some might expand to "file" links.
  14829. (file-types-re
  14830. (format "\\[\\[\\(?:file%s:\\|attachment:\\|[./~]\\)\\|\\]\\[\\(<?file:\\)"
  14831. (if (not link-abbrevs) ""
  14832. (concat "\\|" (regexp-opt link-abbrevs))))))
  14833. (while (re-search-forward file-types-re end t)
  14834. (let* ((link (org-element-lineage
  14835. (save-match-data (org-element-context))
  14836. '(link) t))
  14837. (linktype (org-element-property :type link))
  14838. (inner-start (match-beginning 1))
  14839. (path
  14840. (cond
  14841. ;; No link at point; no inline image.
  14842. ((not link) nil)
  14843. ;; File link without a description. Also handle
  14844. ;; INCLUDE-LINKED here since it should have
  14845. ;; precedence over the next case. I.e., if link
  14846. ;; contains filenames in both the path and the
  14847. ;; description, prioritize the path only when
  14848. ;; INCLUDE-LINKED is non-nil.
  14849. ((or (not (org-element-property :contents-begin link))
  14850. include-linked)
  14851. (and (or (equal "file" linktype)
  14852. (equal "attachment" linktype))
  14853. (org-element-property :path link)))
  14854. ;; Link with a description. Check if description
  14855. ;; is a filename. Even if Org doesn't have syntax
  14856. ;; for those -- clickable image -- constructs, fake
  14857. ;; them, as in `org-export-insert-image-links'.
  14858. ((not inner-start) nil)
  14859. (t
  14860. (org-with-point-at inner-start
  14861. (and (looking-at
  14862. (if (char-equal ?< (char-after inner-start))
  14863. org-link-angle-re
  14864. org-link-plain-re))
  14865. ;; File name must fill the whole
  14866. ;; description.
  14867. (= (org-element-property :contents-end link)
  14868. (match-end 0))
  14869. (match-string 2)))))))
  14870. (when (and path (string-match-p file-extension-re path))
  14871. (let ((file (if (equal "attachment" linktype)
  14872. (progn
  14873. (require 'org-attach)
  14874. (ignore-errors (org-attach-expand path)))
  14875. (expand-file-name path))))
  14876. (when (and file (file-exists-p file))
  14877. (let ((width
  14878. ;; Apply `org-image-actual-width' specifications.
  14879. (cond
  14880. ((eq org-image-actual-width t) nil)
  14881. ((listp org-image-actual-width)
  14882. (or
  14883. ;; First try to find a width among
  14884. ;; attributes associated to the paragraph
  14885. ;; containing link.
  14886. (pcase (org-element-lineage link '(paragraph))
  14887. (`nil nil)
  14888. (p
  14889. (let* ((case-fold-search t)
  14890. (end (org-element-property :post-affiliated p))
  14891. (re "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"))
  14892. (when (org-with-point-at
  14893. (org-element-property :begin p)
  14894. (re-search-forward re end t))
  14895. (string-to-number (match-string 1))))))
  14896. ;; Otherwise, fall-back to provided number.
  14897. (car org-image-actual-width)))
  14898. ((numberp org-image-actual-width)
  14899. org-image-actual-width)
  14900. (t nil)))
  14901. (old (get-char-property-and-overlay
  14902. (org-element-property :begin link)
  14903. 'org-image-overlay)))
  14904. (if (and (car-safe old) refresh)
  14905. (image-refresh (overlay-get (cdr old) 'display))
  14906. (let ((image (org--create-inline-image file width)))
  14907. (when image
  14908. (let ((ov (make-overlay
  14909. (org-element-property :begin link)
  14910. (progn
  14911. (goto-char
  14912. (org-element-property :end link))
  14913. (skip-chars-backward " \t")
  14914. (point)))))
  14915. (overlay-put ov 'display image)
  14916. (overlay-put ov 'face 'default)
  14917. (overlay-put ov 'org-image-overlay t)
  14918. (overlay-put
  14919. ov 'modification-hooks
  14920. (list 'org-display-inline-remove-overlay))
  14921. (when (<= 26 emacs-major-version)
  14922. (cl-assert (boundp 'image-map))
  14923. (overlay-put ov 'keymap image-map))
  14924. (push ov org-inline-image-overlays))))))))))))))))
  14925. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  14926. "Remove inline-display overlay if a corresponding region is modified."
  14927. (let ((inhibit-modification-hooks t))
  14928. (when (and ov after)
  14929. (delete ov org-inline-image-overlays)
  14930. (delete-overlay ov))))
  14931. (defun org-remove-inline-images ()
  14932. "Remove inline display of images."
  14933. (interactive)
  14934. (mapc #'delete-overlay org-inline-image-overlays)
  14935. (setq org-inline-image-overlays nil))
  14936. (defvar org-self-insert-command-undo-counter 0)
  14937. (defvar org-speed-command nil)
  14938. (defun org-self-insert-command (N)
  14939. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  14940. If the cursor is in a table looking at whitespace, the whitespace is
  14941. overwritten, and the table is not marked as requiring realignment."
  14942. (interactive "p")
  14943. (org-check-before-invisible-edit 'insert)
  14944. (cond
  14945. ((and org-use-speed-commands
  14946. (let ((kv (this-command-keys-vector)))
  14947. (setq org-speed-command
  14948. (run-hook-with-args-until-success
  14949. 'org-speed-command-hook
  14950. (make-string 1 (aref kv (1- (length kv))))))))
  14951. (cond
  14952. ((commandp org-speed-command)
  14953. (setq this-command org-speed-command)
  14954. (call-interactively org-speed-command))
  14955. ((functionp org-speed-command)
  14956. (funcall org-speed-command))
  14957. ((and org-speed-command (listp org-speed-command))
  14958. (eval org-speed-command))
  14959. (t (let (org-use-speed-commands)
  14960. (call-interactively 'org-self-insert-command)))))
  14961. ((and
  14962. (= N 1)
  14963. (not (org-region-active-p))
  14964. (org-at-table-p)
  14965. (progn
  14966. ;; Check if we blank the field, and if that triggers align.
  14967. (and (featurep 'org-table)
  14968. org-table-auto-blank-field
  14969. (memq last-command
  14970. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  14971. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  14972. ;; Got extra space, this field does not determine
  14973. ;; column width.
  14974. (let (org-table-may-need-update) (org-table-blank-field))
  14975. ;; No extra space, this field may determine column
  14976. ;; width.
  14977. (org-table-blank-field)))
  14978. t)
  14979. (looking-at "[^|\n]* |"))
  14980. ;; There is room for insertion without re-aligning the table.
  14981. (self-insert-command N)
  14982. (org-table-with-shrunk-field
  14983. (save-excursion
  14984. (skip-chars-forward "^|")
  14985. ;; Do not delete last space, which is
  14986. ;; `org-table-separator-space', but the regular space before
  14987. ;; it.
  14988. (delete-region (- (point) 2) (1- (point))))))
  14989. (t
  14990. (setq org-table-may-need-update t)
  14991. (self-insert-command N)
  14992. (org-fix-tags-on-the-fly)
  14993. (when org-self-insert-cluster-for-undo
  14994. (if (not (eq last-command 'org-self-insert-command))
  14995. (setq org-self-insert-command-undo-counter 1)
  14996. (if (>= org-self-insert-command-undo-counter 20)
  14997. (setq org-self-insert-command-undo-counter 1)
  14998. (and (> org-self-insert-command-undo-counter 0)
  14999. buffer-undo-list (listp buffer-undo-list)
  15000. (not (cadr buffer-undo-list)) ; remove nil entry
  15001. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  15002. (setq org-self-insert-command-undo-counter
  15003. (1+ org-self-insert-command-undo-counter))))))))
  15004. (defun org-check-before-invisible-edit (kind)
  15005. "Check is editing if kind KIND would be dangerous with invisible text around.
  15006. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  15007. ;; First, try to get out of here as quickly as possible, to reduce overhead
  15008. (when (and org-catch-invisible-edits
  15009. (or (not (boundp 'visible-mode)) (not visible-mode))
  15010. (or (get-char-property (point) 'invisible)
  15011. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  15012. ;; OK, we need to take a closer look. Do not consider
  15013. ;; invisibility obtained through text properties (e.g., link
  15014. ;; fontification), as it cannot be toggled.
  15015. (let* ((invisible-at-point
  15016. (pcase (get-char-property-and-overlay (point) 'invisible)
  15017. (`(,_ . ,(and (pred overlayp) o)) o)))
  15018. ;; Assume that point cannot land in the middle of an
  15019. ;; overlay, or between two overlays.
  15020. (invisible-before-point
  15021. (and (not invisible-at-point)
  15022. (not (bobp))
  15023. (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  15024. (`(,_ . ,(and (pred overlayp) o)) o))))
  15025. (border-and-ok-direction
  15026. (or
  15027. ;; Check if we are acting predictably before invisible
  15028. ;; text.
  15029. (and invisible-at-point
  15030. (memq kind '(insert delete-backward)))
  15031. ;; Check if we are acting predictably after invisible text
  15032. ;; This works not well, and I have turned it off. It seems
  15033. ;; better to always show and stop after invisible text.
  15034. ;; (and (not invisible-at-point) invisible-before-point
  15035. ;; (memq kind '(insert delete)))
  15036. )))
  15037. (when (or invisible-at-point invisible-before-point)
  15038. (when (eq org-catch-invisible-edits 'error)
  15039. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  15040. (if (and org-custom-properties-overlays
  15041. (y-or-n-p "Display invisible properties in this buffer? "))
  15042. (org-toggle-custom-properties-visibility)
  15043. ;; Make the area visible
  15044. (save-excursion
  15045. (when invisible-before-point
  15046. (goto-char
  15047. (previous-single-char-property-change (point) 'invisible)))
  15048. ;; Remove whatever overlay is currently making yet-to-be
  15049. ;; edited text invisible. Also remove nested invisibility
  15050. ;; related overlays.
  15051. (delete-overlay (or invisible-at-point invisible-before-point))
  15052. (let ((origin (if invisible-at-point (point) (1- (point)))))
  15053. (while (pcase (get-char-property-and-overlay origin 'invisible)
  15054. (`(,_ . ,(and (pred overlayp) o))
  15055. (delete-overlay o)
  15056. t)))))
  15057. (cond
  15058. ((eq org-catch-invisible-edits 'show)
  15059. ;; That's it, we do the edit after showing
  15060. (message
  15061. "Unfolding invisible region around point before editing")
  15062. (sit-for 1))
  15063. ((and (eq org-catch-invisible-edits 'smart)
  15064. border-and-ok-direction)
  15065. (message "Unfolding invisible region around point before editing"))
  15066. (t
  15067. ;; Don't do the edit, make the user repeat it in full visibility
  15068. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  15069. (defun org-fix-tags-on-the-fly ()
  15070. "Align tags in headline at point.
  15071. Unlike `org-align-tags', this function does nothing if point is
  15072. either not currently on a tagged headline or on a tag."
  15073. (when (and (org-match-line org-tag-line-re)
  15074. (< (point) (match-beginning 1)))
  15075. (org-align-tags)))
  15076. (defun org-delete-backward-char (N)
  15077. "Like `delete-backward-char', insert whitespace at field end in tables.
  15078. When deleting backwards, in tables this function will insert whitespace in
  15079. front of the next \"|\" separator, to keep the table aligned. The table will
  15080. still be marked for re-alignment if the field did fill the entire column,
  15081. because, in this case the deletion might narrow the column."
  15082. (interactive "p")
  15083. (save-match-data
  15084. (org-check-before-invisible-edit 'delete-backward)
  15085. (if (and (= N 1)
  15086. (not overwrite-mode)
  15087. (not (org-region-active-p))
  15088. (not (eq (char-before) ?|))
  15089. (save-excursion (skip-chars-backward " \t") (not (bolp)))
  15090. (looking-at-p ".*?|")
  15091. (org-at-table-p))
  15092. (progn (forward-char -1) (org-delete-char 1))
  15093. (backward-delete-char N)
  15094. (org-fix-tags-on-the-fly))))
  15095. (defun org-delete-char (N)
  15096. "Like `delete-char', but insert whitespace at field end in tables.
  15097. When deleting characters, in tables this function will insert whitespace in
  15098. front of the next \"|\" separator, to keep the table aligned. The table will
  15099. still be marked for re-alignment if the field did fill the entire column,
  15100. because, in this case the deletion might narrow the column."
  15101. (interactive "p")
  15102. (save-match-data
  15103. (org-check-before-invisible-edit 'delete)
  15104. (cond
  15105. ((or (/= N 1)
  15106. (eq (char-after) ?|)
  15107. (save-excursion (skip-chars-backward " \t") (bolp))
  15108. (not (org-at-table-p)))
  15109. (delete-char N)
  15110. (org-fix-tags-on-the-fly))
  15111. ((looking-at ".\\(.*?\\)|")
  15112. (let* ((update? org-table-may-need-update)
  15113. (noalign (looking-at-p ".*? |")))
  15114. (delete-char 1)
  15115. (org-table-with-shrunk-field
  15116. (save-excursion
  15117. ;; Last space is `org-table-separator-space', so insert
  15118. ;; a regular one before it instead.
  15119. (goto-char (- (match-end 0) 2))
  15120. (insert " ")))
  15121. ;; If there were two spaces at the end, this field does not
  15122. ;; determine the width of the column.
  15123. (when noalign (setq org-table-may-need-update update?))))
  15124. (t
  15125. (delete-char N)))))
  15126. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  15127. (put 'org-self-insert-command 'delete-selection
  15128. (lambda ()
  15129. (not (run-hook-with-args-until-success
  15130. 'self-insert-uses-region-functions))))
  15131. (put 'orgtbl-self-insert-command 'delete-selection
  15132. (lambda ()
  15133. (not (run-hook-with-args-until-success
  15134. 'self-insert-uses-region-functions))))
  15135. (put 'org-delete-char 'delete-selection 'supersede)
  15136. (put 'org-delete-backward-char 'delete-selection 'supersede)
  15137. (put 'org-yank 'delete-selection 'yank)
  15138. ;; Make `flyspell-mode' delay after some commands
  15139. (put 'org-self-insert-command 'flyspell-delayed t)
  15140. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  15141. (put 'org-delete-char 'flyspell-delayed t)
  15142. (put 'org-delete-backward-char 'flyspell-delayed t)
  15143. ;; Make pabbrev-mode expand after Org mode commands
  15144. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  15145. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  15146. (defun org-transpose-words ()
  15147. "Transpose words for Org.
  15148. This uses the `org-mode-transpose-word-syntax-table' syntax
  15149. table, which interprets characters in `org-emphasis-alist' as
  15150. word constituents."
  15151. (interactive)
  15152. (with-syntax-table org-mode-transpose-word-syntax-table
  15153. (call-interactively 'transpose-words)))
  15154. (defvar org-ctrl-c-ctrl-c-hook nil
  15155. "Hook for functions attaching themselves to `C-c C-c'.
  15156. This can be used to add additional functionality to the C-c C-c
  15157. key which executes context-dependent commands. This hook is run
  15158. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  15159. run after the last test.
  15160. Each function will be called with no arguments. The function
  15161. must check if the context is appropriate for it to act. If yes,
  15162. it should do its thing and then return a non-nil value. If the
  15163. context is wrong, just do nothing and return nil.")
  15164. (defvar org-ctrl-c-ctrl-c-final-hook nil
  15165. "Hook for functions attaching themselves to `C-c C-c'.
  15166. This can be used to add additional functionality to the C-c C-c
  15167. key which executes context-dependent commands. This hook is run
  15168. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  15169. before the first test.
  15170. Each function will be called with no arguments. The function
  15171. must check if the context is appropriate for it to act. If yes,
  15172. it should do its thing and then return a non-nil value. If the
  15173. context is wrong, just do nothing and return nil.")
  15174. (defvar org-tab-first-hook nil
  15175. "Hook for functions to attach themselves to TAB.
  15176. See `org-ctrl-c-ctrl-c-hook' for more information.
  15177. This hook runs as the first action when TAB is pressed, even before
  15178. `org-cycle' messes around with the `outline-regexp' to cater for
  15179. inline tasks and plain list item folding.
  15180. If any function in this hook returns t, any other actions that
  15181. would have been caused by TAB (such as table field motion or visibility
  15182. cycling) will not occur.")
  15183. (defvar org-tab-after-check-for-table-hook nil
  15184. "Hook for functions to attach themselves to TAB.
  15185. See `org-ctrl-c-ctrl-c-hook' for more information.
  15186. This hook runs after it has been established that the cursor is not in a
  15187. table, but before checking if the cursor is in a headline or if global cycling
  15188. should be done.
  15189. If any function in this hook returns t, not other actions like visibility
  15190. cycling will be done.")
  15191. (defvar org-tab-after-check-for-cycling-hook nil
  15192. "Hook for functions to attach themselves to TAB.
  15193. See `org-ctrl-c-ctrl-c-hook' for more information.
  15194. This hook runs after it has been established that not table field motion and
  15195. not visibility should be done because of current context. This is probably
  15196. the place where a package like yasnippets can hook in.")
  15197. (defvar org-tab-before-tab-emulation-hook nil
  15198. "Hook for functions to attach themselves to TAB.
  15199. See `org-ctrl-c-ctrl-c-hook' for more information.
  15200. This hook runs after every other options for TAB have been exhausted, but
  15201. before indentation and \t insertion takes place.")
  15202. (defvar org-metaleft-hook nil
  15203. "Hook for functions attaching themselves to `M-left'.
  15204. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15205. (defvar org-metaright-hook nil
  15206. "Hook for functions attaching themselves to `M-right'.
  15207. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15208. (defvar org-metaup-hook nil
  15209. "Hook for functions attaching themselves to `M-up'.
  15210. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15211. (defvar org-metadown-hook nil
  15212. "Hook for functions attaching themselves to `M-down'.
  15213. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15214. (defvar org-shiftmetaleft-hook nil
  15215. "Hook for functions attaching themselves to `M-S-left'.
  15216. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15217. (defvar org-shiftmetaright-hook nil
  15218. "Hook for functions attaching themselves to `M-S-right'.
  15219. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15220. (defvar org-shiftmetaup-hook nil
  15221. "Hook for functions attaching themselves to `M-S-up'.
  15222. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15223. (defvar org-shiftmetadown-hook nil
  15224. "Hook for functions attaching themselves to `M-S-down'.
  15225. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15226. (defvar org-metareturn-hook nil
  15227. "Hook for functions attaching themselves to `M-RET'.
  15228. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15229. (defvar org-shiftup-hook nil
  15230. "Hook for functions attaching themselves to `S-up'.
  15231. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15232. (defvar org-shiftup-final-hook nil
  15233. "Hook for functions attaching themselves to `S-up'.
  15234. This one runs after all other options except shift-select have been excluded.
  15235. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15236. (defvar org-shiftdown-hook nil
  15237. "Hook for functions attaching themselves to `S-down'.
  15238. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15239. (defvar org-shiftdown-final-hook nil
  15240. "Hook for functions attaching themselves to `S-down'.
  15241. This one runs after all other options except shift-select have been excluded.
  15242. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15243. (defvar org-shiftleft-hook nil
  15244. "Hook for functions attaching themselves to `S-left'.
  15245. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15246. (defvar org-shiftleft-final-hook nil
  15247. "Hook for functions attaching themselves to `S-left'.
  15248. This one runs after all other options except shift-select have been excluded.
  15249. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15250. (defvar org-shiftright-hook nil
  15251. "Hook for functions attaching themselves to `S-right'.
  15252. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15253. (defvar org-shiftright-final-hook nil
  15254. "Hook for functions attaching themselves to `S-right'.
  15255. This one runs after all other options except shift-select have been excluded.
  15256. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15257. (defun org-modifier-cursor-error ()
  15258. "Throw an error, a modified cursor command was applied in wrong context."
  15259. (user-error "This command is active in special context like tables, headlines or items"))
  15260. (defun org-shiftselect-error ()
  15261. "Throw an error because Shift-Cursor command was applied in wrong context."
  15262. (if (and (boundp 'shift-select-mode) shift-select-mode)
  15263. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  15264. (user-error "This command works only in special context like headlines or timestamps")))
  15265. (defun org-call-for-shift-select (cmd)
  15266. (let ((this-command-keys-shift-translated t))
  15267. (call-interactively cmd)))
  15268. (defun org-shifttab (&optional arg)
  15269. "Global visibility cycling or move to previous table field.
  15270. Call `org-table-previous-field' within a table.
  15271. When ARG is nil, cycle globally through visibility states.
  15272. When ARG is a numeric prefix, show contents of this level."
  15273. (interactive "P")
  15274. (cond
  15275. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  15276. ((integerp arg)
  15277. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  15278. (message "Content view to level: %d" arg)
  15279. (org-content (prefix-numeric-value arg2))
  15280. (org-cycle-show-empty-lines t)
  15281. (setq org-cycle-global-status 'overview)))
  15282. (t (call-interactively 'org-global-cycle))))
  15283. (defun org-shiftmetaleft ()
  15284. "Promote subtree or delete table column.
  15285. Calls `org-promote-subtree', `org-outdent-item-tree', or
  15286. `org-table-delete-column', depending on context. See the
  15287. individual commands for more information."
  15288. (interactive)
  15289. (cond
  15290. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  15291. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  15292. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  15293. ((if (not (org-region-active-p)) (org-at-item-p)
  15294. (save-excursion (goto-char (region-beginning))
  15295. (org-at-item-p)))
  15296. (call-interactively 'org-outdent-item-tree))
  15297. (t (org-modifier-cursor-error))))
  15298. (defun org-shiftmetaright ()
  15299. "Demote subtree or insert table column.
  15300. Calls `org-demote-subtree', `org-indent-item-tree', or
  15301. `org-table-insert-column', depending on context. See the
  15302. individual commands for more information."
  15303. (interactive)
  15304. (cond
  15305. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  15306. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  15307. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  15308. ((if (not (org-region-active-p)) (org-at-item-p)
  15309. (save-excursion (goto-char (region-beginning))
  15310. (org-at-item-p)))
  15311. (call-interactively 'org-indent-item-tree))
  15312. (t (org-modifier-cursor-error))))
  15313. (defun org-shiftmetaup (&optional _arg)
  15314. "Drag the line at point up.
  15315. In a table, kill the current row.
  15316. On a clock timestamp, update the value of the timestamp like `S-<up>'
  15317. but also adjust the previous clocked item in the clock history.
  15318. Everywhere else, drag the line at point up."
  15319. (interactive "P")
  15320. (cond
  15321. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  15322. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  15323. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15324. (call-interactively 'org-timestamp-up)))
  15325. (t (call-interactively 'org-drag-line-backward))))
  15326. (defun org-shiftmetadown (&optional _arg)
  15327. "Drag the line at point down.
  15328. In a table, insert an empty row at the current line.
  15329. On a clock timestamp, update the value of the timestamp like `S-<down>'
  15330. but also adjust the previous clocked item in the clock history.
  15331. Everywhere else, drag the line at point down."
  15332. (interactive "P")
  15333. (cond
  15334. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  15335. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  15336. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15337. (call-interactively 'org-timestamp-down)))
  15338. (t (call-interactively 'org-drag-line-forward))))
  15339. (defsubst org-hidden-tree-error ()
  15340. (user-error
  15341. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  15342. (defun org-metaleft (&optional _arg)
  15343. "Promote heading, list item at point or move table column left.
  15344. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  15345. depending on context. With no specific context, calls the Emacs
  15346. default `backward-word'. See the individual commands for more
  15347. information.
  15348. This function runs the hook `org-metaleft-hook' as a first step,
  15349. and returns at first non-nil value."
  15350. (interactive "P")
  15351. (cond
  15352. ((run-hook-with-args-until-success 'org-metaleft-hook))
  15353. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  15354. ((org-with-limited-levels
  15355. (or (org-at-heading-p)
  15356. (and (org-region-active-p)
  15357. (save-excursion
  15358. (goto-char (region-beginning))
  15359. (org-at-heading-p)))))
  15360. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15361. (call-interactively 'org-do-promote))
  15362. ;; At an inline task.
  15363. ((org-at-heading-p)
  15364. (call-interactively 'org-inlinetask-promote))
  15365. ((or (org-at-item-p)
  15366. (and (org-region-active-p)
  15367. (save-excursion
  15368. (goto-char (region-beginning))
  15369. (org-at-item-p))))
  15370. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15371. (call-interactively 'org-outdent-item))
  15372. (t (call-interactively 'backward-word))))
  15373. (defun org-metaright (&optional _arg)
  15374. "Demote heading, list item at point or move table column right.
  15375. In front of a drawer or a block keyword, indent it correctly.
  15376. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  15377. `org-indent-drawer' or `org-indent-block' depending on context.
  15378. With no specific context, calls the Emacs default `forward-word'.
  15379. See the individual commands for more information.
  15380. This function runs the hook `org-metaright-hook' as a first step,
  15381. and returns at first non-nil value."
  15382. (interactive "P")
  15383. (cond
  15384. ((run-hook-with-args-until-success 'org-metaright-hook))
  15385. ((org-at-table-p) (call-interactively 'org-table-move-column))
  15386. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  15387. ((org-at-block-p) (call-interactively 'org-indent-block))
  15388. ((org-with-limited-levels
  15389. (or (org-at-heading-p)
  15390. (and (org-region-active-p)
  15391. (save-excursion
  15392. (goto-char (region-beginning))
  15393. (org-at-heading-p)))))
  15394. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15395. (call-interactively 'org-do-demote))
  15396. ;; At an inline task.
  15397. ((org-at-heading-p)
  15398. (call-interactively 'org-inlinetask-demote))
  15399. ((or (org-at-item-p)
  15400. (and (org-region-active-p)
  15401. (save-excursion
  15402. (goto-char (region-beginning))
  15403. (org-at-item-p))))
  15404. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15405. (call-interactively 'org-indent-item))
  15406. (t (call-interactively 'forward-word))))
  15407. (defun org-check-for-hidden (what)
  15408. "Check if there are hidden headlines/items in the current visual line.
  15409. WHAT can be either `headlines' or `items'. If the current line is
  15410. an outline or item heading and it has a folded subtree below it,
  15411. this function returns t, nil otherwise."
  15412. (let ((re (cond
  15413. ((eq what 'headlines) org-outline-regexp-bol)
  15414. ((eq what 'items) (org-item-beginning-re))
  15415. (t (error "This should not happen"))))
  15416. beg end)
  15417. (save-excursion
  15418. (catch 'exit
  15419. (unless (org-region-active-p)
  15420. (setq beg (point-at-bol))
  15421. (beginning-of-line 2)
  15422. (while (and (not (eobp)) ;; this is like `next-line'
  15423. (get-char-property (1- (point)) 'invisible))
  15424. (beginning-of-line 2))
  15425. (setq end (point))
  15426. (goto-char beg)
  15427. (goto-char (point-at-eol))
  15428. (setq end (max end (point)))
  15429. (while (re-search-forward re end t)
  15430. (when (get-char-property (match-beginning 0) 'invisible)
  15431. (throw 'exit t))))
  15432. nil))))
  15433. (defun org-metaup (&optional _arg)
  15434. "Move subtree up or move table row up.
  15435. Calls `org-move-subtree-up' or `org-table-move-row' or
  15436. `org-move-item-up', depending on context. See the individual commands
  15437. for more information."
  15438. (interactive "P")
  15439. (cond
  15440. ((run-hook-with-args-until-success 'org-metaup-hook))
  15441. ((org-region-active-p)
  15442. (let* ((a (save-excursion
  15443. (goto-char (min (region-beginning) (region-end)))
  15444. (line-beginning-position)))
  15445. (b (save-excursion
  15446. (goto-char (max (region-beginning) (region-end)))
  15447. (if (bolp) (1- (point)) (line-end-position))))
  15448. (c (save-excursion
  15449. (goto-char a)
  15450. (move-beginning-of-line 0)
  15451. (point)))
  15452. (d (save-excursion
  15453. (goto-char a)
  15454. (move-end-of-line 0)
  15455. (point))))
  15456. (transpose-regions a b c d)
  15457. (goto-char c)))
  15458. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  15459. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  15460. ((org-at-item-p) (call-interactively 'org-move-item-up))
  15461. (t (org-drag-element-backward))))
  15462. (defun org-metadown (&optional _arg)
  15463. "Move subtree down or move table row down.
  15464. Calls `org-move-subtree-down' or `org-table-move-row' or
  15465. `org-move-item-down', depending on context. See the individual
  15466. commands for more information."
  15467. (interactive "P")
  15468. (cond
  15469. ((run-hook-with-args-until-success 'org-metadown-hook))
  15470. ((org-region-active-p)
  15471. (let* ((a (save-excursion
  15472. (goto-char (min (region-beginning) (region-end)))
  15473. (line-beginning-position)))
  15474. (b (save-excursion
  15475. (goto-char (max (region-beginning) (region-end)))
  15476. (if (bolp) (1- (point)) (line-end-position))))
  15477. (c (save-excursion
  15478. (goto-char b)
  15479. (move-beginning-of-line (if (bolp) 1 2))
  15480. (point)))
  15481. (d (save-excursion
  15482. (goto-char b)
  15483. (move-end-of-line (if (bolp) 1 2))
  15484. (point))))
  15485. (transpose-regions a b c d)
  15486. (goto-char d)))
  15487. ((org-at-table-p) (call-interactively 'org-table-move-row))
  15488. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  15489. ((org-at-item-p) (call-interactively 'org-move-item-down))
  15490. (t (org-drag-element-forward))))
  15491. (defun org-shiftup (&optional arg)
  15492. "Act on current element according to context.
  15493. Call `org-timestamp-up' or `org-priority-up', or
  15494. `org-previous-item', or `org-table-move-cell-up'. See the
  15495. individual commands for more information."
  15496. (interactive "P")
  15497. (cond
  15498. ((run-hook-with-args-until-success 'org-shiftup-hook))
  15499. ((and org-support-shift-select (org-region-active-p))
  15500. (org-call-for-shift-select 'previous-line))
  15501. ((org-at-timestamp-p 'lax)
  15502. (call-interactively (if org-edit-timestamp-down-means-later
  15503. 'org-timestamp-down 'org-timestamp-up)))
  15504. ((and (not (eq org-support-shift-select 'always))
  15505. org-priority-enable-commands
  15506. (org-at-heading-p))
  15507. (call-interactively 'org-priority-up))
  15508. ((and (not org-support-shift-select) (org-at-item-p))
  15509. (call-interactively 'org-previous-item))
  15510. ((org-clocktable-try-shift 'up arg))
  15511. ((and (not (eq org-support-shift-select 'always))
  15512. (org-at-table-p))
  15513. (org-table-move-cell-up))
  15514. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  15515. (org-support-shift-select
  15516. (org-call-for-shift-select 'previous-line))
  15517. (t (org-shiftselect-error))))
  15518. (defun org-shiftdown (&optional arg)
  15519. "Act on current element according to context.
  15520. Call `org-timestamp-down' or `org-priority-down', or
  15521. `org-next-item', or `org-table-move-cell-down'. See the
  15522. individual commands for more information."
  15523. (interactive "P")
  15524. (cond
  15525. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  15526. ((and org-support-shift-select (org-region-active-p))
  15527. (org-call-for-shift-select 'next-line))
  15528. ((org-at-timestamp-p 'lax)
  15529. (call-interactively (if org-edit-timestamp-down-means-later
  15530. 'org-timestamp-up 'org-timestamp-down)))
  15531. ((and (not (eq org-support-shift-select 'always))
  15532. org-priority-enable-commands
  15533. (org-at-heading-p))
  15534. (call-interactively 'org-priority-down))
  15535. ((and (not org-support-shift-select) (org-at-item-p))
  15536. (call-interactively 'org-next-item))
  15537. ((org-clocktable-try-shift 'down arg))
  15538. ((and (not (eq org-support-shift-select 'always))
  15539. (org-at-table-p))
  15540. (org-table-move-cell-down))
  15541. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  15542. (org-support-shift-select
  15543. (org-call-for-shift-select 'next-line))
  15544. (t (org-shiftselect-error))))
  15545. (defun org-shiftright (&optional arg)
  15546. "Act on the current element according to context.
  15547. This does one of the following:
  15548. - switch a timestamp at point one day into the future
  15549. - on a headline, switch to the next TODO keyword
  15550. - on an item, switch entire list to the next bullet type
  15551. - on a property line, switch to the next allowed value
  15552. - on a clocktable definition line, move time block into the future
  15553. - in a table, move a single cell right"
  15554. (interactive "P")
  15555. (cond
  15556. ((run-hook-with-args-until-success 'org-shiftright-hook))
  15557. ((and org-support-shift-select (org-region-active-p))
  15558. (org-call-for-shift-select 'forward-char))
  15559. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  15560. ((and (not (eq org-support-shift-select 'always))
  15561. (org-at-heading-p))
  15562. (let ((org-inhibit-logging
  15563. (not org-treat-S-cursor-todo-selection-as-state-change))
  15564. (org-inhibit-blocking
  15565. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15566. (org-call-with-arg 'org-todo 'right)))
  15567. ((or (and org-support-shift-select
  15568. (not (eq org-support-shift-select 'always))
  15569. (org-at-item-bullet-p))
  15570. (and (not org-support-shift-select) (org-at-item-p)))
  15571. (org-call-with-arg 'org-cycle-list-bullet nil))
  15572. ((and (not (eq org-support-shift-select 'always))
  15573. (org-at-property-p))
  15574. (call-interactively 'org-property-next-allowed-value))
  15575. ((org-clocktable-try-shift 'right arg))
  15576. ((and (not (eq org-support-shift-select 'always))
  15577. (org-at-table-p))
  15578. (org-table-move-cell-right))
  15579. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  15580. (org-support-shift-select
  15581. (org-call-for-shift-select 'forward-char))
  15582. (t (org-shiftselect-error))))
  15583. (defun org-shiftleft (&optional arg)
  15584. "Act on current element according to context.
  15585. This does one of the following:
  15586. - switch a timestamp at point one day into the past
  15587. - on a headline, switch to the previous TODO keyword.
  15588. - on an item, switch entire list to the previous bullet type
  15589. - on a property line, switch to the previous allowed value
  15590. - on a clocktable definition line, move time block into the past
  15591. - in a table, move a single cell left"
  15592. (interactive "P")
  15593. (cond
  15594. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  15595. ((and org-support-shift-select (org-region-active-p))
  15596. (org-call-for-shift-select 'backward-char))
  15597. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  15598. ((and (not (eq org-support-shift-select 'always))
  15599. (org-at-heading-p))
  15600. (let ((org-inhibit-logging
  15601. (not org-treat-S-cursor-todo-selection-as-state-change))
  15602. (org-inhibit-blocking
  15603. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15604. (org-call-with-arg 'org-todo 'left)))
  15605. ((or (and org-support-shift-select
  15606. (not (eq org-support-shift-select 'always))
  15607. (org-at-item-bullet-p))
  15608. (and (not org-support-shift-select) (org-at-item-p)))
  15609. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  15610. ((and (not (eq org-support-shift-select 'always))
  15611. (org-at-property-p))
  15612. (call-interactively 'org-property-previous-allowed-value))
  15613. ((org-clocktable-try-shift 'left arg))
  15614. ((and (not (eq org-support-shift-select 'always))
  15615. (org-at-table-p))
  15616. (org-table-move-cell-left))
  15617. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  15618. (org-support-shift-select
  15619. (org-call-for-shift-select 'backward-char))
  15620. (t (org-shiftselect-error))))
  15621. (defun org-shiftcontrolright ()
  15622. "Switch to next TODO set."
  15623. (interactive)
  15624. (cond
  15625. ((and org-support-shift-select (org-region-active-p))
  15626. (org-call-for-shift-select 'forward-word))
  15627. ((and (not (eq org-support-shift-select 'always))
  15628. (org-at-heading-p))
  15629. (org-call-with-arg 'org-todo 'nextset))
  15630. (org-support-shift-select
  15631. (org-call-for-shift-select 'forward-word))
  15632. (t (org-shiftselect-error))))
  15633. (defun org-shiftcontrolleft ()
  15634. "Switch to previous TODO set."
  15635. (interactive)
  15636. (cond
  15637. ((and org-support-shift-select (org-region-active-p))
  15638. (org-call-for-shift-select 'backward-word))
  15639. ((and (not (eq org-support-shift-select 'always))
  15640. (org-at-heading-p))
  15641. (org-call-with-arg 'org-todo 'previousset))
  15642. (org-support-shift-select
  15643. (org-call-for-shift-select 'backward-word))
  15644. (t (org-shiftselect-error))))
  15645. (defun org-shiftcontrolup (&optional n)
  15646. "Change timestamps synchronously up in CLOCK log lines.
  15647. Optional argument N tells to change by that many units."
  15648. (interactive "P")
  15649. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  15650. (let (org-support-shift-select)
  15651. (org-clock-timestamps-up n))
  15652. (user-error "Not at a clock log")))
  15653. (defun org-shiftcontroldown (&optional n)
  15654. "Change timestamps synchronously down in CLOCK log lines.
  15655. Optional argument N tells to change by that many units."
  15656. (interactive "P")
  15657. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  15658. (let (org-support-shift-select)
  15659. (org-clock-timestamps-down n))
  15660. (user-error "Not at a clock log")))
  15661. (defun org-increase-number-at-point (&optional inc)
  15662. "Increment the number at point.
  15663. With an optional prefix numeric argument INC, increment using
  15664. this numeric value."
  15665. (interactive "p")
  15666. (if (not (number-at-point))
  15667. (user-error "Not on a number")
  15668. (unless inc (setq inc 1))
  15669. (let ((pos (point))
  15670. (beg (skip-chars-backward "-+^/*0-9eE."))
  15671. (end (skip-chars-forward "-+^/*0-9eE.")) nap)
  15672. (setq nap (buffer-substring-no-properties
  15673. (+ pos beg) (+ pos beg end)))
  15674. (delete-region (+ pos beg) (+ pos beg end))
  15675. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  15676. (when (org-at-table-p)
  15677. (org-table-align)
  15678. (org-table-end-of-field 1))))
  15679. (defun org-decrease-number-at-point (&optional inc)
  15680. "Decrement the number at point.
  15681. With an optional prefix numeric argument INC, decrement using
  15682. this numeric value."
  15683. (interactive "p")
  15684. (org-increase-number-at-point (- (or inc 1))))
  15685. (defun org-ctrl-c-ret ()
  15686. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  15687. (interactive)
  15688. (cond
  15689. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  15690. (t (call-interactively 'org-insert-heading))))
  15691. (defun org-copy-visible (beg end)
  15692. "Copy the visible parts of the region."
  15693. (interactive "r")
  15694. (let ((result ""))
  15695. (while (/= beg end)
  15696. (when (get-char-property beg 'invisible)
  15697. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  15698. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  15699. (setq result (concat result (buffer-substring beg next)))
  15700. (setq beg next)))
  15701. (setq deactivate-mark t)
  15702. (kill-new result)
  15703. (message "Visible strings have been copied to the kill ring.")))
  15704. (defun org-copy-special ()
  15705. "Copy region in table or copy current subtree.
  15706. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  15707. context. See the individual commands for more information."
  15708. (interactive)
  15709. (call-interactively
  15710. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  15711. (defun org-cut-special ()
  15712. "Cut region in table or cut current subtree.
  15713. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  15714. context. See the individual commands for more information."
  15715. (interactive)
  15716. (call-interactively
  15717. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  15718. (defun org-paste-special (arg)
  15719. "Paste rectangular region into table, or past subtree relative to level.
  15720. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  15721. See the individual commands for more information."
  15722. (interactive "P")
  15723. (if (org-at-table-p)
  15724. (org-table-paste-rectangle)
  15725. (org-paste-subtree arg)))
  15726. (defun org-edit-special (&optional arg)
  15727. "Call a special editor for the element at point.
  15728. When at a table, call the formula editor with `org-table-edit-formulas'.
  15729. When in a source code block, call `org-edit-src-code'.
  15730. When in a fixed-width region, call `org-edit-fixed-width-region'.
  15731. When in an export block, call `org-edit-export-block'.
  15732. When in a LaTeX environment, call `org-edit-latex-environment'.
  15733. When at an #+INCLUDE keyword, visit the included file.
  15734. When at a footnote reference, call `org-edit-footnote-reference'.
  15735. When at a planning line call, `org-deadline' and/or `org-schedule'.
  15736. When at an active timestamp, call `org-time-stamp'.
  15737. When at an inactive timestamp, call `org-time-stamp-inactive'.
  15738. On a link, call `ffap' to visit the link at point.
  15739. Otherwise, return a user error."
  15740. (interactive "P")
  15741. (let ((element (org-element-at-point)))
  15742. (barf-if-buffer-read-only)
  15743. (pcase (org-element-type element)
  15744. (`src-block
  15745. (if (not arg) (org-edit-src-code)
  15746. (let* ((info (org-babel-get-src-block-info))
  15747. (lang (nth 0 info))
  15748. (params (nth 2 info))
  15749. (session (cdr (assq :session params))))
  15750. (if (not session) (org-edit-src-code)
  15751. ;; At a source block with a session and function called
  15752. ;; with an ARG: switch to the buffer related to the
  15753. ;; inferior process.
  15754. (switch-to-buffer
  15755. (funcall (intern (concat "org-babel-prep-session:" lang))
  15756. session params))))))
  15757. (`keyword
  15758. (unless (member (org-element-property :key element)
  15759. '("INCLUDE" "SETUPFILE"))
  15760. (user-error "No special environment to edit here"))
  15761. (let ((value (org-element-property :value element)))
  15762. (unless (org-string-nw-p value) (user-error "No file to edit"))
  15763. (let ((file (and (string-match "\\`\"\\(.*?\\)\"\\|\\S-+" value)
  15764. (or (match-string 1 value)
  15765. (match-string 0 value)))))
  15766. (when (org-file-url-p file)
  15767. (user-error "Files located with a URL cannot be edited"))
  15768. (org-link-open-from-string
  15769. (format "[[%s]]" (expand-file-name file))))))
  15770. (`table
  15771. (if (eq (org-element-property :type element) 'table.el)
  15772. (org-edit-table.el)
  15773. (call-interactively 'org-table-edit-formulas)))
  15774. ;; Only Org tables contain `table-row' type elements.
  15775. (`table-row (call-interactively 'org-table-edit-formulas))
  15776. (`example-block (org-edit-src-code))
  15777. (`export-block (org-edit-export-block))
  15778. (`fixed-width (org-edit-fixed-width-region))
  15779. (`latex-environment (org-edit-latex-environment))
  15780. (`planning
  15781. (let ((proplist (cadr element)))
  15782. (mapc #'call-interactively
  15783. (remq nil
  15784. (list
  15785. (when (plist-get proplist :deadline) #'org-deadline)
  15786. (when (plist-get proplist :scheduled) #'org-schedule))))))
  15787. (_
  15788. ;; No notable element at point. Though, we may be at a link or
  15789. ;; a footnote reference, which are objects. Thus, scan deeper.
  15790. (let ((context (org-element-context element)))
  15791. (pcase (org-element-type context)
  15792. (`footnote-reference (org-edit-footnote-reference))
  15793. (`inline-src-block (org-edit-inline-src-code))
  15794. (`timestamp (if (eq 'inactive (org-element-property :type context))
  15795. (call-interactively #'org-time-stamp-inactive)
  15796. (call-interactively #'org-time-stamp)))
  15797. (`link (call-interactively #'ffap))
  15798. (_ (user-error "No special environment to edit here"))))))))
  15799. (defun org-ctrl-c-ctrl-c (&optional arg)
  15800. "Set tags in headline, or update according to changed information at point.
  15801. This command does many different things, depending on context:
  15802. - If column view is active, in agenda or org buffers, quit it.
  15803. - If there are highlights, remove them.
  15804. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  15805. this is what we do.
  15806. - If the cursor is on a statistics cookie, update it.
  15807. - If the cursor is in a headline, in an agenda or an org buffer,
  15808. prompt for tags and insert them into the current line, aligned
  15809. to `org-tags-column'. When called with prefix arg, realign all
  15810. tags in the current buffer.
  15811. - If the cursor is in one of the special #+KEYWORD lines, this
  15812. triggers scanning the buffer for these lines and updating the
  15813. information.
  15814. - If the cursor is inside a table, realign the table. This command
  15815. works even if the automatic table editor has been turned off.
  15816. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  15817. the entire table.
  15818. - If the cursor is at a footnote reference or definition, jump to
  15819. the corresponding definition or references, respectively.
  15820. - If the cursor is a the beginning of a dynamic block, update it.
  15821. - If the current buffer is a capture buffer, close note and file it.
  15822. - If the cursor is on a <<<target>>>, update radio targets and
  15823. corresponding links in this buffer.
  15824. - If the cursor is on a numbered item in a plain list, renumber the
  15825. ordered list.
  15826. - If the cursor is on a checkbox, toggle it.
  15827. - If the cursor is on a code block, evaluate it. The variable
  15828. `org-confirm-babel-evaluate' can be used to control prompting
  15829. before code block evaluation, by default every code block
  15830. evaluation requires confirmation. Code block evaluation can be
  15831. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  15832. (interactive "P")
  15833. (cond
  15834. ((bound-and-true-p org-columns-overlays) (org-columns-quit))
  15835. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  15836. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  15837. (org-remove-occur-highlights)
  15838. (message "Temporary highlights/overlays removed from current buffer"))
  15839. ((and (local-variable-p 'org-finish-function)
  15840. (fboundp org-finish-function))
  15841. (funcall org-finish-function))
  15842. ((org-babel-hash-at-point))
  15843. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  15844. (t
  15845. (let* ((context
  15846. (org-element-lineage
  15847. (org-element-context)
  15848. ;; Limit to supported contexts.
  15849. '(babel-call clock dynamic-block footnote-definition
  15850. footnote-reference inline-babel-call inline-src-block
  15851. inlinetask item keyword node-property paragraph
  15852. plain-list planning property-drawer radio-target
  15853. src-block statistics-cookie table table-cell table-row
  15854. timestamp)
  15855. t))
  15856. (radio-list-p (org-at-radio-list-p))
  15857. (type (org-element-type context)))
  15858. ;; For convenience: at the first line of a paragraph on the same
  15859. ;; line as an item, apply function on that item instead.
  15860. (when (eq type 'paragraph)
  15861. (let ((parent (org-element-property :parent context)))
  15862. (when (and (eq (org-element-type parent) 'item)
  15863. (= (line-beginning-position)
  15864. (org-element-property :begin parent)))
  15865. (setq context parent)
  15866. (setq type 'item))))
  15867. ;; Act according to type of element or object at point.
  15868. ;;
  15869. ;; Do nothing on a blank line, except if it is contained in
  15870. ;; a source block. Hence, we first check if point is in such
  15871. ;; a block and then if it is at a blank line.
  15872. (pcase type
  15873. ((or `inline-src-block `src-block)
  15874. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  15875. (org-babel-eval-wipe-error-buffer)
  15876. (org-babel-execute-src-block
  15877. current-prefix-arg (org-babel-get-src-block-info nil context))))
  15878. ((guard (org-match-line "[ \t]*$"))
  15879. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  15880. (user-error
  15881. (substitute-command-keys
  15882. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  15883. ((or `babel-call `inline-babel-call)
  15884. (let ((info (org-babel-lob-get-info context)))
  15885. (when info (org-babel-execute-src-block nil info))))
  15886. (`clock (org-clock-update-time-maybe))
  15887. (`dynamic-block
  15888. (save-excursion
  15889. (goto-char (org-element-property :post-affiliated context))
  15890. (org-update-dblock)))
  15891. (`footnote-definition
  15892. (goto-char (org-element-property :post-affiliated context))
  15893. (call-interactively 'org-footnote-action))
  15894. (`footnote-reference (call-interactively #'org-footnote-action))
  15895. ((or `headline `inlinetask)
  15896. (save-excursion (goto-char (org-element-property :begin context))
  15897. (call-interactively #'org-set-tags-command)))
  15898. (`item
  15899. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  15900. ;; unconditionally, whereas `C-u' will toggle its presence.
  15901. ;; Without a universal argument, if the item has a checkbox,
  15902. ;; toggle it. Otherwise repair the list.
  15903. (if (or radio-list-p
  15904. (and (boundp org-list-checkbox-radio-mode)
  15905. org-list-checkbox-radio-mode))
  15906. (org-toggle-radio-button arg)
  15907. (let* ((box (org-element-property :checkbox context))
  15908. (struct (org-element-property :structure context))
  15909. (old-struct (copy-tree struct))
  15910. (parents (org-list-parents-alist struct))
  15911. (prevs (org-list-prevs-alist struct))
  15912. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  15913. (org-list-set-checkbox
  15914. (org-element-property :begin context) struct
  15915. (cond ((equal arg '(16)) "[-]")
  15916. ((and (not box) (equal arg '(4))) "[ ]")
  15917. ((or (not box) (equal arg '(4))) nil)
  15918. ((eq box 'on) "[ ]")
  15919. (t "[X]")))
  15920. ;; Mimic `org-list-write-struct' but with grabbing a return
  15921. ;; value from `org-list-struct-fix-box'.
  15922. (org-list-struct-fix-ind struct parents 2)
  15923. (org-list-struct-fix-item-end struct)
  15924. (org-list-struct-fix-bul struct prevs)
  15925. (org-list-struct-fix-ind struct parents)
  15926. (let ((block-item
  15927. (org-list-struct-fix-box struct parents prevs orderedp)))
  15928. (if (and box (equal struct old-struct))
  15929. (if (equal arg '(16))
  15930. (message "Checkboxes already reset")
  15931. (user-error "Cannot toggle this checkbox: %s"
  15932. (if (eq box 'on)
  15933. "all subitems checked"
  15934. "unchecked subitems")))
  15935. (org-list-struct-apply-struct struct old-struct)
  15936. (org-update-checkbox-count-maybe))
  15937. (when block-item
  15938. (message "Checkboxes were removed due to empty box at line %d"
  15939. (org-current-line block-item)))))))
  15940. (`plain-list
  15941. ;; At a plain list, with a double C-u argument, set
  15942. ;; checkboxes of each item to "[-]", whereas a single one
  15943. ;; will toggle their presence according to the state of the
  15944. ;; first item in the list. Without an argument, repair the
  15945. ;; list.
  15946. (if (or radio-list-p
  15947. (and (boundp org-list-checkbox-radio-mode)
  15948. org-list-checkbox-radio-mode))
  15949. (org-toggle-radio-button arg)
  15950. (let* ((begin (org-element-property :contents-begin context))
  15951. (struct (org-element-property :structure context))
  15952. (old-struct (copy-tree struct))
  15953. (first-box (save-excursion
  15954. (goto-char begin)
  15955. (looking-at org-list-full-item-re)
  15956. (match-string-no-properties 3)))
  15957. (new-box (cond ((equal arg '(16)) "[-]")
  15958. ((equal arg '(4)) (unless first-box "[ ]"))
  15959. ((equal first-box "[X]") "[ ]")
  15960. (t "[X]"))))
  15961. (cond
  15962. (arg
  15963. (dolist (pos
  15964. (org-list-get-all-items
  15965. begin struct (org-list-prevs-alist struct)))
  15966. (org-list-set-checkbox pos struct new-box)))
  15967. ((and first-box (eq (point) begin))
  15968. ;; For convenience, when point is at bol on the first
  15969. ;; item of the list and no argument is provided, simply
  15970. ;; toggle checkbox of that item, if any.
  15971. (org-list-set-checkbox begin struct new-box)))
  15972. (when (equal
  15973. (org-list-write-struct
  15974. struct (org-list-parents-alist struct) old-struct)
  15975. old-struct)
  15976. (message "Cannot update this checkbox"))
  15977. (org-update-checkbox-count-maybe))))
  15978. (`keyword
  15979. (let ((org-inhibit-startup-visibility-stuff t)
  15980. (org-startup-align-all-tables nil))
  15981. (when (boundp 'org-table-coordinate-overlays)
  15982. (mapc #'delete-overlay org-table-coordinate-overlays)
  15983. (setq org-table-coordinate-overlays nil))
  15984. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  15985. (message "Local setup has been refreshed"))
  15986. ((or `property-drawer `node-property)
  15987. (call-interactively #'org-property-action))
  15988. (`radio-target
  15989. (call-interactively #'org-update-radio-target-regexp))
  15990. (`statistics-cookie
  15991. (call-interactively #'org-update-statistics-cookies))
  15992. ((or `table `table-cell `table-row)
  15993. ;; At a table, recalculate every field and align it. Also
  15994. ;; send the table if necessary. If the table has
  15995. ;; a `table.el' type, just give up. At a table row or cell,
  15996. ;; maybe recalculate line but always align table.
  15997. (if (eq (org-element-property :type context) 'table.el)
  15998. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  15999. Use `\\[org-edit-special]' to edit table.el tables"))
  16000. (if (or (eq type 'table)
  16001. ;; Check if point is at a TBLFM line.
  16002. (and (eq type 'table-row)
  16003. (= (point) (org-element-property :end context))))
  16004. (save-excursion
  16005. (if (org-at-TBLFM-p)
  16006. (progn (require 'org-table)
  16007. (org-table-calc-current-TBLFM))
  16008. (goto-char (org-element-property :contents-begin context))
  16009. (org-call-with-arg 'org-table-recalculate (or arg t))
  16010. (orgtbl-send-table 'maybe)))
  16011. (org-table-maybe-eval-formula)
  16012. (cond (arg (call-interactively #'org-table-recalculate))
  16013. ((org-table-maybe-recalculate-line))
  16014. (t (org-table-align))))))
  16015. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  16016. (org-timestamp-change 0 'day))
  16017. ((and `nil (guard (org-at-heading-p)))
  16018. ;; When point is on an unsupported object type, we can miss
  16019. ;; the fact that it also is at a heading. Handle it here.
  16020. (call-interactively #'org-set-tags-command))
  16021. ((guard
  16022. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  16023. (_
  16024. (user-error
  16025. (substitute-command-keys
  16026. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  16027. (defun org-mode-restart ()
  16028. (interactive)
  16029. (let ((indent-status (bound-and-true-p org-indent-mode)))
  16030. (funcall major-mode)
  16031. (hack-local-variables)
  16032. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  16033. (org-indent-mode -1))
  16034. (org-reset-file-cache))
  16035. (message "%s restarted" major-mode))
  16036. (defun org-flag-above-first-heading (&optional arg)
  16037. "Hide from bob up to the first heading.
  16038. Move point to the beginning of first heading or end of buffer."
  16039. (goto-char (point-min))
  16040. (unless (org-at-heading-p)
  16041. (outline-next-heading))
  16042. (unless (bobp)
  16043. (org-flag-region 1 (1- (point)) (not arg) 'outline)))
  16044. (defun org-show-branches-buffer ()
  16045. "Show all branches in the buffer."
  16046. (org-flag-above-first-heading)
  16047. (outline-hide-sublevels 1)
  16048. (unless (eobp)
  16049. (outline-show-branches)
  16050. (while (outline-get-next-sibling)
  16051. (outline-show-branches)))
  16052. (goto-char (point-min)))
  16053. (defun org-kill-note-or-show-branches ()
  16054. "Abort storing current note, or show just branches."
  16055. (interactive)
  16056. (cond (org-finish-function
  16057. (let ((org-note-abort t)) (funcall org-finish-function)))
  16058. ((org-before-first-heading-p)
  16059. (org-show-branches-buffer)
  16060. (org-hide-archived-subtrees (point-min) (point-max)))
  16061. (t
  16062. (let ((beg (progn (org-back-to-heading) (point)))
  16063. (end (save-excursion (org-end-of-subtree t t) (point))))
  16064. (outline-hide-subtree)
  16065. (outline-show-branches)
  16066. (org-hide-archived-subtrees beg end)))))
  16067. (defun org-delete-indentation (&optional arg)
  16068. "Join current line to previous and fix whitespace at join.
  16069. If previous line is a headline add to headline title. Otherwise
  16070. the function calls `delete-indentation'.
  16071. With a non-nil optional argument, join it to the following one."
  16072. (interactive "*P")
  16073. (if (save-excursion
  16074. (beginning-of-line (if arg 1 0))
  16075. (let ((case-fold-search nil))
  16076. (looking-at org-complex-heading-regexp)))
  16077. ;; At headline.
  16078. (let ((tags-column (when (match-beginning 5)
  16079. (save-excursion (goto-char (match-beginning 5))
  16080. (current-column))))
  16081. (string (concat " " (progn (when arg (forward-line 1))
  16082. (org-trim (delete-and-extract-region
  16083. (line-beginning-position)
  16084. (line-end-position)))))))
  16085. (unless (bobp) (delete-region (point) (1- (point))))
  16086. (goto-char (or (match-end 4)
  16087. (match-beginning 5)
  16088. (match-end 0)))
  16089. (skip-chars-backward " \t")
  16090. (save-excursion (insert string))
  16091. ;; Adjust alignment of tags.
  16092. (cond
  16093. ((not tags-column)) ;no tags
  16094. (org-auto-align-tags (org-align-tags))
  16095. (t (org--align-tags-here tags-column)))) ;preserve tags column
  16096. (delete-indentation arg)))
  16097. (defun org-open-line (n)
  16098. "Insert a new row in tables, call `open-line' elsewhere.
  16099. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  16100. As a special case, when a document starts with a table, allow to
  16101. call `open-line' on the very first character."
  16102. (interactive "*p")
  16103. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  16104. (org-table-insert-row)
  16105. (open-line n)))
  16106. (defun org-return (&optional indent)
  16107. "Goto next table row or insert a newline.
  16108. Calls `org-table-next-row' or `newline', depending on context.
  16109. When optional INDENT argument is non-nil, call
  16110. `newline-and-indent' instead of `newline'.
  16111. When `org-return-follows-link' is non-nil and point is on
  16112. a timestamp or a link, call `org-open-at-point'. However, it
  16113. will not happen if point is in a table or on a \"dead\"
  16114. object (e.g., within a comment). In these case, you need to use
  16115. `org-open-at-point' directly."
  16116. (interactive)
  16117. (let ((context (if org-return-follows-link (org-element-context)
  16118. (org-element-at-point))))
  16119. (cond
  16120. ;; In a table, call `org-table-next-row'. However, before first
  16121. ;; column or after last one, split the table.
  16122. ((or (and (eq 'table (org-element-type context))
  16123. (not (eq 'table.el (org-element-property :type context)))
  16124. (>= (point) (org-element-property :contents-begin context))
  16125. (< (point) (org-element-property :contents-end context)))
  16126. (org-element-lineage context '(table-row table-cell) t))
  16127. (if (or (looking-at-p "[ \t]*$")
  16128. (save-excursion (skip-chars-backward " \t") (bolp)))
  16129. (insert "\n")
  16130. (org-table-justify-field-maybe)
  16131. (call-interactively #'org-table-next-row)))
  16132. ;; On a link or a timestamp, call `org-open-at-point' if
  16133. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  16134. ;; locations, e.g., in a comment, as `org-open-at-point'.
  16135. ((and org-return-follows-link
  16136. (or (and (eq 'link (org-element-type context))
  16137. ;; Ensure point is not on the white spaces after
  16138. ;; the link.
  16139. (let ((origin (point)))
  16140. (org-with-point-at (org-element-property :end context)
  16141. (skip-chars-backward " \t")
  16142. (> (point) origin))))
  16143. (org-in-regexp org-ts-regexp-both nil t)
  16144. (org-in-regexp org-tsr-regexp-both nil t)
  16145. (org-in-regexp org-link-any-re nil t)))
  16146. (call-interactively #'org-open-at-point))
  16147. ;; Insert newline in heading, but preserve tags.
  16148. ((and (not (bolp))
  16149. (let ((case-fold-search nil))
  16150. (org-match-line org-complex-heading-regexp)))
  16151. ;; At headline. Split line. However, if point is on keyword,
  16152. ;; priority cookie or tags, do not break any of them: add
  16153. ;; a newline after the headline instead.
  16154. (let ((tags-column (and (match-beginning 5)
  16155. (save-excursion (goto-char (match-beginning 5))
  16156. (current-column))))
  16157. (string
  16158. (when (and (match-end 4) (org-point-in-group (point) 4))
  16159. (delete-and-extract-region (point) (match-end 4)))))
  16160. ;; Adjust tag alignment.
  16161. (cond
  16162. ((not (and tags-column string)))
  16163. (org-auto-align-tags (org-align-tags))
  16164. (t (org--align-tags-here tags-column))) ;preserve tags column
  16165. (end-of-line)
  16166. (org-show-entry)
  16167. (if indent (newline-and-indent) (newline))
  16168. (when string (save-excursion (insert (org-trim string))))))
  16169. ;; In a list, make sure indenting keeps trailing text within.
  16170. ((and indent
  16171. (not (eolp))
  16172. (org-element-lineage context '(item)))
  16173. (let ((trailing-data
  16174. (delete-and-extract-region (point) (line-end-position))))
  16175. (newline-and-indent)
  16176. (save-excursion (insert trailing-data))))
  16177. (t
  16178. ;; Do not auto-fill when point is in an Org property drawer.
  16179. (let ((auto-fill-function (and (not (org-at-property-p))
  16180. auto-fill-function)))
  16181. (if indent
  16182. (newline-and-indent)
  16183. (newline)))))))
  16184. (defun org-return-indent ()
  16185. "Goto next table row or insert a newline and indent.
  16186. Calls `org-table-next-row' or `newline-and-indent', depending on
  16187. context. See the individual commands for more information."
  16188. (interactive)
  16189. (org-return t))
  16190. (defun org-ctrl-c-tab (&optional arg)
  16191. "Toggle columns width in a table, or show children.
  16192. Call `org-table-toggle-column-width' if point is in a table.
  16193. Otherwise, call `org-show-children'. ARG is the level to hide."
  16194. (interactive "p")
  16195. (if (org-at-table-p)
  16196. (call-interactively #'org-table-toggle-column-width)
  16197. (if (org-before-first-heading-p)
  16198. (progn
  16199. (org-flag-above-first-heading)
  16200. (outline-hide-sublevels (or arg 1))
  16201. (goto-char (point-min)))
  16202. (outline-hide-subtree)
  16203. (org-show-children arg))))
  16204. (defun org-ctrl-c-star ()
  16205. "Compute table, or change heading status of lines.
  16206. Calls `org-table-recalculate' or `org-toggle-heading',
  16207. depending on context."
  16208. (interactive)
  16209. (cond
  16210. ((org-at-table-p)
  16211. (call-interactively 'org-table-recalculate))
  16212. (t
  16213. ;; Convert all lines in region to list items
  16214. (call-interactively 'org-toggle-heading))))
  16215. (defun org-ctrl-c-minus ()
  16216. "Insert separator line in table or modify bullet status of line.
  16217. Also turns a plain line or a region of lines into list items.
  16218. Calls `org-table-insert-hline', `org-toggle-item', or
  16219. `org-cycle-list-bullet', depending on context."
  16220. (interactive)
  16221. (cond
  16222. ((org-at-table-p)
  16223. (call-interactively 'org-table-insert-hline))
  16224. ((org-region-active-p)
  16225. (call-interactively 'org-toggle-item))
  16226. ((org-in-item-p)
  16227. (call-interactively 'org-cycle-list-bullet))
  16228. (t
  16229. (call-interactively 'org-toggle-item))))
  16230. (defun org-toggle-heading (&optional nstars)
  16231. "Convert headings to normal text, or items or text to headings.
  16232. If there is no active region, only convert the current line.
  16233. With a `\\[universal-argument]' prefix, convert the whole list at
  16234. point into heading.
  16235. In a region:
  16236. - If the first non blank line is a headline, remove the stars
  16237. from all headlines in the region.
  16238. - If it is a normal line, turn each and every normal line (i.e.,
  16239. not an heading or an item) in the region into headings. If you
  16240. want to convert only the first line of this region, use one
  16241. universal prefix argument.
  16242. - If it is a plain list item, turn all plain list items into headings.
  16243. When converting a line into a heading, the number of stars is chosen
  16244. such that the lines become children of the current entry. However,
  16245. when a numeric prefix argument is given, its value determines the
  16246. number of stars to add."
  16247. (interactive "P")
  16248. (let ((skip-blanks
  16249. (function
  16250. ;; Return beginning of first non-blank line, starting from
  16251. ;; line at POS.
  16252. (lambda (pos)
  16253. (save-excursion
  16254. (goto-char pos)
  16255. (while (org-at-comment-p) (forward-line))
  16256. (skip-chars-forward " \r\t\n")
  16257. (point-at-bol)))))
  16258. beg end toggled)
  16259. ;; Determine boundaries of changes. If a universal prefix has
  16260. ;; been given, put the list in a region. If region ends at a bol,
  16261. ;; do not consider the last line to be in the region.
  16262. (when (and current-prefix-arg (org-at-item-p))
  16263. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  16264. (org-mark-element))
  16265. (if (org-region-active-p)
  16266. (setq beg (funcall skip-blanks (region-beginning))
  16267. end (copy-marker (save-excursion
  16268. (goto-char (region-end))
  16269. (if (bolp) (point) (point-at-eol)))))
  16270. (setq beg (funcall skip-blanks (point-at-bol))
  16271. end (copy-marker (point-at-eol))))
  16272. ;; Ensure inline tasks don't count as headings.
  16273. (org-with-limited-levels
  16274. (save-excursion
  16275. (goto-char beg)
  16276. (cond
  16277. ;; Case 1. Started at an heading: de-star headings.
  16278. ((org-at-heading-p)
  16279. (while (< (point) end)
  16280. (when (org-at-heading-p t)
  16281. (looking-at org-outline-regexp) (replace-match "")
  16282. (setq toggled t))
  16283. (forward-line)))
  16284. ;; Case 2. Started at an item: change items into headlines.
  16285. ;; One star will be added by `org-list-to-subtree'.
  16286. ((org-at-item-p)
  16287. (while (< (point) end)
  16288. (when (org-at-item-p)
  16289. ;; Pay attention to cases when region ends before list.
  16290. (let* ((struct (org-list-struct))
  16291. (list-end
  16292. (min (org-list-get-bottom-point struct) (1+ end))))
  16293. (save-restriction
  16294. (narrow-to-region (point) list-end)
  16295. (insert (org-list-to-subtree
  16296. (org-list-to-lisp t)
  16297. (pcase (org-current-level)
  16298. (`nil 1)
  16299. (l (1+ (org-reduced-level l)))))
  16300. "\n")))
  16301. (setq toggled t))
  16302. (forward-line)))
  16303. ;; Case 3. Started at normal text: make every line an heading,
  16304. ;; skipping headlines and items.
  16305. (t (let* ((stars
  16306. (make-string
  16307. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  16308. (add-stars
  16309. (cond (nstars "") ; stars from prefix only
  16310. ((equal stars "") "*") ; before first heading
  16311. (org-odd-levels-only "**") ; inside heading, odd
  16312. (t "*"))) ; inside heading, oddeven
  16313. (rpl (concat stars add-stars " "))
  16314. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  16315. (while (< (point) (if (equal nstars '(4)) lend end))
  16316. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  16317. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  16318. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  16319. (forward-line)))))))
  16320. (unless toggled (message "Cannot toggle heading from here"))))
  16321. (defun org-meta-return (&optional arg)
  16322. "Insert a new heading or wrap a region in a table.
  16323. Calls `org-insert-heading', `org-insert-item' or
  16324. `org-table-wrap-region', depending on context. When called with
  16325. an argument, unconditionally call `org-insert-heading'."
  16326. (interactive "P")
  16327. (org-check-before-invisible-edit 'insert)
  16328. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  16329. (call-interactively (cond (arg #'org-insert-heading)
  16330. ((org-at-table-p) #'org-table-wrap-region)
  16331. ((org-in-item-p) #'org-insert-item)
  16332. (t #'org-insert-heading)))))
  16333. ;;; Menu entries
  16334. (defsubst org-in-subtree-not-table-p ()
  16335. "Are we in a subtree and not in a table?"
  16336. (and (not (org-before-first-heading-p))
  16337. (not (org-at-table-p))))
  16338. ;; Define the Org mode menus
  16339. (easy-menu-define org-org-menu org-mode-map "Org menu"
  16340. `("Org"
  16341. ("Show/Hide"
  16342. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  16343. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  16344. ["Sparse Tree..." org-sparse-tree t]
  16345. ["Reveal Context" org-reveal t]
  16346. ["Show All" org-show-all t]
  16347. "--"
  16348. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  16349. "--"
  16350. ["New Heading" org-insert-heading t]
  16351. ("Navigate Headings"
  16352. ["Up" outline-up-heading t]
  16353. ["Next" outline-next-visible-heading t]
  16354. ["Previous" outline-previous-visible-heading t]
  16355. ["Next Same Level" outline-forward-same-level t]
  16356. ["Previous Same Level" outline-backward-same-level t]
  16357. "--"
  16358. ["Jump" org-goto t])
  16359. ("Edit Structure"
  16360. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  16361. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  16362. "--"
  16363. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  16364. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  16365. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  16366. "--"
  16367. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  16368. "--"
  16369. ["Copy visible text" org-copy-visible t]
  16370. "--"
  16371. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  16372. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  16373. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  16374. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  16375. "--"
  16376. ["Sort Region/Children" org-sort t]
  16377. "--"
  16378. ["Convert to odd levels" org-convert-to-odd-levels t]
  16379. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  16380. ("Editing"
  16381. ["Emphasis..." org-emphasize t]
  16382. ["Edit Source Example" org-edit-special t]
  16383. "--"
  16384. ["Footnote new/jump" org-footnote-action t]
  16385. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  16386. ("Archive"
  16387. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  16388. "--"
  16389. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  16390. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  16391. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)])
  16392. "--"
  16393. ("Hyperlinks"
  16394. ["Store Link (Global)" org-store-link t]
  16395. ["Find existing link to here" org-occur-link-in-agenda-files t]
  16396. ["Insert Link" org-insert-link t]
  16397. ["Follow Link" org-open-at-point t]
  16398. "--"
  16399. ["Next link" org-next-link t]
  16400. ["Previous link" org-previous-link t]
  16401. "--"
  16402. ["Descriptive Links"
  16403. org-toggle-link-display
  16404. :style radio
  16405. :selected org-descriptive-links
  16406. ]
  16407. ["Literal Links"
  16408. org-toggle-link-display
  16409. :style radio
  16410. :selected (not org-descriptive-links)])
  16411. "--"
  16412. ("TODO Lists"
  16413. ["TODO/DONE/-" org-todo t]
  16414. ("Select keyword"
  16415. ["Next keyword" org-shiftright (org-at-heading-p)]
  16416. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  16417. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  16418. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  16419. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  16420. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  16421. ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  16422. "--"
  16423. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  16424. :selected org-enforce-todo-dependencies :style toggle :active t]
  16425. "Settings for tree at point"
  16426. ["Do Children sequentially" org-toggle-ordered-property :style radio
  16427. :selected (org-entry-get nil "ORDERED")
  16428. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16429. ["Do Children parallel" org-toggle-ordered-property :style radio
  16430. :selected (not (org-entry-get nil "ORDERED"))
  16431. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16432. "--"
  16433. ["Set Priority" org-priority t]
  16434. ["Priority Up" org-shiftup t]
  16435. ["Priority Down" org-shiftdown t]
  16436. "--"
  16437. ["Get news from all feeds" org-feed-update-all t]
  16438. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  16439. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  16440. ("TAGS and Properties"
  16441. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  16442. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  16443. "--"
  16444. ["Set property" org-set-property (not (org-before-first-heading-p))]
  16445. ["Column view of properties" org-columns t]
  16446. ["Insert Column View DBlock" org-columns-insert-dblock t])
  16447. ("Dates and Scheduling"
  16448. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  16449. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  16450. ("Change Date"
  16451. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  16452. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  16453. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  16454. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  16455. ["Compute Time Range" org-evaluate-time-range t]
  16456. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  16457. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  16458. "--"
  16459. ["Custom time format" org-toggle-time-stamp-overlays
  16460. :style radio :selected org-display-custom-times]
  16461. "--"
  16462. ["Goto Calendar" org-goto-calendar t]
  16463. ["Date from Calendar" org-date-from-calendar t]
  16464. "--"
  16465. ["Start/Restart Timer" org-timer-start t]
  16466. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  16467. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  16468. ["Insert Timer String" org-timer t]
  16469. ["Insert Timer Item" org-timer-item t])
  16470. ("Logging work"
  16471. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  16472. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  16473. ["Clock out" org-clock-out t]
  16474. ["Clock cancel" org-clock-cancel t]
  16475. "--"
  16476. ["Mark as default task" org-clock-mark-default-task t]
  16477. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  16478. ["Goto running clock" org-clock-goto t]
  16479. "--"
  16480. ["Display times" org-clock-display t]
  16481. ["Create clock table" org-clock-report t]
  16482. "--"
  16483. ["Record DONE time"
  16484. (progn (setq org-log-done (not org-log-done))
  16485. (message "Switching to %s will %s record a timestamp"
  16486. (car org-done-keywords)
  16487. (if org-log-done "automatically" "not")))
  16488. :style toggle :selected org-log-done])
  16489. "--"
  16490. ["Agenda Command..." org-agenda t]
  16491. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  16492. ("File List for Agenda")
  16493. ("Special views current file"
  16494. ["TODO Tree" org-show-todo-tree t]
  16495. ["Check Deadlines" org-check-deadlines t]
  16496. ["Tags/Property tree" org-match-sparse-tree t])
  16497. "--"
  16498. ["Export/Publish..." org-export-dispatch t]
  16499. ("LaTeX"
  16500. ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  16501. :style toggle :selected org-cdlatex-mode]
  16502. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  16503. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  16504. ["Modify math symbol" org-cdlatex-math-modify
  16505. (org-inside-LaTeX-fragment-p)]
  16506. ["Insert citation" org-reftex-citation t])
  16507. "--"
  16508. ("Documentation"
  16509. ["Show Version" org-version t]
  16510. ["Info Documentation" org-info t]
  16511. ["Browse Org News" org-browse-news t])
  16512. ("Customize"
  16513. ["Browse Org Group" org-customize t]
  16514. "--"
  16515. ["Expand This Menu" org-create-customize-menu
  16516. (fboundp 'customize-menu-create)])
  16517. ["Send bug report" org-submit-bug-report t]
  16518. "--"
  16519. ("Refresh/Reload"
  16520. ["Refresh setup current buffer" org-mode-restart t]
  16521. ["Reload Org (after update)" org-reload t]
  16522. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])))
  16523. (easy-menu-define org-tbl-menu org-mode-map "Org Table menu"
  16524. '("Table"
  16525. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  16526. ["Next Field" org-cycle (org-at-table-p)]
  16527. ["Previous Field" org-shifttab (org-at-table-p)]
  16528. ["Next Row" org-return (org-at-table-p)]
  16529. "--"
  16530. ["Blank Field" org-table-blank-field (org-at-table-p)]
  16531. ["Edit Field" org-table-edit-field (org-at-table-p)]
  16532. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  16533. "--"
  16534. ("Column"
  16535. ["Move Column Left" org-metaleft (org-at-table-p)]
  16536. ["Move Column Right" org-metaright (org-at-table-p)]
  16537. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  16538. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  16539. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  16540. ("Row"
  16541. ["Move Row Up" org-metaup (org-at-table-p)]
  16542. ["Move Row Down" org-metadown (org-at-table-p)]
  16543. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  16544. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  16545. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  16546. "--"
  16547. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  16548. ("Rectangle"
  16549. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  16550. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  16551. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  16552. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  16553. "--"
  16554. ("Calculate"
  16555. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  16556. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  16557. ["Edit Formulas" org-edit-special (org-at-table-p)]
  16558. "--"
  16559. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  16560. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  16561. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  16562. "--"
  16563. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  16564. "--"
  16565. ["Sum Column/Rectangle" org-table-sum
  16566. (or (org-at-table-p) (org-region-active-p))]
  16567. ["Which Column?" org-table-current-column (org-at-table-p)])
  16568. ["Debug Formulas"
  16569. org-table-toggle-formula-debugger
  16570. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  16571. ["Show Col/Row Numbers"
  16572. org-table-toggle-coordinate-overlays
  16573. :style toggle
  16574. :selected (bound-and-true-p org-table-overlay-coordinates)]
  16575. "--"
  16576. ["Create" org-table-create (not (org-at-table-p))]
  16577. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  16578. ["Import from File" org-table-import (not (org-at-table-p))]
  16579. ["Export to File" org-table-export (org-at-table-p)]
  16580. "--"
  16581. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  16582. "--"
  16583. ("Plot"
  16584. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  16585. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  16586. (defun org-info (&optional node)
  16587. "Read documentation for Org in the info system.
  16588. With optional NODE, go directly to that node."
  16589. (interactive)
  16590. (info (format "(org)%s" (or node ""))))
  16591. (defun org-browse-news ()
  16592. "Browse the news for the latest major release."
  16593. (interactive)
  16594. (browse-url "https://orgmode.org/Changes.html"))
  16595. ;;;###autoload
  16596. (defun org-submit-bug-report ()
  16597. "Submit a bug report on Org via mail.
  16598. Don't hesitate to report any problems or inaccurate documentation.
  16599. If you don't have setup sending mail from (X)Emacs, please copy the
  16600. output buffer into your mail program, as it gives us important
  16601. information about your Org version and configuration."
  16602. (interactive)
  16603. (require 'reporter)
  16604. (defvar reporter-prompt-for-summary-p)
  16605. (org-load-modules-maybe)
  16606. (org-require-autoloaded-modules)
  16607. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  16608. (reporter-submit-bug-report
  16609. "emacs-orgmode@gnu.org"
  16610. (org-version nil 'full)
  16611. (let (list)
  16612. (save-window-excursion
  16613. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  16614. (delete-other-windows)
  16615. (erase-buffer)
  16616. (insert "You are about to submit a bug report to the Org mailing list.
  16617. If your report is about Org installation, please read this section:
  16618. https://orgmode.org/org.html#Installation
  16619. Please read https://orgmode.org/org.html#Feedback on how to make
  16620. a good report, it will help Org contributors fixing your problem.
  16621. Search https://lists.gnu.org/archive/html/emacs-orgmode/ to see
  16622. if the issue you are about to raise has already been dealt with.
  16623. We also would like to add your full Org and Outline configuration
  16624. to the bug report. It will help us debugging the issue.
  16625. *HOWEVER*, some variables you have customized may contain private
  16626. information. The names of customers, colleagues, or friends, might
  16627. appear in the form of file names, tags, todo states or search strings.
  16628. If you answer \"yes\" to the prompt, you might want to check and remove
  16629. such private information before sending the email.")
  16630. (add-text-properties (point-min) (point-max) '(face org-warning))
  16631. (when (yes-or-no-p "Include your Org configuration ")
  16632. (mapatoms
  16633. (lambda (v)
  16634. (and (boundp v)
  16635. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  16636. (or (and (symbol-value v)
  16637. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  16638. (and
  16639. (get v 'custom-type) (get v 'standard-value)
  16640. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  16641. (push v list)))))
  16642. (kill-buffer (get-buffer "*Warn about privacy*"))
  16643. list))
  16644. nil nil
  16645. "Remember to cover the basics, that is, what you expected to happen and
  16646. what in fact did happen. You don't know how to make a good report? See
  16647. https://orgmode.org/manual/Feedback.html#Feedback
  16648. Your bug report will be posted to the Org mailing list.
  16649. ------------------------------------------------------------------------")
  16650. (save-excursion
  16651. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  16652. (replace-match "\\1Bug: \\3 [\\2]")))))
  16653. (defun org-install-agenda-files-menu ()
  16654. (let ((bl (buffer-list)))
  16655. (save-excursion
  16656. (while bl
  16657. (set-buffer (pop bl))
  16658. (when (derived-mode-p 'org-mode) (setq bl nil)))
  16659. (when (derived-mode-p 'org-mode)
  16660. (easy-menu-change
  16661. '("Org") "File List for Agenda"
  16662. (append
  16663. (list
  16664. ["Edit File List" (org-edit-agenda-file-list) t]
  16665. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  16666. ["Remove Current File from List" org-remove-file t]
  16667. ["Cycle through agenda files" org-cycle-agenda-files t]
  16668. ["Occur in all agenda files" org-occur-in-agenda-files t]
  16669. "--")
  16670. (mapcar 'org-file-menu-entry
  16671. ;; Prevent initialization from failing.
  16672. (ignore-errors (org-agenda-files t)))))))))
  16673. ;;;; Documentation
  16674. (defun org-require-autoloaded-modules ()
  16675. (interactive)
  16676. (mapc #'require
  16677. '(org-agenda org-archive org-attach org-clock org-colview org-id
  16678. org-table org-timer)))
  16679. ;;;###autoload
  16680. (defun org-reload (&optional uncompiled)
  16681. "Reload all Org Lisp files.
  16682. With prefix arg UNCOMPILED, load the uncompiled versions."
  16683. (interactive "P")
  16684. (require 'loadhist)
  16685. (let* ((org-dir (org-find-library-dir "org"))
  16686. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  16687. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  16688. (remove-re (format "\\`%s\\'"
  16689. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  16690. (feats (delete-dups
  16691. (mapcar 'file-name-sans-extension
  16692. (mapcar 'file-name-nondirectory
  16693. (delq nil
  16694. (mapcar 'feature-file
  16695. features))))))
  16696. (lfeat (append
  16697. (sort
  16698. (setq feats
  16699. (delq nil (mapcar
  16700. (lambda (f)
  16701. (if (and (string-match feature-re f)
  16702. (not (string-match remove-re f)))
  16703. f nil))
  16704. feats)))
  16705. 'string-lessp)
  16706. (list "org-version" "org")))
  16707. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  16708. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  16709. load-uncore load-misses)
  16710. (setq load-misses
  16711. (delq 't
  16712. (mapcar (lambda (f)
  16713. (or (org-load-noerror-mustsuffix (concat org-dir f))
  16714. (and (string= org-dir contrib-dir)
  16715. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  16716. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  16717. (push f load-uncore)
  16718. 't)
  16719. f))
  16720. lfeat)))
  16721. (when load-uncore
  16722. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  16723. (if (> (length load-uncore) 1) "s were" " was")
  16724. (reverse load-uncore)))
  16725. (if load-misses
  16726. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  16727. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  16728. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  16729. ;;;###autoload
  16730. (defun org-customize ()
  16731. "Call the customize function with org as argument."
  16732. (interactive)
  16733. (org-load-modules-maybe)
  16734. (org-require-autoloaded-modules)
  16735. (customize-browse 'org))
  16736. (defun org-create-customize-menu ()
  16737. "Create a full customization menu for Org mode, insert it into the menu."
  16738. (interactive)
  16739. (org-load-modules-maybe)
  16740. (org-require-autoloaded-modules)
  16741. (if (fboundp 'customize-menu-create)
  16742. (progn
  16743. (easy-menu-change
  16744. '("Org") "Customize"
  16745. `(["Browse Org group" org-customize t]
  16746. "--"
  16747. ,(customize-menu-create 'org)
  16748. ["Set" Custom-set t]
  16749. ["Save" Custom-save t]
  16750. ["Reset to Current" Custom-reset-current t]
  16751. ["Reset to Saved" Custom-reset-saved t]
  16752. ["Reset to Standard Settings" Custom-reset-standard t]))
  16753. (message "\"Org\"-menu now contains full customization menu"))
  16754. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  16755. ;;;; Miscellaneous stuff
  16756. ;;; Generally useful functions
  16757. (defun org-in-clocktable-p ()
  16758. "Check if the cursor is in a clocktable."
  16759. (let ((pos (point)) start)
  16760. (save-excursion
  16761. (end-of-line 1)
  16762. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  16763. (setq start (match-beginning 0))
  16764. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  16765. (>= (match-end 0) pos)
  16766. start))))
  16767. (defun org-in-verbatim-emphasis ()
  16768. (save-match-data
  16769. (and (org-in-regexp org-verbatim-re 2)
  16770. (>= (point) (match-beginning 3))
  16771. (<= (point) (match-end 4)))))
  16772. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  16773. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  16774. (if (and marker (marker-buffer marker)
  16775. (buffer-live-p (marker-buffer marker)))
  16776. (progn
  16777. (pop-to-buffer-same-window (marker-buffer marker))
  16778. (when (or (> marker (point-max)) (< marker (point-min)))
  16779. (widen))
  16780. (goto-char marker)
  16781. (org-show-context 'org-goto))
  16782. (if bookmark
  16783. (bookmark-jump bookmark)
  16784. (error "Cannot find location"))))
  16785. (defun org-quote-csv-field (s)
  16786. "Quote field for inclusion in CSV material."
  16787. (if (string-match "[\",]" s)
  16788. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  16789. s))
  16790. (defun org-force-self-insert (N)
  16791. "Needed to enforce self-insert under remapping."
  16792. (interactive "p")
  16793. (self-insert-command N))
  16794. (defun org-quote-vert (s)
  16795. "Replace \"|\" with \"\\vert\"."
  16796. (while (string-match "|" s)
  16797. (setq s (replace-match "\\vert" t t s)))
  16798. s)
  16799. (defun org-uuidgen-p (s)
  16800. "Is S an ID created by UUIDGEN?"
  16801. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  16802. (defun org-in-src-block-p (&optional inside)
  16803. "Whether point is in a code source block.
  16804. When INSIDE is non-nil, don't consider we are within a source
  16805. block when point is at #+BEGIN_SRC or #+END_SRC."
  16806. (let ((case-fold-search t))
  16807. (or (and (eq (get-char-property (point) 'src-block) t))
  16808. (and (not inside)
  16809. (save-match-data
  16810. (save-excursion
  16811. (beginning-of-line)
  16812. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  16813. (defun org-context ()
  16814. "Return a list of contexts of the current cursor position.
  16815. If several contexts apply, all are returned.
  16816. Each context entry is a list with a symbol naming the context, and
  16817. two positions indicating start and end of the context. Possible
  16818. contexts are:
  16819. :headline anywhere in a headline
  16820. :headline-stars on the leading stars in a headline
  16821. :todo-keyword on a TODO keyword (including DONE) in a headline
  16822. :tags on the TAGS in a headline
  16823. :priority on the priority cookie in a headline
  16824. :item on the first line of a plain list item
  16825. :item-bullet on the bullet/number of a plain list item
  16826. :checkbox on the checkbox in a plain list item
  16827. :table in an Org table
  16828. :table-special on a special filed in a table
  16829. :table-table in a table.el table
  16830. :clocktable in a clocktable
  16831. :src-block in a source block
  16832. :link on a hyperlink
  16833. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  16834. :latex-fragment on a LaTeX fragment
  16835. :latex-preview on a LaTeX fragment with overlaid preview image
  16836. This function expects the position to be visible because it uses font-lock
  16837. faces as a help to recognize the following contexts: :table-special, :link,
  16838. and :keyword."
  16839. (let* ((f (get-text-property (point) 'face))
  16840. (faces (if (listp f) f (list f)))
  16841. (case-fold-search t)
  16842. (p (point)) clist o)
  16843. ;; First the large context
  16844. (cond
  16845. ((org-at-heading-p t)
  16846. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  16847. (when (progn
  16848. (beginning-of-line 1)
  16849. (looking-at org-todo-line-tags-regexp))
  16850. (push (org-point-in-group p 1 :headline-stars) clist)
  16851. (push (org-point-in-group p 2 :todo-keyword) clist)
  16852. (push (org-point-in-group p 4 :tags) clist))
  16853. (goto-char p)
  16854. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  16855. (when (looking-at "\\[#[A-Z0-9]\\]")
  16856. (push (org-point-in-group p 0 :priority) clist)))
  16857. ((org-at-item-p)
  16858. (push (org-point-in-group p 2 :item-bullet) clist)
  16859. (push (list :item (point-at-bol)
  16860. (save-excursion (org-end-of-item) (point)))
  16861. clist)
  16862. (and (org-at-item-checkbox-p)
  16863. (push (org-point-in-group p 0 :checkbox) clist)))
  16864. ((org-at-table-p)
  16865. (push (list :table (org-table-begin) (org-table-end)) clist)
  16866. (when (memq 'org-formula faces)
  16867. (push (list :table-special
  16868. (previous-single-property-change p 'face)
  16869. (next-single-property-change p 'face))
  16870. clist)))
  16871. ((org-at-table-p 'any)
  16872. (push (list :table-table) clist)))
  16873. (goto-char p)
  16874. (let ((case-fold-search t))
  16875. ;; New the "medium" contexts: clocktables, source blocks
  16876. (cond ((org-in-clocktable-p)
  16877. (push (list :clocktable
  16878. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  16879. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  16880. (match-beginning 1))
  16881. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  16882. (match-end 0)))
  16883. clist))
  16884. ((org-in-src-block-p)
  16885. (push (list :src-block
  16886. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  16887. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  16888. (match-beginning 1))
  16889. (and (search-forward "#+END_SRC" nil t)
  16890. (match-beginning 0)))
  16891. clist))))
  16892. (goto-char p)
  16893. ;; Now the small context
  16894. (cond
  16895. ((org-at-timestamp-p)
  16896. (push (org-point-in-group p 0 :timestamp) clist))
  16897. ((memq 'org-link faces)
  16898. (push (list :link
  16899. (previous-single-property-change p 'face)
  16900. (next-single-property-change p 'face))
  16901. clist))
  16902. ((memq 'org-special-keyword faces)
  16903. (push (list :keyword
  16904. (previous-single-property-change p 'face)
  16905. (next-single-property-change p 'face))
  16906. clist))
  16907. ((setq o (cl-some
  16908. (lambda (o)
  16909. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  16910. o))
  16911. (overlays-at (point))))
  16912. (push (list :latex-fragment
  16913. (overlay-start o) (overlay-end o))
  16914. clist)
  16915. (push (list :latex-preview
  16916. (overlay-start o) (overlay-end o))
  16917. clist))
  16918. ((org-inside-LaTeX-fragment-p)
  16919. ;; FIXME: positions wrong.
  16920. (push (list :latex-fragment (point) (point)) clist)))
  16921. (setq clist (nreverse (delq nil clist)))
  16922. clist))
  16923. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  16924. "Non-nil when point is between matches of START-RE and END-RE.
  16925. Also return a non-nil value when point is on one of the matches.
  16926. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  16927. buffer positions. Default values are the positions of headlines
  16928. surrounding the point.
  16929. The functions returns a cons cell whose car (resp. cdr) is the
  16930. position before START-RE (resp. after END-RE)."
  16931. (save-match-data
  16932. (let ((pos (point))
  16933. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  16934. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  16935. beg end)
  16936. (save-excursion
  16937. ;; Point is on a block when on START-RE or if START-RE can be
  16938. ;; found before it...
  16939. (and (or (org-in-regexp start-re)
  16940. (re-search-backward start-re limit-up t))
  16941. (setq beg (match-beginning 0))
  16942. ;; ... and END-RE after it...
  16943. (goto-char (match-end 0))
  16944. (re-search-forward end-re limit-down t)
  16945. (> (setq end (match-end 0)) pos)
  16946. ;; ... without another START-RE in-between.
  16947. (goto-char (match-beginning 0))
  16948. (not (re-search-backward start-re (1+ beg) t))
  16949. ;; Return value.
  16950. (cons beg end))))))
  16951. (defun org-in-block-p (names)
  16952. "Non-nil when point belongs to a block whose name belongs to NAMES.
  16953. NAMES is a list of strings containing names of blocks.
  16954. Return first block name matched, or nil. Beware that in case of
  16955. nested blocks, the returned name may not belong to the closest
  16956. block from point."
  16957. (save-match-data
  16958. (catch 'exit
  16959. (let ((case-fold-search t)
  16960. (lim-up (save-excursion (outline-previous-heading)))
  16961. (lim-down (save-excursion (outline-next-heading))))
  16962. (dolist (name names)
  16963. (let ((n (regexp-quote name)))
  16964. (when (org-between-regexps-p
  16965. (concat "^[ \t]*#\\+begin_" n)
  16966. (concat "^[ \t]*#\\+end_" n)
  16967. lim-up lim-down)
  16968. (throw 'exit n)))))
  16969. nil)))
  16970. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  16971. "Call `multi-occur' with buffers for all agenda files."
  16972. (interactive "sOrg-files matching: ")
  16973. (let* ((files (org-agenda-files))
  16974. (tnames (mapcar #'file-truename files))
  16975. (extra org-agenda-text-search-extra-files))
  16976. (when (eq (car extra) 'agenda-archives)
  16977. (setq extra (cdr extra))
  16978. (setq files (org-add-archive-files files)))
  16979. (dolist (f extra)
  16980. (unless (member (file-truename f) tnames)
  16981. (unless (member f files) (setq files (append files (list f))))
  16982. (setq tnames (append tnames (list (file-truename f))))))
  16983. (multi-occur
  16984. (mapcar (lambda (x)
  16985. (with-current-buffer
  16986. ;; FIXME: Why not just (find-file-noselect x)?
  16987. ;; Is it to avoid the "revert buffer" prompt?
  16988. (or (get-file-buffer x) (find-file-noselect x))
  16989. (widen)
  16990. (current-buffer)))
  16991. files)
  16992. regexp)))
  16993. (add-hook 'occur-mode-find-occurrence-hook
  16994. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  16995. (defun org-occur-link-in-agenda-files ()
  16996. "Create a link and search for it in the agendas.
  16997. The link is not stored in `org-stored-links', it is just created
  16998. for the search purpose."
  16999. (interactive)
  17000. (let ((link (condition-case nil
  17001. (org-store-link nil)
  17002. (error "Unable to create a link to here"))))
  17003. (org-occur-in-agenda-files (regexp-quote link))))
  17004. (defun org-back-over-empty-lines ()
  17005. "Move backwards over whitespace, to the beginning of the first empty line.
  17006. Returns the number of empty lines passed."
  17007. (let ((pos (point)))
  17008. (if (cdr (assq 'heading org-blank-before-new-entry))
  17009. (skip-chars-backward " \t\n\r")
  17010. (unless (eobp)
  17011. (forward-line -1)))
  17012. (beginning-of-line 2)
  17013. (goto-char (min (point) pos))
  17014. (count-lines (point) pos)))
  17015. ;;; TODO: Only called once, from ox-odt which should probably use
  17016. ;;; org-export-inline-image-p or something.
  17017. (defun org-file-image-p (file)
  17018. "Return non-nil if FILE is an image."
  17019. (save-match-data
  17020. (string-match (image-file-name-regexp) file)))
  17021. (defun org-get-cursor-date (&optional with-time)
  17022. "Return the date at cursor in as a time.
  17023. This works in the calendar and in the agenda, anywhere else it just
  17024. returns the current time.
  17025. If WITH-TIME is non-nil, returns the time of the event at point (in
  17026. the agenda) or the current time of the day; otherwise returns the
  17027. earliest time on the cursor date that Org treats as that date
  17028. (bearing in mind `org-extend-today-until')."
  17029. (let (date day defd tp hod mod)
  17030. (when with-time
  17031. (setq tp (get-text-property (point) 'time))
  17032. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  17033. (setq hod (string-to-number (match-string 1 tp))
  17034. mod (string-to-number (match-string 2 tp))))
  17035. (or tp (let ((now (decode-time)))
  17036. (setq hod (nth 2 now)
  17037. mod (nth 1 now)))))
  17038. (cond
  17039. ((eq major-mode 'calendar-mode)
  17040. (setq date (calendar-cursor-to-date)
  17041. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  17042. (nth 1 date) (nth 0 date) (nth 2 date))))
  17043. ((eq major-mode 'org-agenda-mode)
  17044. (setq day (get-text-property (point) 'day))
  17045. (when day
  17046. (setq date (calendar-gregorian-from-absolute day)
  17047. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  17048. (nth 1 date) (nth 0 date) (nth 2 date))))))
  17049. (or defd (current-time))))
  17050. (defun org-mark-subtree (&optional up)
  17051. "Mark the current subtree.
  17052. This puts point at the start of the current subtree, and mark at
  17053. the end. If a numeric prefix UP is given, move up into the
  17054. hierarchy of headlines by UP levels before marking the subtree."
  17055. (interactive "P")
  17056. (org-with-limited-levels
  17057. (cond ((org-at-heading-p) (beginning-of-line))
  17058. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  17059. (t (outline-previous-visible-heading 1))))
  17060. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  17061. (if (called-interactively-p 'any)
  17062. (call-interactively 'org-mark-element)
  17063. (org-mark-element)))
  17064. ;;; Indentation
  17065. (defvar org-element-greater-elements)
  17066. (defun org--get-expected-indentation (element contentsp)
  17067. "Expected indentation column for current line, according to ELEMENT.
  17068. ELEMENT is an element containing point. CONTENTSP is non-nil
  17069. when indentation is to be computed according to contents of
  17070. ELEMENT."
  17071. (let ((type (org-element-type element))
  17072. (start (org-element-property :begin element))
  17073. (post-affiliated (org-element-property :post-affiliated element)))
  17074. (org-with-wide-buffer
  17075. (cond
  17076. (contentsp
  17077. (cl-case type
  17078. ((diary-sexp footnote-definition) 0)
  17079. ((headline inlinetask nil)
  17080. (if (not org-adapt-indentation) 0
  17081. (let ((level (org-current-level)))
  17082. (if level (1+ level) 0))))
  17083. ((item plain-list) (org-list-item-body-column post-affiliated))
  17084. (t
  17085. (goto-char start)
  17086. (current-indentation))))
  17087. ((and
  17088. (eq org-adapt-indentation 'headline-data)
  17089. (memq type '(planning clock node-property property-drawer drawer)))
  17090. (org--get-expected-indentation
  17091. (org-element-property :parent element) t))
  17092. ((memq type '(headline inlinetask nil))
  17093. (if (org-match-line "[ \t]*$")
  17094. (org--get-expected-indentation element t)
  17095. 0))
  17096. ((memq type '(diary-sexp footnote-definition)) 0)
  17097. ;; First paragraph of a footnote definition or an item.
  17098. ;; Indent like parent.
  17099. ((< (line-beginning-position) start)
  17100. (org--get-expected-indentation
  17101. (org-element-property :parent element) t))
  17102. ;; At first line: indent according to previous sibling, if any,
  17103. ;; ignoring footnote definitions and inline tasks, or parent's
  17104. ;; contents.
  17105. ((and ( = (line-beginning-position) start)
  17106. (eq org-adapt-indentation t))
  17107. (catch 'exit
  17108. (while t
  17109. (if (= (point-min) start) (throw 'exit 0)
  17110. (goto-char (1- start))
  17111. (let* ((previous (org-element-at-point))
  17112. (parent previous))
  17113. (while (and parent (<= (org-element-property :end parent) start))
  17114. (setq previous parent
  17115. parent (org-element-property :parent parent)))
  17116. (cond
  17117. ((not previous) (throw 'exit 0))
  17118. ((> (org-element-property :end previous) start)
  17119. (throw 'exit (org--get-expected-indentation previous t)))
  17120. ((memq (org-element-type previous)
  17121. '(footnote-definition inlinetask))
  17122. (setq start (org-element-property :begin previous)))
  17123. (t (goto-char (org-element-property :begin previous))
  17124. (throw 'exit
  17125. (if (bolp) (current-indentation)
  17126. ;; At first paragraph in an item or
  17127. ;; a footnote definition.
  17128. (org--get-expected-indentation
  17129. (org-element-property :parent previous) t))))))))))
  17130. ;; Otherwise, move to the first non-blank line above.
  17131. ((not (eq org-adapt-indentation 'headline-data))
  17132. (beginning-of-line)
  17133. (let ((pos (point)))
  17134. (skip-chars-backward " \r\t\n")
  17135. (cond
  17136. ;; Two blank lines end a footnote definition or a plain
  17137. ;; list. When we indent an empty line after them, the
  17138. ;; containing list or footnote definition is over, so it
  17139. ;; qualifies as a previous sibling. Therefore, we indent
  17140. ;; like its first line.
  17141. ((and (memq type '(footnote-definition plain-list))
  17142. (> (count-lines (point) pos) 2))
  17143. (goto-char start)
  17144. (current-indentation))
  17145. ;; Line above is the first one of a paragraph at the
  17146. ;; beginning of an item or a footnote definition. Indent
  17147. ;; like parent.
  17148. ((< (line-beginning-position) start)
  17149. (org--get-expected-indentation
  17150. (org-element-property :parent element) t))
  17151. ;; Line above is the beginning of an element, i.e., point
  17152. ;; was originally on the blank lines between element's start
  17153. ;; and contents.
  17154. ((= (line-beginning-position) post-affiliated)
  17155. (org--get-expected-indentation element t))
  17156. ;; POS is after contents in a greater element. Indent like
  17157. ;; the beginning of the element.
  17158. ((and (memq type org-element-greater-elements)
  17159. (let ((cend (org-element-property :contents-end element)))
  17160. (and cend (<= cend pos))))
  17161. ;; As a special case, if point is at the end of a footnote
  17162. ;; definition or an item, indent like the very last element
  17163. ;; within. If that last element is an item, indent like
  17164. ;; its contents.
  17165. (if (memq type '(footnote-definition item plain-list))
  17166. (let ((last (org-element-at-point)))
  17167. (goto-char pos)
  17168. (org--get-expected-indentation
  17169. last (eq (org-element-type last) 'item)))
  17170. (goto-char start)
  17171. (current-indentation)))
  17172. ;; In any other case, indent like the current line.
  17173. (t (current-indentation)))))
  17174. ;; Finally, no indentation is needed, fall back to 0.
  17175. (t (current-indentation))))))
  17176. (defun org--align-node-property ()
  17177. "Align node property at point.
  17178. Alignment is done according to `org-property-format', which see."
  17179. (when (save-excursion
  17180. (beginning-of-line)
  17181. (looking-at org-property-re))
  17182. (replace-match
  17183. (concat (match-string 4)
  17184. (org-trim
  17185. (format org-property-format (match-string 1) (match-string 3))))
  17186. t t)))
  17187. (defun org-indent-line ()
  17188. "Indent line depending on context.
  17189. Indentation is done according to the following rules:
  17190. - Footnote definitions, diary sexps, headlines and inline tasks
  17191. have to start at column 0.
  17192. - On the very first line of an element, consider, in order, the
  17193. next rules until one matches:
  17194. 1. If there's a sibling element before, ignoring footnote
  17195. definitions and inline tasks, indent like its first line.
  17196. 2. If element has a parent, indent like its contents. More
  17197. precisely, if parent is an item, indent after the bullet.
  17198. Else, indent like parent's first line.
  17199. 3. Otherwise, indent relatively to current level, if
  17200. `org-adapt-indentation' is non-nil, or to left margin.
  17201. - On a blank line at the end of an element, indent according to
  17202. the type of the element. More precisely
  17203. 1. If element is a plain list, an item, or a footnote
  17204. definition, indent like the very last element within.
  17205. 2. If element is a paragraph, indent like its last non blank
  17206. line.
  17207. 3. Otherwise, indent like its very first line.
  17208. - In the code part of a source block, use language major mode
  17209. to indent current line if `org-src-tab-acts-natively' is
  17210. non-nil. If it is nil, do nothing.
  17211. - Otherwise, indent like the first non-blank line above.
  17212. The function doesn't indent an item as it could break the whole
  17213. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  17214. `\\[org-shiftmetaright]'.
  17215. Also align node properties according to `org-property-format'."
  17216. (interactive)
  17217. (if (org-at-heading-p) 'noindent
  17218. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  17219. (type (org-element-type element)))
  17220. (cond ((and (memq type '(plain-list item))
  17221. (= (line-beginning-position)
  17222. (org-element-property :post-affiliated element)))
  17223. 'noindent)
  17224. ((and (eq type 'latex-environment)
  17225. (>= (point) (org-element-property :post-affiliated element))
  17226. (< (point) (org-with-wide-buffer
  17227. (goto-char (org-element-property :end element))
  17228. (skip-chars-backward " \r\t\n")
  17229. (line-beginning-position 2))))
  17230. 'noindent)
  17231. ((and (eq type 'src-block)
  17232. org-src-tab-acts-natively
  17233. (> (line-beginning-position)
  17234. (org-element-property :post-affiliated element))
  17235. (< (line-beginning-position)
  17236. (org-with-wide-buffer
  17237. (goto-char (org-element-property :end element))
  17238. (skip-chars-backward " \r\t\n")
  17239. (line-beginning-position))))
  17240. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  17241. (t
  17242. (let ((column (org--get-expected-indentation element nil)))
  17243. ;; Preserve current column.
  17244. (if (<= (current-column) (current-indentation))
  17245. (indent-line-to column)
  17246. (save-excursion (indent-line-to column))))
  17247. ;; Align node property. Also preserve current column.
  17248. (when (eq type 'node-property)
  17249. (let ((column (current-column)))
  17250. (org--align-node-property)
  17251. (org-move-to-column column))))))))
  17252. (defun org-indent-region (start end)
  17253. "Indent each non-blank line in the region.
  17254. Called from a program, START and END specify the region to
  17255. indent. The function will not indent contents of example blocks,
  17256. verse blocks and export blocks as leading white spaces are
  17257. assumed to be significant there."
  17258. (interactive "r")
  17259. (save-excursion
  17260. (goto-char start)
  17261. (skip-chars-forward " \r\t\n")
  17262. (unless (eobp) (beginning-of-line))
  17263. (let ((indent-to
  17264. (lambda (ind pos)
  17265. ;; Set IND as indentation for all lines between point and
  17266. ;; POS. Blank lines are ignored. Leave point after POS
  17267. ;; once done.
  17268. (let ((limit (copy-marker pos)))
  17269. (while (< (point) limit)
  17270. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  17271. (forward-line))
  17272. (set-marker limit nil))))
  17273. (end (copy-marker end)))
  17274. (while (< (point) end)
  17275. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  17276. (let* ((element (org-element-at-point))
  17277. (type (org-element-type element))
  17278. (element-end (copy-marker (org-element-property :end element)))
  17279. (ind (org--get-expected-indentation element nil)))
  17280. (cond
  17281. ;; Element indented as a single block. Example blocks
  17282. ;; preserving indentation are a special case since the
  17283. ;; "contents" must not be indented whereas the block
  17284. ;; boundaries can.
  17285. ((or (memq type '(export-block latex-environment))
  17286. (and (eq type 'example-block)
  17287. (not
  17288. (or org-src-preserve-indentation
  17289. (org-element-property :preserve-indent element)))))
  17290. (let ((offset (- ind (current-indentation))))
  17291. (unless (zerop offset)
  17292. (indent-rigidly (org-element-property :begin element)
  17293. (org-element-property :end element)
  17294. offset)))
  17295. (goto-char element-end))
  17296. ;; Elements indented line wise. Be sure to exclude
  17297. ;; example blocks (preserving indentation) and source
  17298. ;; blocks from this category as they are treated
  17299. ;; specially later.
  17300. ((or (memq type '(paragraph table table-row))
  17301. (not (or (org-element-property :contents-begin element)
  17302. (memq type '(example-block src-block)))))
  17303. (when (eq type 'node-property)
  17304. (org--align-node-property)
  17305. (beginning-of-line))
  17306. (funcall indent-to ind (min element-end end)))
  17307. ;; Elements consisting of three parts: before the
  17308. ;; contents, the contents, and after the contents. The
  17309. ;; contents are treated specially, according to the
  17310. ;; element type, or not indented at all. Other parts are
  17311. ;; indented as a single block.
  17312. (t
  17313. (let* ((post (copy-marker
  17314. (org-element-property :post-affiliated element)))
  17315. (cbeg
  17316. (copy-marker
  17317. (cond
  17318. ((not (org-element-property :contents-begin element))
  17319. ;; Fake contents for source blocks.
  17320. (org-with-wide-buffer
  17321. (goto-char post)
  17322. (line-beginning-position 2)))
  17323. ((memq type '(footnote-definition item plain-list))
  17324. ;; Contents in these elements could start on
  17325. ;; the same line as the beginning of the
  17326. ;; element. Make sure we start indenting
  17327. ;; from the second line.
  17328. (org-with-wide-buffer
  17329. (goto-char post)
  17330. (end-of-line)
  17331. (skip-chars-forward " \r\t\n")
  17332. (if (eobp) (point) (line-beginning-position))))
  17333. (t (org-element-property :contents-begin element)))))
  17334. (cend (copy-marker
  17335. (or (org-element-property :contents-end element)
  17336. ;; Fake contents for source blocks.
  17337. (org-with-wide-buffer
  17338. (goto-char element-end)
  17339. (skip-chars-backward " \r\t\n")
  17340. (line-beginning-position)))
  17341. t)))
  17342. ;; Do not change items indentation individually as it
  17343. ;; might break the list as a whole. On the other
  17344. ;; hand, when at a plain list, indent it as a whole.
  17345. (cond ((eq type 'plain-list)
  17346. (let ((offset (- ind (current-indentation))))
  17347. (unless (zerop offset)
  17348. (indent-rigidly (org-element-property :begin element)
  17349. (org-element-property :end element)
  17350. offset))
  17351. (goto-char cbeg)))
  17352. ((eq type 'item) (goto-char cbeg))
  17353. (t (funcall indent-to ind (min cbeg end))))
  17354. (when (< (point) end)
  17355. (cl-case type
  17356. ((example-block verse-block))
  17357. (src-block
  17358. ;; In a source block, indent source code
  17359. ;; according to language major mode, but only if
  17360. ;; `org-src-tab-acts-natively' is non-nil.
  17361. (when (and (< (point) end) org-src-tab-acts-natively)
  17362. (ignore-errors
  17363. (org-babel-do-in-edit-buffer
  17364. (indent-region (point-min) (point-max))))))
  17365. (t (org-indent-region (point) (min cend end))))
  17366. (goto-char (min cend end))
  17367. (when (< (point) end)
  17368. (funcall indent-to ind (min element-end end))))
  17369. (set-marker post nil)
  17370. (set-marker cbeg nil)
  17371. (set-marker cend nil))))
  17372. (set-marker element-end nil))))
  17373. (set-marker end nil))))
  17374. (defun org-indent-drawer ()
  17375. "Indent the drawer at point."
  17376. (interactive)
  17377. (unless (save-excursion
  17378. (beginning-of-line)
  17379. (looking-at-p org-drawer-regexp))
  17380. (user-error "Not at a drawer"))
  17381. (let ((element (org-element-at-point)))
  17382. (unless (memq (org-element-type element) '(drawer property-drawer))
  17383. (user-error "Not at a drawer"))
  17384. (org-with-wide-buffer
  17385. (org-indent-region (org-element-property :begin element)
  17386. (org-element-property :end element))))
  17387. (message "Drawer at point indented"))
  17388. (defun org-indent-block ()
  17389. "Indent the block at point."
  17390. (interactive)
  17391. (unless (save-excursion
  17392. (beginning-of-line)
  17393. (let ((case-fold-search t))
  17394. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  17395. (user-error "Not at a block"))
  17396. (let ((element (org-element-at-point)))
  17397. (unless (memq (org-element-type element)
  17398. '(comment-block center-block dynamic-block example-block
  17399. export-block quote-block special-block
  17400. src-block verse-block))
  17401. (user-error "Not at a block"))
  17402. (org-with-wide-buffer
  17403. (org-indent-region (org-element-property :begin element)
  17404. (org-element-property :end element))))
  17405. (message "Block at point indented"))
  17406. ;;; Filling
  17407. ;; We use our own fill-paragraph and auto-fill functions.
  17408. ;; `org-fill-paragraph' relies on adaptive filling and context
  17409. ;; checking. Appropriate `fill-prefix' is computed with
  17410. ;; `org-adaptive-fill-function'.
  17411. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  17412. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  17413. ;; `org-adaptive-fill-function' value. Internally,
  17414. ;; `org-comment-line-break-function' breaks the line.
  17415. ;; `org-setup-filling' installs filling and auto-filling related
  17416. ;; variables during `org-mode' initialization.
  17417. (defun org-setup-filling ()
  17418. (require 'org-element)
  17419. ;; Prevent auto-fill from inserting unwanted new items.
  17420. (when (boundp 'fill-nobreak-predicate)
  17421. (setq-local
  17422. fill-nobreak-predicate
  17423. (org-uniquify
  17424. (append fill-nobreak-predicate
  17425. '(org-fill-line-break-nobreak-p
  17426. org-fill-n-macro-as-item-nobreak-p
  17427. org-fill-paragraph-with-timestamp-nobreak-p)))))
  17428. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  17429. (setq-local paragraph-start paragraph-ending)
  17430. (setq-local paragraph-separate paragraph-ending))
  17431. (setq-local fill-paragraph-function 'org-fill-paragraph)
  17432. (setq-local auto-fill-inhibit-regexp nil)
  17433. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  17434. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  17435. (setq-local comment-line-break-function 'org-comment-line-break-function))
  17436. (defun org-fill-line-break-nobreak-p ()
  17437. "Non-nil when a new line at point would create an Org line break."
  17438. (save-excursion
  17439. (skip-chars-backward " \t")
  17440. (skip-chars-backward "\\\\")
  17441. (looking-at "\\\\\\\\\\($\\|[^\\]\\)")))
  17442. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  17443. "Non-nil when a new line at point would split a timestamp."
  17444. (and (org-at-timestamp-p 'lax)
  17445. (not (looking-at org-ts-regexp-both))))
  17446. (defun org-fill-n-macro-as-item-nobreak-p ()
  17447. "Non-nil when a new line at point would create a new list."
  17448. ;; During export, a "n" macro followed by a dot or a closing
  17449. ;; parenthesis can end up being parsed as a new list item.
  17450. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  17451. (defun org-adaptive-fill-function ()
  17452. "Compute a fill prefix for the current line.
  17453. Return fill prefix, as a string, or nil if current line isn't
  17454. meant to be filled. For convenience, if `adaptive-fill-regexp'
  17455. matches in paragraphs or comments, use it."
  17456. (org-with-wide-buffer
  17457. (unless (org-at-heading-p)
  17458. (let* ((p (line-beginning-position))
  17459. (element (save-excursion
  17460. (beginning-of-line)
  17461. (org-element-at-point)))
  17462. (type (org-element-type element))
  17463. (post-affiliated (org-element-property :post-affiliated element)))
  17464. (unless (< p post-affiliated)
  17465. (cl-case type
  17466. (comment
  17467. (save-excursion
  17468. (beginning-of-line)
  17469. (looking-at "[ \t]*")
  17470. (concat (match-string 0) "# ")))
  17471. (footnote-definition "")
  17472. ((item plain-list)
  17473. (make-string (org-list-item-body-column post-affiliated) ?\s))
  17474. (paragraph
  17475. ;; Fill prefix is usually the same as the current line,
  17476. ;; unless the paragraph is at the beginning of an item.
  17477. (let ((parent (org-element-property :parent element)))
  17478. (save-excursion
  17479. (beginning-of-line)
  17480. (cond ((eq (org-element-type parent) 'item)
  17481. (make-string (org-list-item-body-column
  17482. (org-element-property :begin parent))
  17483. ?\s))
  17484. ((and adaptive-fill-regexp
  17485. ;; Locally disable
  17486. ;; `adaptive-fill-function' to let
  17487. ;; `fill-context-prefix' handle
  17488. ;; `adaptive-fill-regexp' variable.
  17489. (let (adaptive-fill-function)
  17490. (fill-context-prefix
  17491. post-affiliated
  17492. (org-element-property :end element)))))
  17493. ((looking-at "[ \t]+") (match-string 0))
  17494. (t "")))))
  17495. (comment-block
  17496. ;; Only fill contents if P is within block boundaries.
  17497. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  17498. (forward-line)
  17499. (point)))
  17500. (cend (save-excursion
  17501. (goto-char (org-element-property :end element))
  17502. (skip-chars-backward " \r\t\n")
  17503. (line-beginning-position))))
  17504. (when (and (>= p cbeg) (< p cend))
  17505. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  17506. (match-string 0)
  17507. ""))))))))))
  17508. (defun org-fill-element (&optional justify)
  17509. "Fill element at point, when applicable.
  17510. This function only applies to comment blocks, comments, example
  17511. blocks and paragraphs. Also, as a special case, re-align table
  17512. when point is at one.
  17513. If JUSTIFY is non-nil (interactively, with prefix argument),
  17514. justify as well. If `sentence-end-double-space' is non-nil, then
  17515. period followed by one space does not end a sentence, so don't
  17516. break a line there. The variable `fill-column' controls the
  17517. width for filling.
  17518. For convenience, when point is at a plain list, an item or
  17519. a footnote definition, try to fill the first paragraph within."
  17520. (with-syntax-table org-mode-transpose-word-syntax-table
  17521. ;; Move to end of line in order to get the first paragraph within
  17522. ;; a plain list or a footnote definition.
  17523. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  17524. ;; First check if point is in a blank line at the beginning of
  17525. ;; the buffer. In that case, ignore filling.
  17526. (cl-case (org-element-type element)
  17527. ;; Use major mode filling function is source blocks.
  17528. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  17529. ;; Align Org tables, leave table.el tables as-is.
  17530. (table-row (org-table-align) t)
  17531. (table
  17532. (when (eq (org-element-property :type element) 'org)
  17533. (save-excursion
  17534. (goto-char (org-element-property :post-affiliated element))
  17535. (org-table-align)))
  17536. t)
  17537. (paragraph
  17538. ;; Paragraphs may contain `line-break' type objects.
  17539. (let ((beg (max (point-min)
  17540. (org-element-property :contents-begin element)))
  17541. (end (min (point-max)
  17542. (org-element-property :contents-end element))))
  17543. ;; Do nothing if point is at an affiliated keyword.
  17544. (if (< (line-end-position) beg) t
  17545. ;; Fill paragraph, taking line breaks into account.
  17546. (save-excursion
  17547. (goto-char beg)
  17548. (let ((cuts (list beg)))
  17549. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  17550. (when (eq 'line-break
  17551. (org-element-type
  17552. (save-excursion (backward-char)
  17553. (org-element-context))))
  17554. (push (point) cuts)))
  17555. (dolist (c (delq end cuts))
  17556. (fill-region-as-paragraph c end justify)
  17557. (setq end c))))
  17558. t)))
  17559. ;; Contents of `comment-block' type elements should be
  17560. ;; filled as plain text, but only if point is within block
  17561. ;; markers.
  17562. (comment-block
  17563. (let* ((case-fold-search t)
  17564. (beg (save-excursion
  17565. (goto-char (org-element-property :begin element))
  17566. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  17567. (forward-line)
  17568. (point)))
  17569. (end (save-excursion
  17570. (goto-char (org-element-property :end element))
  17571. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  17572. (line-beginning-position))))
  17573. (if (or (< (point) beg) (> (point) end)) t
  17574. (fill-region-as-paragraph
  17575. (save-excursion (end-of-line)
  17576. (re-search-backward "^[ \t]*$" beg 'move)
  17577. (line-beginning-position))
  17578. (save-excursion (beginning-of-line)
  17579. (re-search-forward "^[ \t]*$" end 'move)
  17580. (line-beginning-position))
  17581. justify))))
  17582. ;; Fill comments.
  17583. (comment
  17584. (let ((begin (org-element-property :post-affiliated element))
  17585. (end (org-element-property :end element)))
  17586. (when (and (>= (point) begin) (<= (point) end))
  17587. (let ((begin (save-excursion
  17588. (end-of-line)
  17589. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  17590. (progn (forward-line) (point))
  17591. begin)))
  17592. (end (save-excursion
  17593. (end-of-line)
  17594. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  17595. (1- (line-beginning-position))
  17596. (skip-chars-backward " \r\t\n")
  17597. (line-end-position)))))
  17598. ;; Do not fill comments when at a blank line.
  17599. (when (> end begin)
  17600. (let ((fill-prefix
  17601. (save-excursion
  17602. (beginning-of-line)
  17603. (looking-at "[ \t]*#")
  17604. (let ((comment-prefix (match-string 0)))
  17605. (goto-char (match-end 0))
  17606. (if (looking-at adaptive-fill-regexp)
  17607. (concat comment-prefix (match-string 0))
  17608. (concat comment-prefix " "))))))
  17609. (save-excursion
  17610. (fill-region-as-paragraph begin end justify))))))
  17611. t))
  17612. ;; Ignore every other element.
  17613. (otherwise t)))))
  17614. (defun org-fill-paragraph (&optional justify region)
  17615. "Fill element at point, when applicable.
  17616. This function only applies to comment blocks, comments, example
  17617. blocks and paragraphs. Also, as a special case, re-align table
  17618. when point is at one.
  17619. For convenience, when point is at a plain list, an item or
  17620. a footnote definition, try to fill the first paragraph within.
  17621. If JUSTIFY is non-nil (interactively, with prefix argument),
  17622. justify as well. If `sentence-end-double-space' is non-nil, then
  17623. period followed by one space does not end a sentence, so don't
  17624. break a line there. The variable `fill-column' controls the
  17625. width for filling.
  17626. The REGION argument is non-nil if called interactively; in that
  17627. case, if Transient Mark mode is enabled and the mark is active,
  17628. fill each of the elements in the active region, instead of just
  17629. filling the current element."
  17630. (interactive (progn
  17631. (barf-if-buffer-read-only)
  17632. (list (when current-prefix-arg 'full) t)))
  17633. (let ((hash (and (not (buffer-modified-p))
  17634. (org-buffer-hash))))
  17635. (cond
  17636. ((and region transient-mark-mode mark-active
  17637. (not (eq (region-beginning) (region-end))))
  17638. (let ((origin (point-marker))
  17639. (start (region-beginning)))
  17640. (unwind-protect
  17641. (progn
  17642. (goto-char (region-end))
  17643. (while (> (point) start)
  17644. (org-backward-paragraph)
  17645. (org-fill-element justify)))
  17646. (goto-char origin)
  17647. (set-marker origin nil))))
  17648. (t (org-fill-element justify)))
  17649. ;; If we didn't change anything in the buffer (and the buffer was
  17650. ;; previously unmodified), then flip the modification status back
  17651. ;; to "unchanged".
  17652. (when (and hash (equal hash (org-buffer-hash)))
  17653. (set-buffer-modified-p nil))))
  17654. (defun org-auto-fill-function ()
  17655. "Auto-fill function."
  17656. ;; Check if auto-filling is meaningful.
  17657. (let ((fc (current-fill-column)))
  17658. (when (and fc (> (current-column) fc))
  17659. (let* ((fill-prefix (org-adaptive-fill-function))
  17660. ;; Enforce empty fill prefix, if required. Otherwise, it
  17661. ;; will be computed again.
  17662. (adaptive-fill-mode (not (equal fill-prefix ""))))
  17663. (when fill-prefix (do-auto-fill))))))
  17664. (defun org-comment-line-break-function (&optional soft)
  17665. "Break line at point and indent, continuing comment if within one.
  17666. The inserted newline is marked hard if variable
  17667. `use-hard-newlines' is true, unless optional argument SOFT is
  17668. non-nil."
  17669. (if soft (insert-and-inherit ?\n) (newline 1))
  17670. (save-excursion (forward-char -1) (delete-horizontal-space))
  17671. (delete-horizontal-space)
  17672. (indent-to-left-margin)
  17673. (insert-before-markers-and-inherit fill-prefix))
  17674. ;;; Fixed Width Areas
  17675. (defun org-toggle-fixed-width ()
  17676. "Toggle fixed-width markup.
  17677. Add or remove fixed-width markup on current line, whenever it
  17678. makes sense. Return an error otherwise.
  17679. If a region is active and if it contains only fixed-width areas
  17680. or blank lines, remove all fixed-width markup in it. If the
  17681. region contains anything else, convert all non-fixed-width lines
  17682. to fixed-width ones.
  17683. Blank lines at the end of the region are ignored unless the
  17684. region only contains such lines."
  17685. (interactive)
  17686. (if (not (org-region-active-p))
  17687. ;; No region:
  17688. ;;
  17689. ;; Remove fixed width marker only in a fixed-with element.
  17690. ;;
  17691. ;; Add fixed width maker in paragraphs, in blank lines after
  17692. ;; elements or at the beginning of a headline or an inlinetask,
  17693. ;; and before any one-line elements (e.g., a clock).
  17694. (progn
  17695. (beginning-of-line)
  17696. (let* ((element (org-element-at-point))
  17697. (type (org-element-type element)))
  17698. (cond
  17699. ((and (eq type 'fixed-width)
  17700. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  17701. (replace-match
  17702. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  17703. ((and (memq type '(babel-call clock comment diary-sexp headline
  17704. horizontal-rule keyword paragraph
  17705. planning))
  17706. (<= (org-element-property :post-affiliated element) (point)))
  17707. (skip-chars-forward " \t")
  17708. (insert ": "))
  17709. ((and (looking-at-p "[ \t]*$")
  17710. (or (eq type 'inlinetask)
  17711. (save-excursion
  17712. (skip-chars-forward " \r\t\n")
  17713. (<= (org-element-property :end element) (point)))))
  17714. (delete-region (point) (line-end-position))
  17715. (org-indent-line)
  17716. (insert ": "))
  17717. (t (user-error "Cannot insert a fixed-width line here")))))
  17718. ;; Region active.
  17719. (let* ((begin (save-excursion
  17720. (goto-char (region-beginning))
  17721. (line-beginning-position)))
  17722. (end (copy-marker
  17723. (save-excursion
  17724. (goto-char (region-end))
  17725. (unless (eolp) (beginning-of-line))
  17726. (if (save-excursion (re-search-backward "\\S-" begin t))
  17727. (progn (skip-chars-backward " \r\t\n") (point))
  17728. (point)))))
  17729. (all-fixed-width-p
  17730. (catch 'not-all-p
  17731. (save-excursion
  17732. (goto-char begin)
  17733. (skip-chars-forward " \r\t\n")
  17734. (when (eobp) (throw 'not-all-p nil))
  17735. (while (< (point) end)
  17736. (let ((element (org-element-at-point)))
  17737. (if (eq (org-element-type element) 'fixed-width)
  17738. (goto-char (org-element-property :end element))
  17739. (throw 'not-all-p nil))))
  17740. t))))
  17741. (if all-fixed-width-p
  17742. (save-excursion
  17743. (goto-char begin)
  17744. (while (< (point) end)
  17745. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  17746. (replace-match
  17747. "" nil nil nil
  17748. (if (= (line-end-position) (match-end 0)) 0 1)))
  17749. (forward-line)))
  17750. (let ((min-ind (point-max)))
  17751. ;; Find minimum indentation across all lines.
  17752. (save-excursion
  17753. (goto-char begin)
  17754. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  17755. (setq min-ind 0)
  17756. (catch 'zerop
  17757. (while (< (point) end)
  17758. (unless (looking-at-p "[ \t]*$")
  17759. (let ((ind (current-indentation)))
  17760. (setq min-ind (min min-ind ind))
  17761. (when (zerop ind) (throw 'zerop t))))
  17762. (forward-line)))))
  17763. ;; Loop over all lines and add fixed-width markup everywhere
  17764. ;; but in fixed-width lines.
  17765. (save-excursion
  17766. (goto-char begin)
  17767. (while (< (point) end)
  17768. (cond
  17769. ((org-at-heading-p)
  17770. (insert ": ")
  17771. (forward-line)
  17772. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  17773. (insert ":")
  17774. (forward-line)))
  17775. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  17776. (let* ((element (org-element-at-point))
  17777. (element-end (org-element-property :end element)))
  17778. (if (eq (org-element-type element) 'fixed-width)
  17779. (progn (goto-char element-end)
  17780. (skip-chars-backward " \r\t\n")
  17781. (forward-line))
  17782. (let ((limit (min end element-end)))
  17783. (while (< (point) limit)
  17784. (org-move-to-column min-ind t)
  17785. (insert ": ")
  17786. (forward-line))))))
  17787. (t
  17788. (org-move-to-column min-ind t)
  17789. (insert ": ")
  17790. (forward-line)))))))
  17791. (set-marker end nil))))
  17792. ;;; Blocks
  17793. (defun org-block-map (function &optional start end)
  17794. "Call FUNCTION at the head of all source blocks in the current buffer.
  17795. Optional arguments START and END can be used to limit the range."
  17796. (let ((start (or start (point-min)))
  17797. (end (or end (point-max))))
  17798. (save-excursion
  17799. (goto-char start)
  17800. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  17801. (save-excursion
  17802. (save-match-data
  17803. (goto-char (match-beginning 0))
  17804. (funcall function)))))))
  17805. (defun org-next-block (arg &optional backward block-regexp)
  17806. "Jump to the next block.
  17807. With a prefix argument ARG, jump forward ARG many blocks.
  17808. When BACKWARD is non-nil, jump to the previous block.
  17809. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  17810. Match data is set according to this regexp when the function
  17811. returns.
  17812. Return point at beginning of the opening line of found block.
  17813. Throw an error if no block is found."
  17814. (interactive "p")
  17815. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  17816. (case-fold-search t)
  17817. (search-fn (if backward #'re-search-backward #'re-search-forward))
  17818. (count (or arg 1))
  17819. (origin (point))
  17820. last-element)
  17821. (if backward (beginning-of-line) (end-of-line))
  17822. (while (and (> count 0) (funcall search-fn re nil t))
  17823. (let ((element (save-excursion
  17824. (goto-char (match-beginning 0))
  17825. (save-match-data (org-element-at-point)))))
  17826. (when (and (memq (org-element-type element)
  17827. '(center-block comment-block dynamic-block
  17828. example-block export-block quote-block
  17829. special-block src-block verse-block))
  17830. (<= (match-beginning 0)
  17831. (org-element-property :post-affiliated element)))
  17832. (setq last-element element)
  17833. (cl-decf count))))
  17834. (if (= count 0)
  17835. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  17836. (save-match-data (org-show-context)))
  17837. (goto-char origin)
  17838. (user-error "No %s code blocks" (if backward "previous" "further")))))
  17839. (defun org-previous-block (arg &optional block-regexp)
  17840. "Jump to the previous block.
  17841. With a prefix argument ARG, jump backward ARG many source blocks.
  17842. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  17843. (interactive "p")
  17844. (org-next-block arg t block-regexp))
  17845. ;;; Comments
  17846. ;; Org comments syntax is quite complex. It requires the entire line
  17847. ;; to be just a comment. Also, even with the right syntax at the
  17848. ;; beginning of line, some elements (e.g., verse-block or
  17849. ;; example-block) don't accept comments. Usual Emacs comment commands
  17850. ;; cannot cope with those requirements. Therefore, Org replaces them.
  17851. ;; Org still relies on `comment-dwim', but cannot trust
  17852. ;; `comment-only-p'. So, `comment-region-function' and
  17853. ;; `uncomment-region-function' both point
  17854. ;; to`org-comment-or-uncomment-region'. Eventually,
  17855. ;; `org-insert-comment' takes care of insertion of comments at the
  17856. ;; beginning of line.
  17857. ;; `org-setup-comments-handling' install comments related variables
  17858. ;; during `org-mode' initialization.
  17859. (defun org-setup-comments-handling ()
  17860. (interactive)
  17861. (setq-local comment-use-syntax nil)
  17862. (setq-local comment-start "# ")
  17863. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  17864. (setq-local comment-insert-comment-function 'org-insert-comment)
  17865. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  17866. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  17867. (defun org-insert-comment ()
  17868. "Insert an empty comment above current line.
  17869. If the line is empty, insert comment at its beginning. When
  17870. point is within a source block, comment according to the related
  17871. major mode."
  17872. (if (let ((element (org-element-at-point)))
  17873. (and (eq (org-element-type element) 'src-block)
  17874. (< (save-excursion
  17875. (goto-char (org-element-property :post-affiliated element))
  17876. (line-end-position))
  17877. (point))
  17878. (> (save-excursion
  17879. (goto-char (org-element-property :end element))
  17880. (skip-chars-backward " \r\t\n")
  17881. (line-beginning-position))
  17882. (point))))
  17883. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  17884. (beginning-of-line)
  17885. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  17886. (open-line 1))
  17887. (org-indent-line)
  17888. (insert "# ")))
  17889. (defvar comment-empty-lines) ; From newcomment.el.
  17890. (defun org-comment-or-uncomment-region (beg end &rest _)
  17891. "Comment or uncomment each non-blank line in the region.
  17892. Uncomment each non-blank line between BEG and END if it only
  17893. contains commented lines. Otherwise, comment them. If region is
  17894. strictly within a source block, use appropriate comment syntax."
  17895. (if (let ((element (org-element-at-point)))
  17896. (and (eq (org-element-type element) 'src-block)
  17897. (< (save-excursion
  17898. (goto-char (org-element-property :post-affiliated element))
  17899. (line-end-position))
  17900. beg)
  17901. (>= (save-excursion
  17902. (goto-char (org-element-property :end element))
  17903. (skip-chars-backward " \r\t\n")
  17904. (line-beginning-position))
  17905. end)))
  17906. ;; Translate region boundaries for the Org buffer to the source
  17907. ;; buffer.
  17908. (let ((offset (- end beg)))
  17909. (save-excursion
  17910. (goto-char beg)
  17911. (org-babel-do-in-edit-buffer
  17912. (comment-or-uncomment-region (point) (+ offset (point))))))
  17913. (save-restriction
  17914. ;; Restrict region
  17915. (narrow-to-region (save-excursion (goto-char beg)
  17916. (skip-chars-forward " \r\t\n" end)
  17917. (line-beginning-position))
  17918. (save-excursion (goto-char end)
  17919. (skip-chars-backward " \r\t\n" beg)
  17920. (line-end-position)))
  17921. (let ((uncommentp
  17922. ;; UNCOMMENTP is non-nil when every non blank line between
  17923. ;; BEG and END is a comment.
  17924. (save-excursion
  17925. (goto-char (point-min))
  17926. (while (and (not (eobp))
  17927. (let ((element (org-element-at-point)))
  17928. (and (eq (org-element-type element) 'comment)
  17929. (goto-char (min (point-max)
  17930. (org-element-property
  17931. :end element)))))))
  17932. (eobp))))
  17933. (if uncommentp
  17934. ;; Only blank lines and comments in region: uncomment it.
  17935. (save-excursion
  17936. (goto-char (point-min))
  17937. (while (not (eobp))
  17938. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  17939. (replace-match "" nil nil nil 1))
  17940. (forward-line)))
  17941. ;; Comment each line in region.
  17942. (let ((min-indent (point-max)))
  17943. ;; First find the minimum indentation across all lines.
  17944. (save-excursion
  17945. (goto-char (point-min))
  17946. (while (and (not (eobp)) (not (zerop min-indent)))
  17947. (unless (looking-at "[ \t]*$")
  17948. (setq min-indent (min min-indent (current-indentation))))
  17949. (forward-line)))
  17950. ;; Then loop over all lines.
  17951. (save-excursion
  17952. (goto-char (point-min))
  17953. (while (not (eobp))
  17954. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  17955. ;; Don't get fooled by invisible text (e.g. link path)
  17956. ;; when moving to column MIN-INDENT.
  17957. (let ((buffer-invisibility-spec nil))
  17958. (org-move-to-column min-indent t))
  17959. (insert comment-start))
  17960. (forward-line)))))))))
  17961. (defun org-comment-dwim (_arg)
  17962. "Call the comment command you mean.
  17963. Call `org-toggle-comment' if on a heading, otherwise call
  17964. `comment-dwim', within a source edit buffer if needed."
  17965. (interactive "*P")
  17966. (cond ((org-at-heading-p)
  17967. (call-interactively #'org-toggle-comment))
  17968. ((org-in-src-block-p)
  17969. (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
  17970. (t (call-interactively #'comment-dwim))))
  17971. ;;; Timestamps API
  17972. ;; This section contains tools to operate on, or create, timestamp
  17973. ;; objects, as returned by, e.g. `org-element-context'.
  17974. (defun org-timestamp-from-string (s)
  17975. "Convert Org timestamp S, as a string, into a timestamp object.
  17976. Return nil if S is not a valid timestamp string."
  17977. (when (org-string-nw-p s)
  17978. (with-temp-buffer
  17979. (save-excursion (insert s))
  17980. (org-element-timestamp-parser))))
  17981. (defun org-timestamp-from-time (time &optional with-time inactive)
  17982. "Convert a time value into a timestamp object.
  17983. TIME is an Emacs internal time representation, as returned, e.g.,
  17984. by `current-time'.
  17985. When optional argument WITH-TIME is non-nil, return a timestamp
  17986. object with a time part, i.e., with hours and minutes.
  17987. Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
  17988. return an active timestamp."
  17989. (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
  17990. (org-element-create 'timestamp
  17991. (list :type (if inactive 'inactive 'active)
  17992. :year-start year
  17993. :month-start month
  17994. :day-start day
  17995. :hour-start (and with-time hour)
  17996. :minute-start (and with-time minute)))))
  17997. (defun org-timestamp-to-time (timestamp &optional end)
  17998. "Convert TIMESTAMP object into an Emacs internal time value.
  17999. Use end of date range or time range when END is non-nil.
  18000. Otherwise, use its start."
  18001. (apply #'encode-time 0
  18002. (mapcar
  18003. (lambda (prop) (or (org-element-property prop timestamp) 0))
  18004. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  18005. '(:minute-start :hour-start :day-start :month-start
  18006. :year-start)))))
  18007. (defun org-timestamp-has-time-p (timestamp)
  18008. "Non-nil when TIMESTAMP has a time specified."
  18009. (org-element-property :hour-start timestamp))
  18010. (defun org-timestamp-format (timestamp format &optional end utc)
  18011. "Format a TIMESTAMP object into a string.
  18012. FORMAT is a format specifier to be passed to
  18013. `format-time-string'.
  18014. When optional argument END is non-nil, use end of date-range or
  18015. time-range, if possible.
  18016. When optional argument UTC is non-nil, time is be expressed as
  18017. Universal Time."
  18018. (format-time-string format (org-timestamp-to-time timestamp end)
  18019. (and utc t)))
  18020. (defun org-timestamp-split-range (timestamp &optional end)
  18021. "Extract a TIMESTAMP object from a date or time range.
  18022. END, when non-nil, means extract the end of the range.
  18023. Otherwise, extract its start.
  18024. Return a new timestamp object."
  18025. (let ((type (org-element-property :type timestamp)))
  18026. (if (memq type '(active inactive diary)) timestamp
  18027. (let ((split-ts (org-element-copy timestamp)))
  18028. ;; Set new type.
  18029. (org-element-put-property
  18030. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  18031. ;; Copy start properties over end properties if END is
  18032. ;; non-nil. Otherwise, copy end properties over `start' ones.
  18033. (let ((p-alist '((:minute-start . :minute-end)
  18034. (:hour-start . :hour-end)
  18035. (:day-start . :day-end)
  18036. (:month-start . :month-end)
  18037. (:year-start . :year-end))))
  18038. (dolist (p-cell p-alist)
  18039. (org-element-put-property
  18040. split-ts
  18041. (funcall (if end #'car #'cdr) p-cell)
  18042. (org-element-property
  18043. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  18044. ;; Eventually refresh `:raw-value'.
  18045. (org-element-put-property split-ts :raw-value nil)
  18046. (org-element-put-property
  18047. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  18048. (defun org-timestamp-translate (timestamp &optional boundary)
  18049. "Translate TIMESTAMP object to custom format.
  18050. Format string is defined in `org-time-stamp-custom-formats',
  18051. which see.
  18052. When optional argument BOUNDARY is non-nil, it is either the
  18053. symbol `start' or `end'. In this case, only translate the
  18054. starting or ending part of TIMESTAMP if it is a date or time
  18055. range. Otherwise, translate both parts.
  18056. Return timestamp as-is if `org-display-custom-times' is nil or if
  18057. it has a `diary' type."
  18058. (let ((type (org-element-property :type timestamp)))
  18059. (if (or (not org-display-custom-times) (eq type 'diary))
  18060. (org-element-interpret-data timestamp)
  18061. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  18062. org-time-stamp-custom-formats)))
  18063. (if (and (not boundary) (memq type '(active-range inactive-range)))
  18064. (concat (org-timestamp-format timestamp fmt)
  18065. "--"
  18066. (org-timestamp-format timestamp fmt t))
  18067. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  18068. ;;; Other stuff
  18069. (defvar reftex-docstruct-symbol)
  18070. (defvar org--rds)
  18071. (defun org-reftex-citation ()
  18072. "Use reftex-citation to insert a citation into the buffer.
  18073. This looks for a line like
  18074. #+BIBLIOGRAPHY: foo plain option:-d
  18075. and derives from it that foo.bib is the bibliography file relevant
  18076. for this document. It then installs the necessary environment for RefTeX
  18077. to work in this buffer and calls `reftex-citation' to insert a citation
  18078. into the buffer.
  18079. Export of such citations to both LaTeX and HTML is handled by the contributed
  18080. package ox-bibtex by Taru Karttunen."
  18081. (interactive)
  18082. (let ((reftex-docstruct-symbol 'org--rds)
  18083. org--rds bib)
  18084. (org-with-wide-buffer
  18085. (let ((case-fold-search t)
  18086. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  18087. (if (not (save-excursion
  18088. (or (re-search-forward re nil t)
  18089. (re-search-backward re nil t))))
  18090. (user-error "No bibliography defined in file")
  18091. (setq bib (concat (match-string 1) ".bib")
  18092. org--rds (list (list 'bib bib))))))
  18093. (call-interactively 'reftex-citation)))
  18094. ;;;; Functions extending outline functionality
  18095. (defun org-beginning-of-line (&optional n)
  18096. "Go to the beginning of the current visible line.
  18097. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18098. symbol `reversed', on the first attempt move to where the
  18099. headline text starts, and only move to beginning of line when the
  18100. cursor is already before the start of the text of the headline.
  18101. If `org-special-ctrl-a/e' is symbol `reversed' then go to the
  18102. start of the text on the second attempt.
  18103. With argument N not nil or 1, move forward N - 1 lines first."
  18104. (interactive "^p")
  18105. (let ((origin (point))
  18106. (special (pcase org-special-ctrl-a/e
  18107. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  18108. deactivate-mark)
  18109. ;; First move to a visible line.
  18110. (if (bound-and-true-p visual-line-mode)
  18111. (beginning-of-visual-line n)
  18112. (move-beginning-of-line n)
  18113. ;; `move-beginning-of-line' may leave point after invisible
  18114. ;; characters if line starts with such of these (e.g., with
  18115. ;; a link at column 0). Really move to the beginning of the
  18116. ;; current visible line.
  18117. (beginning-of-line))
  18118. (cond
  18119. ;; No special behavior. Point is already at the beginning of
  18120. ;; a line, logical or visual.
  18121. ((not special))
  18122. ;; `beginning-of-visual-line' left point before logical beginning
  18123. ;; of line: point is at the beginning of a visual line. Bail
  18124. ;; out.
  18125. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  18126. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  18127. ;; At a headline, special position is before the title, but
  18128. ;; after any TODO keyword or priority cookie.
  18129. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  18130. (line-end-position)))
  18131. (bol (point)))
  18132. (if (eq special 'reversed)
  18133. (when (and (= origin bol) (eq last-command this-command))
  18134. (goto-char refpos))
  18135. (when (or (> origin refpos) (= origin bol))
  18136. (goto-char refpos)))))
  18137. ((and (looking-at org-list-full-item-re)
  18138. (memq (org-element-type (save-match-data (org-element-at-point)))
  18139. '(item plain-list)))
  18140. ;; Set special position at first white space character after
  18141. ;; bullet, and check-box, if any.
  18142. (let ((after-bullet
  18143. (let ((box (match-end 3)))
  18144. (cond ((not box) (match-end 1))
  18145. ((eq (char-after box) ?\s) (1+ box))
  18146. (t box)))))
  18147. (if (eq special 'reversed)
  18148. (when (and (= (point) origin) (eq last-command this-command))
  18149. (goto-char after-bullet))
  18150. (when (or (> origin after-bullet) (= (point) origin))
  18151. (goto-char after-bullet)))))
  18152. ;; No special context. Point is already at beginning of line.
  18153. (t nil))))
  18154. (defun org-end-of-line (&optional n)
  18155. "Go to the end of the line, but before ellipsis, if any.
  18156. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18157. symbol `reversed', ignore tags on the first attempt, and only
  18158. move to after the tags when the cursor is already beyond the end
  18159. of the headline.
  18160. If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
  18161. on the second attempt.
  18162. With argument N not nil or 1, move forward N - 1 lines first."
  18163. (interactive "^p")
  18164. (let ((origin (point))
  18165. (special (pcase org-special-ctrl-a/e
  18166. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  18167. deactivate-mark)
  18168. ;; First move to a visible line.
  18169. (if (bound-and-true-p visual-line-mode)
  18170. (beginning-of-visual-line n)
  18171. (move-beginning-of-line n))
  18172. (cond
  18173. ;; At a headline, with tags.
  18174. ((and special
  18175. (save-excursion
  18176. (beginning-of-line)
  18177. (let ((case-fold-search nil))
  18178. (looking-at org-complex-heading-regexp)))
  18179. (match-end 5))
  18180. (let ((tags (save-excursion
  18181. (goto-char (match-beginning 5))
  18182. (skip-chars-backward " \t")
  18183. (point)))
  18184. (visual-end (and (bound-and-true-p visual-line-mode)
  18185. (save-excursion
  18186. (end-of-visual-line)
  18187. (point)))))
  18188. ;; If `end-of-visual-line' brings us before end of line or
  18189. ;; even tags, i.e., the headline spans over multiple visual
  18190. ;; lines, move there.
  18191. (cond ((and visual-end
  18192. (< visual-end tags)
  18193. (<= origin visual-end))
  18194. (goto-char visual-end))
  18195. ((eq special 'reversed)
  18196. (if (and (= origin (line-end-position))
  18197. (eq this-command last-command))
  18198. (goto-char tags)
  18199. (end-of-line)))
  18200. (t
  18201. (if (or (< origin tags) (= origin (line-end-position)))
  18202. (goto-char tags)
  18203. (end-of-line))))))
  18204. ((bound-and-true-p visual-line-mode)
  18205. (let ((bol (line-beginning-position)))
  18206. (end-of-visual-line)
  18207. ;; If `end-of-visual-line' gets us past the ellipsis at the
  18208. ;; end of a line, backtrack and use `end-of-line' instead.
  18209. (when (/= bol (line-beginning-position))
  18210. (goto-char bol)
  18211. (end-of-line))))
  18212. (t (end-of-line)))))
  18213. (defun org-backward-sentence (&optional _arg)
  18214. "Go to beginning of sentence, or beginning of table field.
  18215. This will call `backward-sentence' or `org-table-beginning-of-field',
  18216. depending on context."
  18217. (interactive)
  18218. (let* ((element (org-element-at-point))
  18219. (contents-begin (org-element-property :contents-begin element))
  18220. (table (org-element-lineage element '(table) t)))
  18221. (if (and table
  18222. (> (point) contents-begin)
  18223. (<= (point) (org-element-property :contents-end table)))
  18224. (call-interactively #'org-table-beginning-of-field)
  18225. (save-restriction
  18226. (when (and contents-begin
  18227. (< (point-min) contents-begin)
  18228. (> (point) contents-begin))
  18229. (narrow-to-region contents-begin
  18230. (org-element-property :contents-end element)))
  18231. (call-interactively #'backward-sentence)))))
  18232. (defun org-forward-sentence (&optional _arg)
  18233. "Go to end of sentence, or end of table field.
  18234. This will call `forward-sentence' or `org-table-end-of-field',
  18235. depending on context."
  18236. (interactive)
  18237. (if (and (org-at-heading-p)
  18238. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  18239. (save-restriction
  18240. (narrow-to-region (line-beginning-position) (line-end-position))
  18241. (call-interactively #'forward-sentence))
  18242. (let* ((element (org-element-at-point))
  18243. (contents-end (org-element-property :contents-end element))
  18244. (table (org-element-lineage element '(table) t)))
  18245. (if (and table
  18246. (>= (point) (org-element-property :contents-begin table))
  18247. (< (point) contents-end))
  18248. (call-interactively #'org-table-end-of-field)
  18249. (save-restriction
  18250. (when (and contents-end
  18251. (> (point-max) contents-end)
  18252. ;; Skip blank lines between elements.
  18253. (< (org-element-property :end element)
  18254. (save-excursion (goto-char contents-end)
  18255. (skip-chars-forward " \r\t\n"))))
  18256. (narrow-to-region (org-element-property :contents-begin element)
  18257. contents-end))
  18258. ;; End of heading is considered as the end of a sentence.
  18259. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  18260. (call-interactively #'forward-sentence)))))))
  18261. (defun org-kill-line (&optional _arg)
  18262. "Kill line, to tags or end of line."
  18263. (interactive)
  18264. (cond
  18265. ((or (not org-special-ctrl-k)
  18266. (bolp)
  18267. (not (org-at-heading-p)))
  18268. (when (and (get-char-property (line-end-position) 'invisible)
  18269. org-ctrl-k-protect-subtree
  18270. (or (eq org-ctrl-k-protect-subtree 'error)
  18271. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  18272. (user-error
  18273. (substitute-command-keys
  18274. "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
  18275. (call-interactively
  18276. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  18277. ((org-match-line org-tag-line-re)
  18278. (let ((end (save-excursion
  18279. (goto-char (match-beginning 1))
  18280. (skip-chars-backward " \t")
  18281. (point))))
  18282. (if (<= end (point)) ;on tags part
  18283. (kill-region (point) (line-end-position))
  18284. (kill-region (point) end)))
  18285. ;; Only align tags when we are still on a heading:
  18286. (if (org-at-heading-p) (org-align-tags)))
  18287. (t (kill-region (point) (line-end-position)))))
  18288. (defun org-yank (&optional arg)
  18289. "Yank. If the kill is a subtree, treat it specially.
  18290. This command will look at the current kill and check if is a single
  18291. subtree, or a series of subtrees[1]. If it passes the test, and if the
  18292. cursor is at the beginning of a line or after the stars of a currently
  18293. empty headline, then the yank is handled specially. How exactly depends
  18294. on the value of the following variables.
  18295. `org-yank-folded-subtrees'
  18296. By default, this variable is non-nil, which results in
  18297. subtree(s) being folded after insertion, except if doing so
  18298. would swallow text after the yanked text.
  18299. `org-yank-adjusted-subtrees'
  18300. When non-nil (the default value is nil), the subtree will be
  18301. promoted or demoted in order to fit into the local outline tree
  18302. structure, which means that the level will be adjusted so that it
  18303. becomes the smaller one of the two *visible* surrounding headings.
  18304. Any prefix to this command will cause `yank' to be called directly with
  18305. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  18306. will just
  18307. plainly yank the text as it is.
  18308. \[1] The test checks if the first non-white line is a heading
  18309. and if there are no other headings with fewer stars."
  18310. (interactive "P")
  18311. (org-yank-generic 'yank arg))
  18312. (defun org-yank-generic (command arg)
  18313. "Perform some yank-like command.
  18314. This function implements the behavior described in the `org-yank'
  18315. documentation. However, it has been generalized to work for any
  18316. interactive command with similar behavior."
  18317. ;; pretend to be command COMMAND
  18318. (setq this-command command)
  18319. (if arg
  18320. (call-interactively command)
  18321. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  18322. (and (org-kill-is-subtree-p)
  18323. (or (bolp)
  18324. (and (looking-at "[ \t]*$")
  18325. (string-match
  18326. "\\`\\*+\\'"
  18327. (buffer-substring (point-at-bol) (point)))))))
  18328. swallowp)
  18329. (cond
  18330. ((and subtreep org-yank-folded-subtrees)
  18331. (let ((beg (point))
  18332. end)
  18333. (if (and subtreep org-yank-adjusted-subtrees)
  18334. (org-paste-subtree nil nil 'for-yank)
  18335. (call-interactively command))
  18336. (setq end (point))
  18337. (goto-char beg)
  18338. (when (and (bolp) subtreep
  18339. (not (setq swallowp
  18340. (org-yank-folding-would-swallow-text beg end))))
  18341. (org-with-limited-levels
  18342. (or (looking-at org-outline-regexp)
  18343. (re-search-forward org-outline-regexp-bol end t))
  18344. (while (and (< (point) end) (looking-at org-outline-regexp))
  18345. (org-flag-subtree t)
  18346. (org-cycle-show-empty-lines 'folded)
  18347. (condition-case nil
  18348. (outline-forward-same-level 1)
  18349. (error (goto-char end))))))
  18350. (when swallowp
  18351. (message
  18352. "Inserted text not folded because that would swallow text"))
  18353. (goto-char end)
  18354. (skip-chars-forward " \t\n\r")
  18355. (beginning-of-line 1)
  18356. (push-mark beg 'nomsg)))
  18357. ((and subtreep org-yank-adjusted-subtrees)
  18358. (let ((beg (point-at-bol)))
  18359. (org-paste-subtree nil nil 'for-yank)
  18360. (push-mark beg 'nomsg)))
  18361. (t
  18362. (call-interactively command))))))
  18363. (defun org-yank-folding-would-swallow-text (beg end)
  18364. "Would hide-subtree at BEG swallow any text after END?"
  18365. (let (level)
  18366. (org-with-limited-levels
  18367. (save-excursion
  18368. (goto-char beg)
  18369. (when (or (looking-at org-outline-regexp)
  18370. (re-search-forward org-outline-regexp-bol end t))
  18371. (setq level (org-outline-level)))
  18372. (goto-char end)
  18373. (skip-chars-forward " \t\r\n\v\f")
  18374. (not (or (eobp)
  18375. (and (bolp) (looking-at-p org-outline-regexp)
  18376. (<= (org-outline-level) level))))))))
  18377. (defun org-back-to-heading (&optional invisible-ok)
  18378. "Call `outline-back-to-heading', but provide a better error message."
  18379. (condition-case nil
  18380. (outline-back-to-heading invisible-ok)
  18381. (error
  18382. (user-error "Before first headline at position %d in buffer %s"
  18383. (point) (current-buffer)))))
  18384. (defun org-back-to-heading-or-point-min (&optional invisible-ok)
  18385. "Go back to heading or first point in buffer.
  18386. If point is before first heading go to first point in buffer
  18387. instead of back to heading."
  18388. (condition-case nil
  18389. (outline-back-to-heading invisible-ok)
  18390. (error
  18391. (goto-char (point-min)))))
  18392. (defun org-before-first-heading-p ()
  18393. "Before first heading?"
  18394. (org-with-limited-levels
  18395. (save-excursion
  18396. (end-of-line)
  18397. (null (re-search-backward org-outline-regexp-bol nil t)))))
  18398. (defun org-at-heading-p (&optional _)
  18399. "Non-nil when on a headline."
  18400. (outline-on-heading-p t))
  18401. (defun org-in-commented-heading-p (&optional no-inheritance)
  18402. "Non-nil if point is under a commented heading.
  18403. This function also checks ancestors of the current headline,
  18404. unless optional argument NO-INHERITANCE is non-nil."
  18405. (cond
  18406. ((org-before-first-heading-p) nil)
  18407. ((let ((headline (nth 4 (org-heading-components))))
  18408. (and headline
  18409. (let ((case-fold-search nil))
  18410. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  18411. headline)))))
  18412. (no-inheritance nil)
  18413. (t
  18414. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  18415. (defun org-at-comment-p nil
  18416. "Return t if cursor is in a commented line."
  18417. (save-excursion
  18418. (save-match-data
  18419. (beginning-of-line)
  18420. (looking-at "^[ \t]*# "))))
  18421. (defun org-at-keyword-p nil
  18422. "Return t if cursor is at a keyword-line."
  18423. (save-excursion
  18424. (move-beginning-of-line 1)
  18425. (looking-at org-keyword-regexp)))
  18426. (defun org-at-drawer-p nil
  18427. "Return t if cursor is at a drawer keyword."
  18428. (save-excursion
  18429. (move-beginning-of-line 1)
  18430. (looking-at org-drawer-regexp)))
  18431. (defun org-at-block-p nil
  18432. "Return t if cursor is at a block keyword."
  18433. (save-excursion
  18434. (move-beginning-of-line 1)
  18435. (looking-at org-block-regexp)))
  18436. (defun org-point-at-end-of-empty-headline ()
  18437. "If point is at the end of an empty headline, return t, else nil.
  18438. If the heading only contains a TODO keyword, it is still still considered
  18439. empty."
  18440. (let ((case-fold-search nil))
  18441. (and (looking-at "[ \t]*$")
  18442. org-todo-line-regexp
  18443. (save-excursion
  18444. (beginning-of-line)
  18445. (looking-at org-todo-line-regexp)
  18446. (string= (match-string 3) "")))))
  18447. (defun org-at-heading-or-item-p ()
  18448. (or (org-at-heading-p) (org-at-item-p)))
  18449. (defun org-up-heading-all (arg)
  18450. "Move to the heading line of which the present line is a subheading.
  18451. This function considers both visible and invisible heading lines.
  18452. With argument, move up ARG levels."
  18453. (outline-up-heading arg t))
  18454. (defun org-up-heading-safe ()
  18455. "Move to the heading line of which the present line is a subheading.
  18456. This version will not throw an error. It will return the level of the
  18457. headline found, or nil if no higher level is found.
  18458. Also, this function will be a lot faster than `outline-up-heading',
  18459. because it relies on stars being the outline starters. This can really
  18460. make a significant difference in outlines with very many siblings."
  18461. (when (ignore-errors (org-back-to-heading t))
  18462. (let ((level-up (1- (funcall outline-level))))
  18463. (and (> level-up 0)
  18464. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  18465. (funcall outline-level)))))
  18466. (defun org-up-heading-or-point-min ()
  18467. "Move to the heading line of which the present is a subheading, or point-min.
  18468. This version is needed to make point-min behave like a virtual
  18469. heading of level 0 for property-inheritance. It will return the
  18470. level of the headline found (down to 0) or nil if already at a
  18471. point before the first headline or at point-min."
  18472. (when (ignore-errors (org-back-to-heading t))
  18473. (if (< 1 (funcall outline-level))
  18474. (org-up-heading-safe)
  18475. (unless (= (point) (point-min)) (goto-char (point-min))))))
  18476. (defun org-first-sibling-p ()
  18477. "Is this heading the first child of its parents?"
  18478. (interactive)
  18479. (let ((re org-outline-regexp-bol)
  18480. level l)
  18481. (unless (org-at-heading-p t)
  18482. (user-error "Not at a heading"))
  18483. (setq level (funcall outline-level))
  18484. (save-excursion
  18485. (if (not (re-search-backward re nil t))
  18486. t
  18487. (setq l (funcall outline-level))
  18488. (< l level)))))
  18489. (defun org-goto-sibling (&optional previous)
  18490. "Goto the next sibling, even if it is invisible.
  18491. When PREVIOUS is set, go to the previous sibling instead. Returns t
  18492. when a sibling was found. When none is found, return nil and don't
  18493. move point."
  18494. (let ((fun (if previous 're-search-backward 're-search-forward))
  18495. (pos (point))
  18496. (re org-outline-regexp-bol)
  18497. level l)
  18498. (when (ignore-errors (org-back-to-heading t))
  18499. (setq level (funcall outline-level))
  18500. (catch 'exit
  18501. (or previous (forward-char 1))
  18502. (while (funcall fun re nil t)
  18503. (setq l (funcall outline-level))
  18504. (when (< l level) (goto-char pos) (throw 'exit nil))
  18505. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  18506. (goto-char pos)
  18507. nil))))
  18508. (defun org-show-siblings ()
  18509. "Show all siblings of the current headline."
  18510. (save-excursion
  18511. (while (org-goto-sibling) (org-flag-heading nil)))
  18512. (save-excursion
  18513. (while (org-goto-sibling 'previous)
  18514. (org-flag-heading nil))))
  18515. (defun org-goto-first-child ()
  18516. "Goto the first child, even if it is invisible.
  18517. Return t when a child was found. Otherwise don't move point and
  18518. return nil."
  18519. (let (level (pos (point)) (re org-outline-regexp-bol))
  18520. (when (ignore-errors (org-back-to-heading t))
  18521. (setq level (outline-level))
  18522. (forward-char 1)
  18523. (if (and (re-search-forward re nil t) (> (outline-level) level))
  18524. (progn (goto-char (match-beginning 0)) t)
  18525. (goto-char pos) nil))))
  18526. (defun org-show-hidden-entry ()
  18527. "Show an entry where even the heading is hidden."
  18528. (save-excursion
  18529. (org-show-entry)))
  18530. (defun org-flag-heading (flag &optional entry)
  18531. "Flag the current heading. FLAG non-nil means make invisible.
  18532. When ENTRY is non-nil, show the entire entry."
  18533. (save-excursion
  18534. (org-back-to-heading t)
  18535. ;; Check if we should show the entire entry
  18536. (if (not entry)
  18537. (org-flag-region
  18538. (line-end-position 0) (line-end-position) flag 'outline)
  18539. (org-show-entry)
  18540. (save-excursion
  18541. (and (outline-next-heading)
  18542. (org-flag-heading nil))))))
  18543. (defun org-get-next-sibling ()
  18544. "Move to next heading of the same level, and return point.
  18545. If there is no such heading, return nil.
  18546. This is like outline-next-sibling, but invisible headings are ok."
  18547. (let ((level (funcall outline-level)))
  18548. (outline-next-heading)
  18549. (while (and (not (eobp)) (> (funcall outline-level) level))
  18550. (outline-next-heading))
  18551. (unless (or (eobp) (< (funcall outline-level) level))
  18552. (point))))
  18553. (defun org-get-last-sibling ()
  18554. "Move to previous heading of the same level, and return point.
  18555. If there is no such heading, return nil."
  18556. (let ((opoint (point))
  18557. (level (funcall outline-level)))
  18558. (outline-previous-heading)
  18559. (when (and (/= (point) opoint) (outline-on-heading-p t))
  18560. (while (and (> (funcall outline-level) level)
  18561. (not (bobp)))
  18562. (outline-previous-heading))
  18563. (unless (< (funcall outline-level) level)
  18564. (point)))))
  18565. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  18566. "Goto to the end of a subtree."
  18567. ;; This contains an exact copy of the original function, but it uses
  18568. ;; `org-back-to-heading-or-point-min', to make it work also in invisible
  18569. ;; trees and before first headline. And is uses an invisible-ok argument.
  18570. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  18571. ;; Furthermore, when used inside Org, finding the end of a large subtree
  18572. ;; with many children and grandchildren etc, this can be much faster
  18573. ;; than the outline version.
  18574. (org-back-to-heading-or-point-min invisible-ok)
  18575. (let ((first t)
  18576. (level (funcall outline-level)))
  18577. (cond ((= level 0)
  18578. (goto-char (point-max)))
  18579. ((and (derived-mode-p 'org-mode) (< level 1000))
  18580. ;; A true heading (not a plain list item), in Org
  18581. ;; This means we can easily find the end by looking
  18582. ;; only for the right number of stars. Using a regexp to do
  18583. ;; this is so much faster than using a Lisp loop.
  18584. (let ((re (concat "^\\*\\{1," (number-to-string level) "\\} ")))
  18585. (forward-char 1)
  18586. (and (re-search-forward re nil 'move) (beginning-of-line 1))))
  18587. (t
  18588. ;; something else, do it the slow way
  18589. (while (and (not (eobp))
  18590. (or first (> (funcall outline-level) level)))
  18591. (setq first nil)
  18592. (outline-next-heading))))
  18593. (unless to-heading
  18594. (when (memq (preceding-char) '(?\n ?\^M))
  18595. ;; Go to end of line before heading
  18596. (forward-char -1)
  18597. (when (memq (preceding-char) '(?\n ?\^M))
  18598. ;; leave blank line before heading
  18599. (forward-char -1)))))
  18600. (point))
  18601. (defun org-end-of-meta-data (&optional full)
  18602. "Skip planning line and properties drawer in current entry.
  18603. When optional argument FULL is non-nil, also skip empty lines,
  18604. clocking lines and regular drawers at the beginning of the
  18605. entry."
  18606. (org-back-to-heading t)
  18607. (forward-line)
  18608. (when (looking-at-p org-planning-line-re) (forward-line))
  18609. (when (looking-at org-property-drawer-re)
  18610. (goto-char (match-end 0))
  18611. (forward-line))
  18612. (when (and full (not (org-at-heading-p)))
  18613. (catch 'exit
  18614. (let ((end (save-excursion (outline-next-heading) (point)))
  18615. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  18616. (while (not (eobp))
  18617. (cond ((looking-at-p org-drawer-regexp)
  18618. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  18619. (forward-line)
  18620. (throw 'exit t)))
  18621. ((looking-at-p re) (forward-line))
  18622. (t (throw 'exit t))))))))
  18623. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  18624. "Move forward to the ARG'th subheading at same level as this one.
  18625. Stop at the first and last subheadings of a superior heading.
  18626. Normally this only looks at visible headings, but when INVISIBLE-OK is
  18627. non-nil it will also look at invisible ones."
  18628. (interactive "p")
  18629. (let ((backward? (and arg (< arg 0))))
  18630. (if (org-before-first-heading-p)
  18631. (if backward? (goto-char (point-min)) (outline-next-heading))
  18632. (org-back-to-heading invisible-ok)
  18633. (unless backward? (end-of-line)) ;do not match current headline
  18634. (let ((level (- (match-end 0) (match-beginning 0) 1))
  18635. (f (if backward? #'re-search-backward #'re-search-forward))
  18636. (count (if arg (abs arg) 1))
  18637. (result (point)))
  18638. (while (and (> count 0)
  18639. (funcall f org-outline-regexp-bol nil 'move))
  18640. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  18641. (cond ((< l level) (setq count 0))
  18642. ((and (= l level)
  18643. (or invisible-ok
  18644. (not (org-invisible-p
  18645. (line-beginning-position)))))
  18646. (cl-decf count)
  18647. (when (= l level) (setq result (point)))))))
  18648. (goto-char result))
  18649. (beginning-of-line))))
  18650. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  18651. "Move backward to the ARG'th subheading at same level as this one.
  18652. Stop at the first and last subheadings of a superior heading."
  18653. (interactive "p")
  18654. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  18655. (defun org-next-visible-heading (arg)
  18656. "Move to the next visible heading.
  18657. This function wraps `outline-next-visible-heading' with
  18658. `org-with-limited-levels' in order to skip over inline tasks and
  18659. respect customization of `org-odd-levels-only'."
  18660. (interactive "p")
  18661. (org-with-limited-levels
  18662. (outline-next-visible-heading arg)))
  18663. (defun org-previous-visible-heading (arg)
  18664. "Move to the previous visible heading.
  18665. This function wraps `outline-previous-visible-heading' with
  18666. `org-with-limited-levels' in order to skip over inline tasks and
  18667. respect customization of `org-odd-levels-only'."
  18668. (interactive "p")
  18669. (org-with-limited-levels
  18670. (outline-previous-visible-heading arg)))
  18671. (defun org-forward-paragraph ()
  18672. "Move forward to beginning of next paragraph or equivalent.
  18673. The function moves point to the beginning of the next visible
  18674. structural element, which can be a paragraph, a table, a list
  18675. item, etc. It also provides some special moves for convenience:
  18676. - On an affiliated keyword, jump to the beginning of the
  18677. relative element.
  18678. - On an item or a footnote definition, move to the second
  18679. element inside, if any.
  18680. - On a table or a property drawer, jump after it.
  18681. - On a verse or source block, stop after blank lines."
  18682. (interactive)
  18683. (unless (eobp)
  18684. (let* ((deactivate-mark nil)
  18685. (element (org-element-at-point))
  18686. (type (org-element-type element))
  18687. (post-affiliated (org-element-property :post-affiliated element))
  18688. (contents-begin (org-element-property :contents-begin element))
  18689. (contents-end (org-element-property :contents-end element))
  18690. (end (let ((end (org-element-property :end element)) (parent element))
  18691. (while (and (setq parent (org-element-property :parent parent))
  18692. (= (org-element-property :contents-end parent) end))
  18693. (setq end (org-element-property :end parent)))
  18694. end)))
  18695. (cond ((not element)
  18696. (skip-chars-forward " \r\t\n")
  18697. (or (eobp) (beginning-of-line)))
  18698. ;; On affiliated keywords, move to element's beginning.
  18699. ((< (point) post-affiliated)
  18700. (goto-char post-affiliated))
  18701. ;; At a table row, move to the end of the table. Similarly,
  18702. ;; at a node property, move to the end of the property
  18703. ;; drawer.
  18704. ((memq type '(node-property table-row))
  18705. (goto-char (org-element-property
  18706. :end (org-element-property :parent element))))
  18707. ((memq type '(property-drawer table)) (goto-char end))
  18708. ;; Consider blank lines as separators in verse and source
  18709. ;; blocks to ease editing.
  18710. ((memq type '(src-block verse-block))
  18711. (when (eq type 'src-block)
  18712. (setq contents-end
  18713. (save-excursion (goto-char end)
  18714. (skip-chars-backward " \r\t\n")
  18715. (line-beginning-position))))
  18716. (beginning-of-line)
  18717. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  18718. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  18719. (goto-char end)
  18720. (skip-chars-forward " \r\t\n")
  18721. (if (= (point) contents-end) (goto-char end)
  18722. (beginning-of-line))))
  18723. ;; With no contents, just skip element.
  18724. ((not contents-begin) (goto-char end))
  18725. ;; If contents are invisible, skip the element altogether.
  18726. ((org-invisible-p (line-end-position))
  18727. (cl-case type
  18728. (headline
  18729. (org-with-limited-levels (outline-next-visible-heading 1)))
  18730. ;; At a plain list, make sure we move to the next item
  18731. ;; instead of skipping the whole list.
  18732. (plain-list (forward-char)
  18733. (org-forward-paragraph))
  18734. (otherwise (goto-char end))))
  18735. ((>= (point) contents-end) (goto-char end))
  18736. ((>= (point) contents-begin)
  18737. ;; This can only happen on paragraphs and plain lists.
  18738. (cl-case type
  18739. (paragraph (goto-char end))
  18740. ;; At a plain list, try to move to second element in
  18741. ;; first item, if possible.
  18742. (plain-list (end-of-line)
  18743. (org-forward-paragraph))))
  18744. ;; When contents start on the middle of a line (e.g. in
  18745. ;; items and footnote definitions), try to reach first
  18746. ;; element starting after current line.
  18747. ((> (line-end-position) contents-begin)
  18748. (end-of-line)
  18749. (org-forward-paragraph))
  18750. (t (goto-char contents-begin))))))
  18751. (defun org-backward-paragraph ()
  18752. "Move backward to start of previous paragraph or equivalent.
  18753. The function moves point to the beginning of the current
  18754. structural element, which can be a paragraph, a table, a list
  18755. item, etc., or to the beginning of the previous visible one if
  18756. point is already there. It also provides some special moves for
  18757. convenience:
  18758. - On an affiliated keyword, jump to the first one.
  18759. - On a table or a property drawer, move to its beginning.
  18760. - On comment, example, export, src and verse blocks, stop
  18761. before blank lines."
  18762. (interactive)
  18763. (unless (bobp)
  18764. (let* ((deactivate-mark nil)
  18765. (element (org-element-at-point))
  18766. (type (org-element-type element))
  18767. (contents-end (org-element-property :contents-end element))
  18768. (post-affiliated (org-element-property :post-affiliated element))
  18769. (begin (org-element-property :begin element))
  18770. (special? ;blocks handled specially
  18771. (memq type '(comment-block example-block export-block src-block
  18772. verse-block)))
  18773. (contents-begin
  18774. (if special?
  18775. ;; These types have no proper contents. Fake line
  18776. ;; below the block opening line as contents beginning.
  18777. (save-excursion (goto-char begin) (line-beginning-position 2))
  18778. (org-element-property :contents-begin element))))
  18779. (cond
  18780. ((not element) (goto-char (point-min)))
  18781. ((= (point) begin)
  18782. (backward-char)
  18783. (org-backward-paragraph))
  18784. ((<= (point) post-affiliated) (goto-char begin))
  18785. ;; Special behavior: on a table or a property drawer, move to
  18786. ;; its beginning.
  18787. ((memq type '(node-property table-row))
  18788. (goto-char (org-element-property
  18789. :post-affiliated (org-element-property :parent element))))
  18790. (special?
  18791. (if (<= (point) contents-begin) (goto-char post-affiliated)
  18792. ;; Inside a verse block, see blank lines as paragraph
  18793. ;; separators.
  18794. (let ((origin (point)))
  18795. (skip-chars-backward " \r\t\n" contents-begin)
  18796. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  18797. (skip-chars-forward " \r\t\n" origin)
  18798. (if (= (point) origin) (goto-char contents-begin)
  18799. (beginning-of-line))))))
  18800. ((eq type 'paragraph) (goto-char contents-begin)
  18801. ;; When at first paragraph in an item or a footnote definition,
  18802. ;; move directly to beginning of line.
  18803. (let ((parent-contents
  18804. (org-element-property
  18805. :contents-begin (org-element-property :parent element))))
  18806. (when (and parent-contents (= parent-contents contents-begin))
  18807. (beginning-of-line))))
  18808. ;; At the end of a greater element, move to the beginning of
  18809. ;; the last element within.
  18810. ((and contents-end (>= (point) contents-end))
  18811. (goto-char (1- contents-end))
  18812. (org-backward-paragraph))
  18813. (t (goto-char (or post-affiliated begin))))
  18814. ;; Ensure we never leave point invisible.
  18815. (when (org-invisible-p (point)) (beginning-of-visual-line)))))
  18816. (defun org-forward-element ()
  18817. "Move forward by one element.
  18818. Move to the next element at the same level, when possible."
  18819. (interactive)
  18820. (cond ((eobp) (user-error "Cannot move further down"))
  18821. ((org-with-limited-levels (org-at-heading-p))
  18822. (let ((origin (point)))
  18823. (goto-char (org-end-of-subtree nil t))
  18824. (unless (org-with-limited-levels (org-at-heading-p))
  18825. (goto-char origin)
  18826. (user-error "Cannot move further down"))))
  18827. (t
  18828. (let* ((elem (org-element-at-point))
  18829. (end (org-element-property :end elem))
  18830. (parent (org-element-property :parent elem)))
  18831. (cond ((and parent (= (org-element-property :contents-end parent) end))
  18832. (goto-char (org-element-property :end parent)))
  18833. ((integer-or-marker-p end) (goto-char end))
  18834. (t (message "No element at point")))))))
  18835. (defun org-backward-element ()
  18836. "Move backward by one element.
  18837. Move to the previous element at the same level, when possible."
  18838. (interactive)
  18839. (cond ((bobp) (user-error "Cannot move further up"))
  18840. ((org-with-limited-levels (org-at-heading-p))
  18841. ;; At a headline, move to the previous one, if any, or stay
  18842. ;; here.
  18843. (let ((origin (point)))
  18844. (org-with-limited-levels (org-backward-heading-same-level 1))
  18845. ;; When current headline has no sibling above, move to its
  18846. ;; parent.
  18847. (when (= (point) origin)
  18848. (or (org-with-limited-levels (org-up-heading-safe))
  18849. (progn (goto-char origin)
  18850. (user-error "Cannot move further up"))))))
  18851. (t
  18852. (let* ((elem (org-element-at-point))
  18853. (beg (org-element-property :begin elem)))
  18854. (cond
  18855. ;; Move to beginning of current element if point isn't
  18856. ;; there already.
  18857. ((null beg) (message "No element at point"))
  18858. ((/= (point) beg) (goto-char beg))
  18859. (t (goto-char beg)
  18860. (skip-chars-backward " \r\t\n")
  18861. (unless (bobp)
  18862. (let ((prev (org-element-at-point)))
  18863. (goto-char (org-element-property :begin prev))
  18864. (while (and (setq prev (org-element-property :parent prev))
  18865. (<= (org-element-property :end prev) beg))
  18866. (goto-char (org-element-property :begin prev)))))))))))
  18867. (defun org-up-element ()
  18868. "Move to upper element."
  18869. (interactive)
  18870. (if (org-with-limited-levels (org-at-heading-p))
  18871. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  18872. (let* ((elem (org-element-at-point))
  18873. (parent (org-element-property :parent elem)))
  18874. (if parent (goto-char (org-element-property :begin parent))
  18875. (if (org-with-limited-levels (org-before-first-heading-p))
  18876. (user-error "No surrounding element")
  18877. (org-with-limited-levels (org-back-to-heading)))))))
  18878. (defun org-down-element ()
  18879. "Move to inner element."
  18880. (interactive)
  18881. (let ((element (org-element-at-point)))
  18882. (cond
  18883. ((memq (org-element-type element) '(plain-list table))
  18884. (goto-char (org-element-property :contents-begin element))
  18885. (forward-char))
  18886. ((memq (org-element-type element) org-element-greater-elements)
  18887. ;; If contents are hidden, first disclose them.
  18888. (when (org-invisible-p (line-end-position)) (org-cycle))
  18889. (goto-char (or (org-element-property :contents-begin element)
  18890. (user-error "No content for this element"))))
  18891. (t (user-error "No inner element")))))
  18892. (defun org-drag-element-backward ()
  18893. "Move backward element at point."
  18894. (interactive)
  18895. (let ((elem (or (org-element-at-point)
  18896. (user-error "No element at point"))))
  18897. (if (eq (org-element-type elem) 'headline)
  18898. ;; Preserve point when moving a whole tree, even if point was
  18899. ;; on blank lines below the headline.
  18900. (let ((offset (skip-chars-backward " \t\n")))
  18901. (unwind-protect (org-move-subtree-up)
  18902. (forward-char (- offset))))
  18903. (let ((prev-elem
  18904. (save-excursion
  18905. (goto-char (org-element-property :begin elem))
  18906. (skip-chars-backward " \r\t\n")
  18907. (unless (bobp)
  18908. (let* ((beg (org-element-property :begin elem))
  18909. (prev (org-element-at-point))
  18910. (up prev))
  18911. (while (and (setq up (org-element-property :parent up))
  18912. (<= (org-element-property :end up) beg))
  18913. (setq prev up))
  18914. prev)))))
  18915. ;; Error out if no previous element or previous element is
  18916. ;; a parent of the current one.
  18917. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  18918. (user-error "Cannot drag element backward")
  18919. (let ((pos (point)))
  18920. (org-element-swap-A-B prev-elem elem)
  18921. (goto-char (+ (org-element-property :begin prev-elem)
  18922. (- pos (org-element-property :begin elem))))))))))
  18923. (defun org-drag-element-forward ()
  18924. "Move forward element at point."
  18925. (interactive)
  18926. (let* ((pos (point))
  18927. (elem (or (org-element-at-point)
  18928. (user-error "No element at point"))))
  18929. (when (= (point-max) (org-element-property :end elem))
  18930. (user-error "Cannot drag element forward"))
  18931. (goto-char (org-element-property :end elem))
  18932. (let ((next-elem (org-element-at-point)))
  18933. (when (or (org-element-nested-p elem next-elem)
  18934. (and (eq (org-element-type next-elem) 'headline)
  18935. (not (eq (org-element-type elem) 'headline))))
  18936. (goto-char pos)
  18937. (user-error "Cannot drag element forward"))
  18938. ;; Compute new position of point: it's shifted by NEXT-ELEM
  18939. ;; body's length (without final blanks) and by the length of
  18940. ;; blanks between ELEM and NEXT-ELEM.
  18941. (let ((size-next (- (save-excursion
  18942. (goto-char (org-element-property :end next-elem))
  18943. (skip-chars-backward " \r\t\n")
  18944. (forward-line)
  18945. ;; Small correction if buffer doesn't end
  18946. ;; with a newline character.
  18947. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  18948. (org-element-property :begin next-elem)))
  18949. (size-blank (- (org-element-property :end elem)
  18950. (save-excursion
  18951. (goto-char (org-element-property :end elem))
  18952. (skip-chars-backward " \r\t\n")
  18953. (forward-line)
  18954. (point)))))
  18955. (org-element-swap-A-B elem next-elem)
  18956. (goto-char (+ pos size-next size-blank))))))
  18957. (defun org-drag-line-forward (arg)
  18958. "Drag the line at point ARG lines forward."
  18959. (interactive "p")
  18960. (dotimes (_ (abs arg))
  18961. (let ((c (current-column)))
  18962. (if (< 0 arg)
  18963. (progn
  18964. (beginning-of-line 2)
  18965. (transpose-lines 1)
  18966. (beginning-of-line 0))
  18967. (transpose-lines 1)
  18968. (beginning-of-line -1))
  18969. (org-move-to-column c))))
  18970. (defun org-drag-line-backward (arg)
  18971. "Drag the line at point ARG lines backward."
  18972. (interactive "p")
  18973. (org-drag-line-forward (- arg)))
  18974. (defun org-mark-element ()
  18975. "Put point at beginning of this element, mark at end.
  18976. Interactively, if this command is repeated or (in Transient Mark
  18977. mode) if the mark is active, it marks the next element after the
  18978. ones already marked."
  18979. (interactive)
  18980. (let (deactivate-mark)
  18981. (if (and (called-interactively-p 'any)
  18982. (or (and (eq last-command this-command) (mark t))
  18983. (and transient-mark-mode mark-active)))
  18984. (set-mark
  18985. (save-excursion
  18986. (goto-char (mark))
  18987. (goto-char (org-element-property :end (org-element-at-point)))))
  18988. (let ((element (org-element-at-point)))
  18989. (end-of-line)
  18990. (push-mark (org-element-property :end element) t t)
  18991. (goto-char (org-element-property :begin element))))))
  18992. (defun org-narrow-to-element ()
  18993. "Narrow buffer to current element."
  18994. (interactive)
  18995. (let ((elem (org-element-at-point)))
  18996. (cond
  18997. ((eq (car elem) 'headline)
  18998. (narrow-to-region
  18999. (org-element-property :begin elem)
  19000. (org-element-property :end elem)))
  19001. ((memq (car elem) org-element-greater-elements)
  19002. (narrow-to-region
  19003. (org-element-property :contents-begin elem)
  19004. (org-element-property :contents-end elem)))
  19005. (t
  19006. (narrow-to-region
  19007. (org-element-property :begin elem)
  19008. (org-element-property :end elem))))))
  19009. (defun org-transpose-element ()
  19010. "Transpose current and previous elements, keeping blank lines between.
  19011. Point is moved after both elements."
  19012. (interactive)
  19013. (org-skip-whitespace)
  19014. (let ((end (org-element-property :end (org-element-at-point))))
  19015. (org-drag-element-backward)
  19016. (goto-char end)))
  19017. (defun org-unindent-buffer ()
  19018. "Un-indent the visible part of the buffer.
  19019. Relative indentation (between items, inside blocks, etc.) isn't
  19020. modified."
  19021. (interactive)
  19022. (unless (eq major-mode 'org-mode)
  19023. (user-error "Cannot un-indent a buffer not in Org mode"))
  19024. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  19025. (unindent-tree
  19026. (lambda (contents)
  19027. (dolist (element (reverse contents))
  19028. (if (memq (org-element-type element) '(headline section))
  19029. (funcall unindent-tree (org-element-contents element))
  19030. (save-excursion
  19031. (save-restriction
  19032. (narrow-to-region
  19033. (org-element-property :begin element)
  19034. (org-element-property :end element))
  19035. (org-do-remove-indentation))))))))
  19036. (funcall unindent-tree (org-element-contents parse-tree))))
  19037. (defun org-make-options-regexp (kwds &optional extra)
  19038. "Make a regular expression for keyword lines.
  19039. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  19040. when non-nil, is a regexp matching keywords names."
  19041. (concat "^[ \t]*#\\+\\("
  19042. (regexp-opt kwds)
  19043. (and extra (concat (and kwds "\\|") extra))
  19044. "\\):[ \t]*\\(.*\\)"))
  19045. ;;; Conveniently switch to Info nodes
  19046. (defun org-info-find-node (&optional nodename)
  19047. "Find Info documentation NODENAME or Org documentation according context.
  19048. Started from `gnus-info-find-node'."
  19049. (interactive)
  19050. (Info-goto-node
  19051. (or nodename
  19052. (let ((default-org-info-node "(org) Top"))
  19053. (cond
  19054. ((eq 'org-agenda-mode major-mode) "(org) Agenda Views")
  19055. ((eq 'org-mode major-mode)
  19056. (let* ((context (org-element-at-point))
  19057. (element-info-nodes ; compare to `org-element-all-elements'.
  19058. `((babel-call . "(org) Evaluating Code Blocks")
  19059. (center-block . "(org) Paragraphs")
  19060. (clock . ,default-org-info-node)
  19061. (comment . "(org) Comment Lines")
  19062. (comment-block . "(org) Comment Lines")
  19063. (diary-sexp . ,default-org-info-node)
  19064. (drawer . "(org) Drawers")
  19065. (dynamic-block . "(org) Dynamic Blocks")
  19066. (example-block . "(org) Literal Examples")
  19067. (export-block . "(org) ASCII/Latin-1/UTF-8 export")
  19068. (fixed-width . ,default-org-info-node)
  19069. (footnote-definition . "(org) Creating Footnotes")
  19070. (headline . "(org) Document Structure")
  19071. (horizontal-rule . "(org) Built-in Table Editor")
  19072. (inlinetask . ,default-org-info-node)
  19073. (item . "(org) Plain Lists")
  19074. (keyword . "(org) Per-file keywords")
  19075. (latex-environment . "(org) LaTeX Export")
  19076. (node-property . "(org) Properties and Columns")
  19077. (paragraph . "(org) Paragraphs")
  19078. (plain-list . "(org) Plain Lists")
  19079. (planning . "(org) Deadlines and Scheduling")
  19080. (property-drawer . "(org) Properties and Columns")
  19081. (quote-block . "(org) Paragraphs")
  19082. (section . ,default-org-info-node)
  19083. (special-block . ,default-org-info-node)
  19084. (src-block . "(org) Working with Source Code")
  19085. (table . "(org) Tables")
  19086. (table-row . "(org) Tables")
  19087. (verse-block . "(org) Paragraphs"))))
  19088. (or (cdr (assoc (car context) element-info-nodes))
  19089. default-org-info-node)))
  19090. (t default-org-info-node))))))
  19091. ;;; Finish up
  19092. (add-hook 'org-mode-hook ;remove overlays when changing major mode
  19093. (lambda () (add-hook 'change-major-mode-hook
  19094. 'org-show-all 'append 'local)))
  19095. (provide 'org)
  19096. (run-hooks 'org-load-hook)
  19097. ;; Local variables:
  19098. ;; generated-autoload-file: "org-loaddefs.el"
  19099. ;; End:
  19100. ;;; org.el ends here