org.el 828 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741
  1. ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
  2. ;; Carstens outline-mode for keeping track of everything.
  3. ;; Copyright (C) 2004-2021 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
  6. ;; Maintainer: Bastien Guerry <bzg@gnu.org>
  7. ;; Keywords: outlines, hypermedia, calendar, wp
  8. ;; Homepage: https://orgmode.org
  9. ;; Package-Requires: ((emacs "25.1"))
  10. ;; Version: 9.6-dev
  11. ;; This file is part of GNU Emacs.
  12. ;;
  13. ;; GNU Emacs is free software: you can redistribute it and/or modify
  14. ;; it under the terms of the GNU General Public License as published by
  15. ;; the Free Software Foundation, either version 3 of the License, or
  16. ;; (at your option) any later version.
  17. ;; GNU Emacs is distributed in the hope that it will be useful,
  18. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. ;; GNU General Public License for more details.
  21. ;; You should have received a copy of the GNU General Public License
  22. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  23. ;;
  24. ;;; Commentary:
  25. ;;
  26. ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
  27. ;; project planning with a fast and effective plain-text system.
  28. ;;
  29. ;; Org mode develops organizational tasks around NOTES files that
  30. ;; contain information about projects as plain text. Org mode is
  31. ;; implemented on top of outline-mode, which makes it possible to keep
  32. ;; the content of large files well structured. Visibility cycling and
  33. ;; structure editing help to work with the tree. Tables are easily
  34. ;; created with a built-in table editor. Org mode supports ToDo
  35. ;; items, deadlines, time stamps, and scheduling. It dynamically
  36. ;; compiles entries into an agenda that utilizes and smoothly
  37. ;; integrates much of the Emacs calendar and diary. Plain text
  38. ;; URL-like links connect to websites, emails, Usenet messages, BBDB
  39. ;; entries, and any files related to the projects. For printing and
  40. ;; sharing of notes, an Org file can be exported as a structured ASCII
  41. ;; file, as HTML, or (todo and agenda items only) as an iCalendar
  42. ;; file. It can also serve as a publishing tool for a set of linked
  43. ;; webpages.
  44. ;;
  45. ;; Installation and Activation
  46. ;; ---------------------------
  47. ;; See the corresponding sections in the manual at
  48. ;;
  49. ;; https://orgmode.org/org.html#Installation
  50. ;;
  51. ;; Documentation
  52. ;; -------------
  53. ;; The documentation of Org mode can be found in the TeXInfo file. The
  54. ;; distribution also contains a PDF version of it. At the homepage of
  55. ;; Org mode, you can read the same text online as HTML. There is also an
  56. ;; excellent reference card made by Philip Rooke. This card can be found
  57. ;; in the doc/ directory.
  58. ;;
  59. ;; A list of recent changes can be found at
  60. ;; https://orgmode.org/Changes.html
  61. ;;
  62. ;;; Code:
  63. (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
  64. (defvar org-inlinetask-min-level)
  65. ;;;; Require other packages
  66. (require 'cl-lib)
  67. (eval-when-compile (require 'gnus-sum))
  68. (require 'calendar)
  69. (require 'find-func)
  70. (require 'format-spec)
  71. (or (eq this-command 'eval-buffer)
  72. (condition-case nil
  73. (load (concat (file-name-directory load-file-name)
  74. "org-loaddefs.el")
  75. nil t t t)
  76. (error
  77. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  78. (sit-for 3)
  79. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  80. (sit-for 3))))
  81. (eval-and-compile (require 'org-macs))
  82. (require 'org-compat)
  83. (require 'org-keys)
  84. (require 'ol)
  85. (require 'oc)
  86. (require 'org-table)
  87. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  88. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  89. (defvar org-outline-regexp "\\*+ "
  90. "Regexp to match Org headlines.")
  91. (defvar org-outline-regexp-bol "^\\*+ "
  92. "Regexp to match Org headlines.
  93. This is similar to `org-outline-regexp' but additionally makes
  94. sure that we are at the beginning of the line.")
  95. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  96. "Matches a headline, putting stars and text into groups.
  97. Stars are put in group 1 and the trimmed body in group 2.")
  98. (declare-function calendar-check-holidays "holidays" (date))
  99. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  100. (declare-function cdlatex-math-symbol "ext:cdlatex")
  101. (declare-function Info-goto-node "info" (nodename &optional fork strict-case))
  102. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  103. (declare-function org-add-archive-files "org-archive" (files))
  104. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  105. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
  106. (declare-function org-agenda-redo "org-agenda" (&optional all))
  107. (declare-function org-agenda-remove-restriction-lock "org-agenda" (&optional noupdate))
  108. (declare-function org-archive-subtree "org-archive" (&optional find-done))
  109. (declare-function org-archive-subtree-default "org-archive" ())
  110. (declare-function org-archive-to-archive-sibling "org-archive" ())
  111. (declare-function org-attach "org-attach" ())
  112. (declare-function org-attach-dir "org-attach"
  113. (&optional create-if-not-exists-p no-fs-check))
  114. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  115. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  116. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  117. (declare-function org-clock-auto-clockout "org-clock" ())
  118. (declare-function org-clock-cancel "org-clock" ())
  119. (declare-function org-clock-display "org-clock" (&optional arg))
  120. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  121. (declare-function org-clock-goto "org-clock" (&optional select))
  122. (declare-function org-clock-in "org-clock" (&optional select start-time))
  123. (declare-function org-clock-in-last "org-clock" (&optional arg))
  124. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  125. (declare-function org-clock-out-if-current "org-clock" ())
  126. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  127. (declare-function org-clock-report "org-clock" (&optional arg))
  128. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  129. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  130. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  131. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  132. (declare-function org-clock-update-time-maybe "org-clock" ())
  133. (declare-function org-clocktable-shift "org-clock" (dir n))
  134. (declare-function org-columns-quit "org-colview" ())
  135. (declare-function org-columns-insert-dblock "org-colview" ())
  136. (declare-function org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  137. (declare-function org-duration-to-minutes "org-duration" (duration &optional canonical))
  138. (declare-function org-element-at-point "org-element" (&optional pom cached-only))
  139. (declare-function org-element-at-point-no-context "org-element" (&optional pom))
  140. (declare-function org-element-cache-refresh "org-element" (pos))
  141. (declare-function org-element-cache-reset "org-element" (&optional all))
  142. (declare-function org-element-cache-map "org-element" (func &rest keys))
  143. (declare-function org-element-contents "org-element" (element))
  144. (declare-function org-element-context "org-element" (&optional element))
  145. (declare-function org-element-copy "org-element" (datum))
  146. (declare-function org-element-create "org-element" (type &optional props &rest children))
  147. (declare-function org-element-extract-element "org-element" (element))
  148. (declare-function org-element-insert-before "org-element" (element location))
  149. (declare-function org-element-interpret-data "org-element" (data))
  150. (declare-function org-element-keyword-parser "org-element" (limit affiliated))
  151. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  152. (declare-function org-element-link-parser "org-element" ())
  153. (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion with-affiliated))
  154. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  155. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  156. (declare-function org-element-parse-secondary-string "org-element" (string restriction &optional parent))
  157. (declare-function org-element-property "org-element" (property element))
  158. (declare-function org-element-put-property "org-element" (element property value))
  159. (declare-function org-element-restriction "org-element" (element))
  160. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  161. (declare-function org-element-timestamp-parser "org-element" ())
  162. (declare-function org-element-type "org-element" (element))
  163. (declare-function org-element--cache-active-p "org-element" ())
  164. (declare-function org-export-dispatch "ox" (&optional arg))
  165. (declare-function org-export-get-backend "ox" (name))
  166. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  167. (declare-function org-feed-goto-inbox "org-feed" (feed))
  168. (declare-function org-feed-update-all "org-feed" ())
  169. (declare-function org-goto "org-goto" (&optional alternative-interface))
  170. (declare-function org-id-find-id-file "org-id" (id))
  171. (declare-function org-id-get-create "org-id" (&optional force))
  172. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  173. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  174. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  175. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  176. (declare-function org-num-mode "org-num" (&optional arg))
  177. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  178. (declare-function org-persist-read "org-persist" (var &optional buffer))
  179. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  180. (declare-function org-timer "org-timer" (&optional restart no-insert))
  181. (declare-function org-timer-item "org-timer" (&optional arg))
  182. (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
  183. (declare-function org-timer-set-timer "org-timer" (&optional opt))
  184. (declare-function org-timer-start "org-timer" (&optional offset))
  185. (declare-function org-timer-stop "org-timer" ())
  186. (declare-function org-toggle-archive-tag "org-archive" (&optional find-done))
  187. (declare-function org-update-radio-target-regexp "ol" ())
  188. (defvar org-agenda-buffer-name)
  189. (defvar org-element-paragraph-separate)
  190. (defvar org-indent-indentation-per-level)
  191. (defvar org-radio-target-regexp)
  192. (defvar org-target-link-regexp)
  193. (defvar org-target-regexp)
  194. (defvar org-id-overriding-file-name)
  195. ;; load languages based on value of `org-babel-load-languages'
  196. (defvar org-babel-load-languages)
  197. (defvar crm-separator) ; dynamically scoped param
  198. ;;;###autoload
  199. (defun org-babel-do-load-languages (sym value)
  200. "Load the languages defined in `org-babel-load-languages'."
  201. (set-default sym value)
  202. (dolist (pair org-babel-load-languages)
  203. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  204. (if active
  205. (require (intern (concat "ob-" lang)))
  206. (fmakunbound
  207. (intern (concat "org-babel-execute:" lang)))
  208. (fmakunbound
  209. (intern (concat "org-babel-expand-body:" lang)))))))
  210. ;;;###autoload
  211. (defun org-babel-load-file (file &optional compile)
  212. "Load Emacs Lisp source code blocks in the Org FILE.
  213. This function exports the source code using `org-babel-tangle'
  214. and then loads the resulting file using `load-file'. With
  215. optional prefix argument COMPILE, the tangled Emacs Lisp file is
  216. byte-compiled before it is loaded."
  217. (interactive "fFile to load: \nP")
  218. (let ((tangled-file (concat (file-name-sans-extension file) ".el")))
  219. ;; Tangle only if the Org file is newer than the Elisp file.
  220. (unless (org-file-newer-than-p
  221. tangled-file
  222. (file-attribute-modification-time
  223. (file-attributes (file-truename file))))
  224. (org-babel-tangle-file file
  225. tangled-file
  226. (rx string-start
  227. (or "emacs-lisp" "elisp")
  228. string-end)))
  229. (if compile
  230. (progn
  231. (byte-compile-file tangled-file)
  232. (load tangled-file)
  233. (message "Compiled and loaded %s" tangled-file))
  234. (load-file tangled-file)
  235. (message "Loaded %s" tangled-file))))
  236. (defcustom org-babel-load-languages '((emacs-lisp . t))
  237. "Languages which can be evaluated in Org buffers.
  238. \\<org-mode-map>
  239. This list can be used to load support for any of the languages
  240. below. Each language will depend on a different set of system
  241. executables and/or Emacs modes.
  242. When a language is \"loaded\", code blocks in that language can
  243. be evaluated with `org-babel-execute-src-block', which is bound
  244. by default to \\[org-ctrl-c-ctrl-c].
  245. The `org-babel-no-eval-on-ctrl-c-ctrl-c' option can be set to
  246. remove code block evaluation from \\[org-ctrl-c-ctrl-c]. By
  247. default, only Emacs Lisp is loaded, since it has no specific
  248. requirement."
  249. :group 'org-babel
  250. :set 'org-babel-do-load-languages
  251. :version "24.1"
  252. :type '(alist :tag "Babel Languages"
  253. :key-type
  254. (choice
  255. (const :tag "Awk" awk)
  256. (const :tag "C" C)
  257. (const :tag "R" R)
  258. (const :tag "Calc" calc)
  259. (const :tag "Clojure" clojure)
  260. (const :tag "CSS" css)
  261. (const :tag "Ditaa" ditaa)
  262. (const :tag "Dot" dot)
  263. (const :tag "Emacs Lisp" emacs-lisp)
  264. (const :tag "Forth" forth)
  265. (const :tag "Fortran" fortran)
  266. (const :tag "Gnuplot" gnuplot)
  267. (const :tag "Haskell" haskell)
  268. (const :tag "Java" java)
  269. (const :tag "Javascript" js)
  270. (const :tag "LaTeX" latex)
  271. (const :tag "Lilypond" lilypond)
  272. (const :tag "Lisp" lisp)
  273. (const :tag "Makefile" makefile)
  274. (const :tag "Maxima" maxima)
  275. (const :tag "Matlab" matlab)
  276. (const :tag "Ocaml" ocaml)
  277. (const :tag "Octave" octave)
  278. (const :tag "Org" org)
  279. (const :tag "Perl" perl)
  280. (const :tag "Pico Lisp" picolisp)
  281. (const :tag "PlantUML" plantuml)
  282. (const :tag "Python" python)
  283. (const :tag "Ruby" ruby)
  284. (const :tag "Sass" sass)
  285. (const :tag "Scala" scala)
  286. (const :tag "Scheme" scheme)
  287. (const :tag "Screen" screen)
  288. (const :tag "Shell Script" shell)
  289. (const :tag "Sql" sql)
  290. (const :tag "Sqlite" sqlite)
  291. (const :tag "Stan" stan))
  292. :value-type (boolean :tag "Activate" :value t)))
  293. ;;;; Customization variables
  294. (defcustom org-clone-delete-id nil
  295. "Remove ID property of clones of a subtree.
  296. When non-nil, clones of a subtree don't inherit the ID property.
  297. Otherwise they inherit the ID property with a new unique
  298. identifier."
  299. :type 'boolean
  300. :version "24.1"
  301. :group 'org-id)
  302. ;;; Version
  303. (org-check-version)
  304. ;;;###autoload
  305. (defun org-version (&optional here full message)
  306. "Show the Org version.
  307. Interactively, or when MESSAGE is non-nil, show it in echo area.
  308. With prefix argument, or when HERE is non-nil, insert it at point.
  309. In non-interactive uses, a reduced version string is output unless
  310. FULL is given."
  311. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  312. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  313. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  314. (load-suffixes (list ".el"))
  315. (org-install-dir
  316. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  317. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  318. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  319. (let* ((load-suffixes save-load-suffixes)
  320. (release (org-release))
  321. (git-version (org-git-version))
  322. (version (format "Org mode version %s (%s @ %s)"
  323. release
  324. git-version
  325. (if org-install-dir
  326. (if (string= org-dir org-install-dir)
  327. org-install-dir
  328. (concat "mixed installation! "
  329. org-install-dir
  330. " and "
  331. org-dir))
  332. "org-loaddefs.el can not be found!")))
  333. (version1 (if full version release)))
  334. (when here (insert version1))
  335. (when message (message "%s" version1))
  336. version1)))
  337. (defconst org-version (org-version))
  338. ;;; Syntax Constants
  339. ;;;; Comments
  340. (defconst org-comment-regexp
  341. (rx (seq bol (zero-or-more (any "\t ")) "#" (or " " eol)))
  342. "Regular expression for comment lines.")
  343. ;;;; Keyword
  344. (defconst org-keyword-regexp "^[ \t]*#\\+\\(\\S-+?\\):[ \t]*\\(.*\\)$"
  345. "Regular expression for keyword-lines.")
  346. ;;;; Block
  347. (defconst org-block-regexp
  348. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  349. "Regular expression for hiding blocks.")
  350. (defconst org-dblock-start-re
  351. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  352. "Matches the start line of a dynamic block, with parameters.")
  353. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  354. "Matches the end of a dynamic block.")
  355. ;;;; Timestamp
  356. (defconst org-ts--internal-regexp
  357. (rx (seq
  358. (= 4 digit) "-" (= 2 digit) "-" (= 2 digit)
  359. (optional " " (*? nonl))))
  360. "Regular expression matching the innards of a time stamp.")
  361. (defconst org-ts-regexp (format "<\\(%s\\)>" org-ts--internal-regexp)
  362. "Regular expression for fast time stamp matching.")
  363. (defconst org-ts-regexp-inactive
  364. (format "\\[\\(%s\\)\\]" org-ts--internal-regexp)
  365. "Regular expression for fast inactive time stamp matching.")
  366. (defconst org-ts-regexp-both (format "[[<]\\(%s\\)[]>]" org-ts--internal-regexp)
  367. "Regular expression for fast time stamp matching.")
  368. (defconst org-ts-regexp0
  369. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  370. "Regular expression matching time strings for analysis.
  371. This one does not require the space after the date, so it can be used
  372. on a string that terminates immediately after the date.")
  373. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  374. "Regular expression matching time strings for analysis.")
  375. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  376. "Regular expression matching time stamps, with groups.")
  377. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  378. "Regular expression matching time stamps (also [..]), with groups.")
  379. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  380. "Regular expression matching a time stamp range.")
  381. (defconst org-tr-regexp-both
  382. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  383. "Regular expression matching a time stamp range.")
  384. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  385. org-ts-regexp "\\)?")
  386. "Regular expression matching a time stamp or time stamp range.")
  387. (defconst org-tsr-regexp-both
  388. (concat org-ts-regexp-both "\\(--?-?"
  389. org-ts-regexp-both "\\)?")
  390. "Regular expression matching a time stamp or time stamp range.
  391. The time stamps may be either active or inactive.")
  392. (defconst org-repeat-re
  393. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\
  394. \\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  395. "Regular expression for specifying repeated events.
  396. After a match, group 1 contains the repeat expression.")
  397. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  398. "Formats for `format-time-string' which are used for time stamps.")
  399. ;;;; Clock and Planning
  400. (defconst org-clock-string "CLOCK:"
  401. "String used as prefix for timestamps clocking work hours on an item.")
  402. (defvar org-closed-string "CLOSED:"
  403. "String used as the prefix for timestamps logging closing a TODO entry.")
  404. (defvar org-deadline-string "DEADLINE:"
  405. "String to mark deadline entries.
  406. \\<org-mode-map>
  407. A deadline is this string, followed by a time stamp. It must be
  408. a word, terminated by a colon. You can insert a schedule keyword
  409. and a timestamp with `\\[org-deadline]'.")
  410. (defvar org-scheduled-string "SCHEDULED:"
  411. "String to mark scheduled TODO entries.
  412. \\<org-mode-map>
  413. A schedule is this string, followed by a time stamp. It must be
  414. a word, terminated by a colon. You can insert a schedule keyword
  415. and a timestamp with `\\[org-schedule]'.")
  416. (defconst org-ds-keyword-length
  417. (+ 2
  418. (apply #'max
  419. (mapcar #'length
  420. (list org-deadline-string org-scheduled-string
  421. org-clock-string org-closed-string))))
  422. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  423. (defconst org-planning-line-re
  424. (concat "^[ \t]*"
  425. (regexp-opt
  426. (list org-closed-string org-deadline-string org-scheduled-string)
  427. t))
  428. "Matches a line with planning info.
  429. Matched keyword is in group 1.")
  430. (defconst org-clock-line-re
  431. (concat "^[ \t]*" org-clock-string)
  432. "Matches a line with clock info.")
  433. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  434. "Matches the DEADLINE keyword.")
  435. (defconst org-deadline-time-regexp
  436. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  437. "Matches the DEADLINE keyword together with a time stamp.")
  438. (defconst org-deadline-time-hour-regexp
  439. (concat "\\<" org-deadline-string
  440. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
  441. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  442. (defconst org-deadline-line-regexp
  443. (concat "\\<\\(" org-deadline-string "\\).*")
  444. "Matches the DEADLINE keyword and the rest of the line.")
  445. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  446. "Matches the SCHEDULED keyword.")
  447. (defconst org-scheduled-time-regexp
  448. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  449. "Matches the SCHEDULED keyword together with a time stamp.")
  450. (defconst org-scheduled-time-hour-regexp
  451. (concat "\\<" org-scheduled-string
  452. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
  453. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  454. (defconst org-closed-time-regexp
  455. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  456. "Matches the CLOSED keyword together with a time stamp.")
  457. (defconst org-keyword-time-regexp
  458. (concat "\\<"
  459. (regexp-opt
  460. (list org-scheduled-string org-deadline-string org-closed-string
  461. org-clock-string)
  462. t)
  463. " *[[<]\\([^]>]+\\)[]>]")
  464. "Matches any of the 4 keywords, together with the time stamp.")
  465. (defconst org-keyword-time-not-clock-regexp
  466. (concat
  467. "\\<"
  468. (regexp-opt
  469. (list org-scheduled-string org-deadline-string org-closed-string) t)
  470. " *[[<]\\([^]>]+\\)[]>]")
  471. "Matches any of the 3 keywords, together with the time stamp.")
  472. (defconst org-all-time-keywords
  473. (mapcar (lambda (w) (substring w 0 -1))
  474. (list org-scheduled-string org-deadline-string
  475. org-clock-string org-closed-string))
  476. "List of time keywords.")
  477. ;;;; Drawer
  478. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  479. "Matches first or last line of a hidden block.
  480. Group 1 contains drawer's name or \"END\".")
  481. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  482. "Regular expression matching the first line of a property drawer.")
  483. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  484. "Regular expression matching the last line of a property drawer.")
  485. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  486. "Regular expression matching the first line of a clock drawer.")
  487. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  488. "Regular expression matching the last line of a clock drawer.")
  489. (defconst org-logbook-drawer-re
  490. (rx (seq bol (0+ (any "\t ")) ":LOGBOOK:" (0+ (any "\t ")) "\n"
  491. (*? (0+ nonl) "\n")
  492. (0+ (any "\t ")) ":END:" (0+ (any "\t ")) eol))
  493. "Matches an entire LOGBOOK drawer.")
  494. (defconst org-property-drawer-re
  495. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  496. "\\(?:[ \t]*:\\S-+:\\(?:[ \t].*\\)?[ \t]*\n\\)*?"
  497. "[ \t]*:END:[ \t]*$")
  498. "Matches an entire property drawer.")
  499. (defconst org-clock-drawer-re
  500. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  501. org-clock-drawer-end-re "\\)\n?")
  502. "Matches an entire clock drawer.")
  503. ;;;; Headline
  504. (defconst org-heading-keyword-regexp-format
  505. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  506. "Printf format for a regexp matching a headline with some keyword.
  507. This regexp will match the headline of any node which has the
  508. exact keyword that is put into the format. The keyword isn't in
  509. any group by default, but the stars and the body are.")
  510. (defconst org-heading-keyword-maybe-regexp-format
  511. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  512. "Printf format for a regexp matching a headline, possibly with some keyword.
  513. This regexp can match any headline with the specified keyword, or
  514. without a keyword. The keyword isn't in any group by default,
  515. but the stars and the body are.")
  516. (defconst org-archive-tag "ARCHIVE"
  517. "The tag that marks a subtree as archived.
  518. An archived subtree does not open during visibility cycling, and does
  519. not contribute to the agenda listings.")
  520. (defconst org-tag-re "[[:alnum:]_@#%]+"
  521. "Regexp matching a single tag.")
  522. (defconst org-tag-group-re "[ \t]+\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  523. "Regexp matching the tag group at the end of a line, with leading spaces.
  524. Tags are stored in match group 1. Match group 2 stores the tags
  525. without the enclosing colons.")
  526. (defconst org-tag-line-re
  527. "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  528. "Regexp matching tags in a headline.
  529. Tags are stored in match group 1. Match group 2 stores the tags
  530. without the enclosing colons.")
  531. (eval-and-compile
  532. (defconst org-comment-string "COMMENT"
  533. "Entries starting with this keyword will never be exported.
  534. \\<org-mode-map>
  535. An entry can be toggled between COMMENT and normal with
  536. `\\[org-toggle-comment]'."))
  537. ;;;; LaTeX Environments and Fragments
  538. (defconst org-latex-regexps
  539. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  540. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  541. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  542. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  543. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  544. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  545. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  546. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  547. "Regular expressions for matching embedded LaTeX.")
  548. ;;;; Node Property
  549. (defconst org-effort-property "Effort"
  550. "The property that is being used to keep track of effort estimates.
  551. Effort estimates given in this property need to be in the format
  552. defined in org-duration.el.")
  553. ;;; The custom variables
  554. (defgroup org nil
  555. "Outline-based notes management and organizer."
  556. :tag "Org"
  557. :group 'outlines
  558. :group 'calendar)
  559. (defcustom org-mode-hook nil
  560. "Mode hook for Org mode, run after the mode was turned on."
  561. :group 'org
  562. :type 'hook)
  563. (defcustom org-load-hook nil
  564. "Hook that is run after org.el has been loaded."
  565. :group 'org
  566. :type 'hook)
  567. (make-obsolete-variable
  568. 'org-load-hook
  569. "use `with-eval-after-load' instead." "9.5")
  570. (defcustom org-log-buffer-setup-hook nil
  571. "Hook that is run after an Org log buffer is created."
  572. :group 'org
  573. :version "24.1"
  574. :type 'hook)
  575. (defvar org-modules) ; defined below
  576. (defvar org-modules-loaded nil
  577. "Have the modules been loaded already?")
  578. ;;;###autoload
  579. (defun org-load-modules-maybe (&optional force)
  580. "Load all extensions listed in `org-modules'."
  581. (when (or force (not org-modules-loaded))
  582. (dolist (ext org-modules)
  583. (condition-case nil (require ext)
  584. (error (message "Problems while trying to load feature `%s'" ext))))
  585. (setq org-modules-loaded t)))
  586. (defun org-set-modules (var value)
  587. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  588. (set var value)
  589. (when (featurep 'org)
  590. (org-load-modules-maybe 'force)
  591. (org-element-cache-reset 'all)))
  592. (defcustom org-modules '(ol-doi ol-w3m ol-bbdb ol-bibtex ol-docview ol-gnus ol-info ol-irc ol-mhe ol-rmail ol-eww)
  593. "Modules that should always be loaded together with org.el.
  594. If a description starts with <C>, the file is not part of Emacs and Org mode,
  595. so loading it will require that you have properly installed org-contrib
  596. package from NonGNU Emacs Lisp Package Archive
  597. http://elpa.nongnu.org/nongnu/org-contrib.html
  598. You can also use this system to load external packages (i.e. neither Org
  599. core modules, nor org-contrib modules). Just add symbols
  600. to the end of the list. If the package is called org-xyz.el, then you need
  601. to add the symbol `xyz', and the package must have a call to:
  602. (provide \\='org-xyz)
  603. For export specific modules, see also `org-export-backends'."
  604. :group 'org
  605. :set 'org-set-modules
  606. :package-version '(Org . "9.5")
  607. :type
  608. '(set :greedy t
  609. (const :tag " bbdb: Links to BBDB entries" ol-bbdb)
  610. (const :tag " bibtex: Links to BibTeX entries" ol-bibtex)
  611. (const :tag " crypt: Encryption of subtrees" org-crypt)
  612. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  613. (const :tag " docview: Links to Docview buffers" ol-docview)
  614. (const :tag " doi: Links to DOI references" ol-doi)
  615. (const :tag " eww: Store link to URL of Eww" ol-eww)
  616. (const :tag " gnus: Links to GNUS folders/messages" ol-gnus)
  617. (const :tag " habit: Track your consistency with habits" org-habit)
  618. (const :tag " id: Global IDs for identifying entries" org-id)
  619. (const :tag " info: Links to Info nodes" ol-info)
  620. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  621. (const :tag " irc: Links to IRC/ERC chat sessions" ol-irc)
  622. (const :tag " mhe: Links to MHE folders/messages" ol-mhe)
  623. (const :tag " mouse: Additional mouse support" org-mouse)
  624. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  625. (const :tag " rmail: Links to RMAIL folders/messages" ol-rmail)
  626. (const :tag " tempo: Fast completion for structures" org-tempo)
  627. (const :tag " w3m: Special cut/paste from w3m to Org mode." ol-w3m)
  628. (const :tag " eshell: Links to working directories in Eshell" ol-eshell)
  629. (const :tag "C annotate-file: Annotate a file with Org syntax" org-annotate-file)
  630. (const :tag "C bookmark: Links to bookmarks" ol-bookmark)
  631. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  632. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  633. (const :tag "C collector: Collect properties into tables" org-collector)
  634. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  635. (const :tag "C elisp-symbol: Links to emacs-lisp symbols" ol-elisp-symbol)
  636. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  637. (const :tag "C eval: Include command output as text" org-eval)
  638. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  639. (const :tag "C git-link: Links to specific file version" ol-git-link)
  640. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  641. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  642. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  643. (const :tag "C mac-iCal: Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  644. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  645. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  646. (const :tag "C man: Links to man pages in Org mode" ol-man)
  647. (const :tag "C mew: Links to Mew folders/messages" ol-mew)
  648. (const :tag "C notify: Notifications for Org mode" org-notify)
  649. (const :tag "C notmuch: Provide Org links to notmuch searches or messages" ol-notmuch)
  650. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  651. (const :tag "C registry: A registry for Org links" org-registry)
  652. (const :tag "C screen: Visit screen sessions through links" org-screen)
  653. (const :tag "C screenshot: Take and manage screenshots in Org files" org-screenshot)
  654. (const :tag "C secretary: Team management with Org" org-secretary)
  655. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  656. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  657. (const :tag "C track: Keep up with Org mode development" org-track)
  658. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  659. (const :tag "C vm: Links to VM folders/messages" ol-vm)
  660. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  661. (const :tag "C wl: Links to Wanderlust folders/messages" ol-wl)
  662. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  663. (defvar org-export-registered-backends) ; From ox.el.
  664. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  665. (declare-function org-export-backend-name "ox" (backend) t)
  666. (defcustom org-export-backends '(ascii html icalendar latex odt)
  667. "List of export back-ends that should be always available.
  668. If a description starts with <C>, the file is not part of Emacs and Org mode,
  669. so loading it will require that you have properly installed org-contrib
  670. package from NonGNU Emacs Lisp Package Archive
  671. http://elpa.nongnu.org/nongnu/org-contrib.html
  672. Unlike to `org-modules', libraries in this list will not be
  673. loaded along with Org, but only once the export framework is
  674. needed.
  675. This variable needs to be set before org.el is loaded. If you
  676. need to make a change while Emacs is running, use the customize
  677. interface or run the following code, where VAL stands for the new
  678. value of the variable, after updating it:
  679. (progn
  680. (setq org-export-registered-backends
  681. (cl-remove-if-not
  682. (lambda (backend)
  683. (let ((name (org-export-backend-name backend)))
  684. (or (memq name val)
  685. (catch \\='parentp
  686. (dolist (b val)
  687. (and (org-export-derived-backend-p b name)
  688. (throw \\='parentp t)))))))
  689. org-export-registered-backends))
  690. (let ((new-list (mapcar #\\='org-export-backend-name
  691. org-export-registered-backends)))
  692. (dolist (backend val)
  693. (cond
  694. ((not (load (format \"ox-%s\" backend) t t))
  695. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  696. backend))
  697. ((not (memq backend new-list)) (push backend new-list))))
  698. (set-default \\='org-export-backends new-list)))
  699. Adding a back-end to this list will also pull the back-end it
  700. depends on, if any."
  701. :group 'org
  702. :group 'org-export
  703. :version "26.1"
  704. :package-version '(Org . "9.0")
  705. :initialize 'custom-initialize-set
  706. :set (lambda (var val)
  707. (if (not (featurep 'ox)) (set-default var val)
  708. ;; Any back-end not required anymore (not present in VAL and not
  709. ;; a parent of any back-end in the new value) is removed from the
  710. ;; list of registered back-ends.
  711. (setq org-export-registered-backends
  712. (cl-remove-if-not
  713. (lambda (backend)
  714. (let ((name (org-export-backend-name backend)))
  715. (or (memq name val)
  716. (catch 'parentp
  717. (dolist (b val)
  718. (and (org-export-derived-backend-p b name)
  719. (throw 'parentp t)))))))
  720. org-export-registered-backends))
  721. ;; Now build NEW-LIST of both new back-ends and required
  722. ;; parents.
  723. (let ((new-list (mapcar #'org-export-backend-name
  724. org-export-registered-backends)))
  725. (dolist (backend val)
  726. (cond
  727. ((not (load (format "ox-%s" backend) t t))
  728. (message "Problems while trying to load export back-end `%s'"
  729. backend))
  730. ((not (memq backend new-list)) (push backend new-list))))
  731. ;; Set VAR to that list with fixed dependencies.
  732. (set-default var new-list))))
  733. :type '(set :greedy t
  734. (const :tag " ascii Export buffer to ASCII format" ascii)
  735. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  736. (const :tag " html Export buffer to HTML format" html)
  737. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  738. (const :tag " latex Export buffer to LaTeX format" latex)
  739. (const :tag " man Export buffer to MAN format" man)
  740. (const :tag " md Export buffer to Markdown format" md)
  741. (const :tag " odt Export buffer to ODT format" odt)
  742. (const :tag " org Export buffer to Org format" org)
  743. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  744. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  745. (const :tag "C deck Export buffer to deck.js presentations" deck)
  746. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  747. (const :tag "C groff Export buffer to Groff format" groff)
  748. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  749. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  750. (const :tag "C s5 Export buffer to s5 presentations" s5)
  751. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  752. (eval-after-load 'ox
  753. '(dolist (backend org-export-backends)
  754. (condition-case nil (require (intern (format "ox-%s" backend)))
  755. (error (message "Problems while trying to load export back-end `%s'"
  756. backend)))))
  757. (defcustom org-support-shift-select nil
  758. "Non-nil means make shift-cursor commands select text when possible.
  759. \\<org-mode-map>
  760. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  761. start selecting a region, or enlarge regions started in this way.
  762. In Org mode, in special contexts, these same keys are used for
  763. other purposes, important enough to compete with shift selection.
  764. Org tries to balance these needs by supporting `shift-select-mode'
  765. outside these special contexts, under control of this variable.
  766. The default of this variable is nil, to avoid confusing behavior. Shifted
  767. cursor keys will then execute Org commands in the following contexts:
  768. - on a headline, changing TODO state (left/right) and priority (up/down)
  769. - on a time stamp, changing the time
  770. - in a plain list item, changing the bullet type
  771. - in a property definition line, switching between allowed values
  772. - in the BEGIN line of a clock table (changing the time block).
  773. - in a table, moving the cell in the specified direction.
  774. Outside these contexts, the commands will throw an error.
  775. When this variable is t and the cursor is not in a special
  776. context, Org mode will support shift-selection for making and
  777. enlarging regions. To make this more effective, the bullet
  778. cycling will no longer happen anywhere in an item line, but only
  779. if the cursor is exactly on the bullet.
  780. If you set this variable to the symbol `always', then the keys
  781. will not be special in headlines, property lines, item lines, and
  782. table cells, to make shift selection work there as well. If this is
  783. what you want, you can use the following alternative commands:
  784. `\\[org-todo]' and `\\[org-priority]' \
  785. to change TODO state and priority,
  786. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  787. can be used to switch TODO sets,
  788. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  789. and properties can be edited by hand or in column view.
  790. However, when the cursor is on a timestamp, shift-cursor commands
  791. will still edit the time stamp - this is just too good to give up."
  792. :group 'org
  793. :type '(choice
  794. (const :tag "Never" nil)
  795. (const :tag "When outside special context" t)
  796. (const :tag "Everywhere except timestamps" always)))
  797. (defcustom org-loop-over-headlines-in-active-region t
  798. "Shall some commands act upon headlines in the active region?
  799. When set to t, some commands will be performed in all headlines
  800. within the active region.
  801. When set to `start-level', some commands will be performed in all
  802. headlines within the active region, provided that these headlines
  803. are of the same level than the first one.
  804. When set to a string, those commands will be performed on the
  805. matching headlines within the active region. Such string must be
  806. a tags/property/todo match as it is used in the agenda tags view.
  807. The list of commands is: `org-schedule', `org-deadline',
  808. `org-todo', `org-set-tags-command', `org-archive-subtree',
  809. `org-archive-set-tag', `org-toggle-archive-tag' and
  810. `org-archive-to-archive-sibling'. The archiving commands skip
  811. already archived entries.
  812. See `org-agenda-loop-over-headlines-in-active-region' for the
  813. equivalent option for agenda views."
  814. :type '(choice (const :tag "Don't loop" nil)
  815. (const :tag "All headlines in active region" t)
  816. (const :tag "In active region, headlines at the same level than the first one" start-level)
  817. (string :tag "Tags/Property/Todo matcher"))
  818. :package-version '(Org . "9.4")
  819. :group 'org-todo
  820. :group 'org-archive)
  821. (defcustom org-startup-folded 'showeverything
  822. "Non-nil means entering Org mode will switch to OVERVIEW.
  823. This can also be configured on a per-file basis by adding one of
  824. the following lines anywhere in the buffer:
  825. #+STARTUP: fold (or `overview', this is equivalent)
  826. #+STARTUP: nofold (or `showall', this is equivalent)
  827. #+STARTUP: content
  828. #+STARTUP: show<n>levels (<n> = 2..5)
  829. #+STARTUP: showeverything
  830. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  831. to ignore this option when Org opens agenda files for the first
  832. time."
  833. :group 'org-startup
  834. :package-version '(Org . "9.4")
  835. :type '(choice
  836. (const :tag "nofold: show all" nil)
  837. (const :tag "fold: overview" t)
  838. (const :tag "fold: show two levels" show2levels)
  839. (const :tag "fold: show three levels" show3levels)
  840. (const :tag "fold: show four levels" show4evels)
  841. (const :tag "fold: show five levels" show5levels)
  842. (const :tag "content: all headlines" content)
  843. (const :tag "show everything, even drawers" showeverything)))
  844. (defcustom org-startup-truncated t
  845. "Non-nil means entering Org mode will set `truncate-lines'.
  846. This is useful since some lines containing links can be very long and
  847. uninteresting. Also tables look terrible when wrapped.
  848. The variable `org-startup-truncated' allows to configure
  849. truncation for Org mode different to the other modes that use the
  850. variable `truncate-lines' and as a shortcut instead of putting
  851. the variable `truncate-lines' into the `org-mode-hook'. If one
  852. wants to configure truncation for Org mode not statically but
  853. dynamically e.g. in a hook like `ediff-prepare-buffer-hook' then
  854. the variable `truncate-lines' has to be used because in such a
  855. case it is too late to set the variable `org-startup-truncated'."
  856. :group 'org-startup
  857. :type 'boolean)
  858. (defcustom org-startup-indented nil
  859. "Non-nil means turn on `org-indent-mode' on startup.
  860. This can also be configured on a per-file basis by adding one of
  861. the following lines anywhere in the buffer:
  862. #+STARTUP: indent
  863. #+STARTUP: noindent"
  864. :group 'org-structure
  865. :type '(choice
  866. (const :tag "Not" nil)
  867. (const :tag "Globally (slow on startup in large files)" t)))
  868. (defcustom org-startup-numerated nil
  869. "Non-nil means turn on `org-num-mode' on startup.
  870. This can also be configured on a per-file basis by adding one of
  871. the following lines anywhere in the buffer:
  872. #+STARTUP: num
  873. #+STARTUP: nonum"
  874. :group 'org-structure
  875. :package-version '(Org . "9.4")
  876. :type '(choice
  877. (const :tag "Not" nil)
  878. (const :tag "Globally" t)))
  879. (defcustom org-use-sub-superscripts t
  880. "Non-nil means interpret \"_\" and \"^\" for display.
  881. If you want to control how Org exports those characters, see
  882. `org-export-with-sub-superscripts'.
  883. When this option is turned on, you can use TeX-like syntax for
  884. sub- and superscripts within the buffer. Several characters after
  885. \"_\" or \"^\" will be considered as a single item - so grouping
  886. with {} is normally not needed. For example, the following things
  887. will be parsed as single sub- or superscripts:
  888. 10^24 or 10^tau several digits will be considered 1 item.
  889. 10^-12 or 10^-tau a leading sign with digits or a word
  890. x^2-y^3 will be read as x^2 - y^3, because items are
  891. terminated by almost any nonword/nondigit char.
  892. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  893. Still, ambiguity is possible. So when in doubt, use {} to enclose
  894. the sub/superscript. If you set this variable to the symbol `{}',
  895. the braces are *required* in order to trigger interpretations as
  896. sub/superscript. This can be helpful in documents that need \"_\"
  897. frequently in plain text."
  898. :group 'org-startup
  899. :version "24.4"
  900. :package-version '(Org . "8.0")
  901. :type '(choice
  902. (const :tag "Always interpret" t)
  903. (const :tag "Only with braces" {})
  904. (const :tag "Never interpret" nil)))
  905. (defcustom org-startup-with-beamer-mode nil
  906. "Non-nil means turn on `org-beamer-mode' on startup.
  907. This can also be configured on a per-file basis by adding one of
  908. the following lines anywhere in the buffer:
  909. #+STARTUP: beamer"
  910. :group 'org-startup
  911. :version "24.1"
  912. :type 'boolean)
  913. (defcustom org-startup-align-all-tables nil
  914. "Non-nil means align all tables when visiting a file.
  915. This can also be configured on a per-file basis by adding one of
  916. the following lines anywhere in the buffer:
  917. #+STARTUP: align
  918. #+STARTUP: noalign"
  919. :group 'org-startup
  920. :type 'boolean)
  921. (defcustom org-startup-shrink-all-tables nil
  922. "Non-nil means shrink all table columns with a width cookie.
  923. This can also be configured on a per-file basis by adding one of
  924. the following lines anywhere in the buffer:
  925. #+STARTUP: shrink"
  926. :group 'org-startup
  927. :type 'boolean
  928. :version "27.1"
  929. :package-version '(Org . "9.2")
  930. :safe #'booleanp)
  931. (defcustom org-startup-with-inline-images nil
  932. "Non-nil means show inline images when loading a new Org file.
  933. This can also be configured on a per-file basis by adding one of
  934. the following lines anywhere in the buffer:
  935. #+STARTUP: inlineimages
  936. #+STARTUP: noinlineimages"
  937. :group 'org-startup
  938. :version "24.1"
  939. :type 'boolean)
  940. (defcustom org-startup-with-latex-preview nil
  941. "Non-nil means preview LaTeX fragments when loading a new Org file.
  942. This can also be configured on a per-file basis by adding one of
  943. the following lines anywhere in the buffer:
  944. #+STARTUP: latexpreview
  945. #+STARTUP: nolatexpreview"
  946. :group 'org-startup
  947. :version "24.4"
  948. :package-version '(Org . "8.0")
  949. :type 'boolean)
  950. (defcustom org-insert-mode-line-in-empty-file nil
  951. "Non-nil means insert the first line setting Org mode in empty files.
  952. When the function `org-mode' is called interactively in an empty file, this
  953. normally means that the file name does not automatically trigger Org mode.
  954. To ensure that the file will always be in Org mode in the future, a
  955. line enforcing Org mode will be inserted into the buffer, if this option
  956. has been set."
  957. :group 'org-startup
  958. :type 'boolean)
  959. (defcustom org-ellipsis nil
  960. "The ellipsis to use in the Org mode outline.
  961. When nil, just use the standard three dots. When a non-empty string,
  962. use that string instead.
  963. The change affects only Org mode (which will then use its own display table).
  964. Changing this requires executing `\\[org-mode]' in a buffer to become
  965. effective. It cannot be set as a local variable."
  966. :group 'org-startup
  967. :type '(choice (const :tag "Default" nil)
  968. (string :tag "String" :value "...#")))
  969. (defvar org-display-table nil
  970. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  971. (defcustom org-directory "~/org"
  972. "Directory with Org files.
  973. This is just a default location to look for Org files. There is no need
  974. at all to put your files into this directory. It is used in the
  975. following situations:
  976. 1. When a capture template specifies a target file that is not an
  977. absolute path. The path will then be interpreted relative to
  978. `org-directory'
  979. 2. When the value of variable `org-agenda-files' is a single file, any
  980. relative paths in this file will be taken as relative to
  981. `org-directory'."
  982. :group 'org-refile
  983. :group 'org-capture
  984. :type 'directory)
  985. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  986. "Default target for storing notes.
  987. Used as a fall back file for org-capture.el, for templates that
  988. do not specify a target file."
  989. :group 'org-refile
  990. :group 'org-capture
  991. :type 'file)
  992. (defcustom org-reverse-note-order nil
  993. "Non-nil means store new notes at the beginning of a file or entry.
  994. When nil, new notes will be filed to the end of a file or entry.
  995. This can also be a list with cons cells of regular expressions that
  996. are matched against file names, and values."
  997. :group 'org-capture
  998. :group 'org-refile
  999. :type '(choice
  1000. (const :tag "Reverse always" t)
  1001. (const :tag "Reverse never" nil)
  1002. (repeat :tag "By file name regexp"
  1003. (cons regexp boolean))))
  1004. (defgroup org-keywords nil
  1005. "Keywords in Org mode."
  1006. :tag "Org Keywords"
  1007. :group 'org)
  1008. (defcustom org-closed-keep-when-no-todo nil
  1009. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  1010. :group 'org-todo
  1011. :group 'org-keywords
  1012. :version "24.4"
  1013. :package-version '(Org . "8.0")
  1014. :type 'boolean)
  1015. (defgroup org-structure nil
  1016. "Options concerning the general structure of Org files."
  1017. :tag "Org Structure"
  1018. :group 'org)
  1019. (defgroup org-reveal-location nil
  1020. "Options about how to make context of a location visible."
  1021. :tag "Org Reveal Location"
  1022. :group 'org-structure)
  1023. (defcustom org-show-context-detail '((agenda . local)
  1024. (bookmark-jump . lineage)
  1025. (isearch . lineage)
  1026. (default . ancestors))
  1027. "Alist between context and visibility span when revealing a location.
  1028. \\<org-mode-map>Some actions may move point into invisible
  1029. locations. As a consequence, Org always exposes a neighborhood
  1030. around point. How much is shown depends on the initial action,
  1031. or context. Valid contexts are
  1032. agenda when exposing an entry from the agenda
  1033. org-goto when using the command `org-goto' (`\\[org-goto]')
  1034. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  1035. tags-tree when constructing a sparse tree based on tags matches
  1036. link-search when exposing search matches associated with a link
  1037. mark-goto when exposing the jump goal of a mark
  1038. bookmark-jump when exposing a bookmark location
  1039. isearch when exiting from an incremental search
  1040. default default for all contexts not set explicitly
  1041. Allowed visibility spans are
  1042. minimal show current headline; if point is not on headline,
  1043. also show entry
  1044. local show current headline, entry and next headline
  1045. ancestors show current headline and its direct ancestors; if
  1046. point is not on headline, also show entry
  1047. ancestors-full show current subtree and its direct ancestors
  1048. lineage show current headline, its direct ancestors and all
  1049. their children; if point is not on headline, also show
  1050. entry and first child
  1051. tree show current headline, its direct ancestors and all
  1052. their children; if point is not on headline, also show
  1053. entry and all children
  1054. canonical show current headline, its direct ancestors along with
  1055. their entries and children; if point is not located on
  1056. the headline, also show current entry and all children
  1057. As special cases, a nil or t value means show all contexts in
  1058. `minimal' or `canonical' view, respectively.
  1059. Some views can make displayed information very compact, but also
  1060. make it harder to edit the location of the match. In such
  1061. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  1062. more context."
  1063. :group 'org-reveal-location
  1064. :version "26.1"
  1065. :package-version '(Org . "9.0")
  1066. :type '(choice
  1067. (const :tag "Canonical" t)
  1068. (const :tag "Minimal" nil)
  1069. (repeat :greedy t :tag "Individual contexts"
  1070. (cons
  1071. (choice :tag "Context"
  1072. (const agenda)
  1073. (const org-goto)
  1074. (const occur-tree)
  1075. (const tags-tree)
  1076. (const link-search)
  1077. (const mark-goto)
  1078. (const bookmark-jump)
  1079. (const isearch)
  1080. (const default))
  1081. (choice :tag "Detail level"
  1082. (const minimal)
  1083. (const local)
  1084. (const ancestors)
  1085. (const ancestors-full)
  1086. (const lineage)
  1087. (const tree)
  1088. (const canonical))))))
  1089. (defcustom org-indirect-buffer-display 'other-window
  1090. "How should indirect tree buffers be displayed?
  1091. This applies to indirect buffers created with the commands
  1092. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1093. Valid values are:
  1094. current-window Display in the current window
  1095. other-window Just display in another window.
  1096. dedicated-frame Create one new frame, and re-use it each time.
  1097. new-frame Make a new frame each time. Note that in this case
  1098. previously-made indirect buffers are kept, and you need to
  1099. kill these buffers yourself."
  1100. :group 'org-structure
  1101. :group 'org-agenda-windows
  1102. :type '(choice
  1103. (const :tag "In current window" current-window)
  1104. (const :tag "In current frame, other window" other-window)
  1105. (const :tag "Each time a new frame" new-frame)
  1106. (const :tag "One dedicated frame" dedicated-frame)))
  1107. (defconst org-file-apps-gnu
  1108. '((remote . emacs)
  1109. (system . mailcap)
  1110. (t . mailcap))
  1111. "Default file applications on a UNIX or GNU/Linux system.
  1112. See `org-file-apps'.")
  1113. (defconst org-file-apps-macos
  1114. '((remote . emacs)
  1115. (system . "open %s")
  1116. ("ps.gz" . "gv %s")
  1117. ("eps.gz" . "gv %s")
  1118. ("dvi" . "xdvi %s")
  1119. ("fig" . "xfig %s")
  1120. (t . "open %s"))
  1121. "Default file applications on a macOS system.
  1122. The system \"open\" is known as a default, but we use X11 applications
  1123. for some files for which the OS does not have a good default.
  1124. See `org-file-apps'.")
  1125. (defconst org-file-apps-windowsnt
  1126. (list '(remote . emacs)
  1127. (cons 'system (lambda (file _path)
  1128. (with-no-warnings (w32-shell-execute "open" file))))
  1129. (cons t (lambda (file _path)
  1130. (with-no-warnings (w32-shell-execute "open" file)))))
  1131. "Default file applications on a Windows NT system.
  1132. The system \"open\" is used for most files.
  1133. See `org-file-apps'.")
  1134. (defcustom org-file-apps
  1135. '((auto-mode . emacs)
  1136. (directory . emacs)
  1137. ("\\.mm\\'" . default)
  1138. ("\\.x?html?\\'" . default)
  1139. ("\\.pdf\\'" . default))
  1140. "Applications for opening `file:path' items in a document.
  1141. \\<org-mode-map>
  1142. Org mode uses system defaults for different file types, but you
  1143. can use this variable to set the application for a given file
  1144. extension. The entries in this list are cons cells where the car
  1145. identifies files and the cdr the corresponding command.
  1146. Possible values for the file identifier are:
  1147. \"string\" A string as a file identifier can be interpreted in different
  1148. ways, depending on its contents:
  1149. - Alphanumeric characters only:
  1150. Match links with this file extension.
  1151. Example: (\"pdf\" . \"evince %s\")
  1152. to open PDFs with evince.
  1153. - Regular expression: Match links where the
  1154. filename matches the regexp. If you want to
  1155. use groups here, use shy groups.
  1156. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1157. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1158. to open *.html and *.xhtml with firefox.
  1159. - Regular expression which contains (non-shy) groups:
  1160. Match links where the whole link, including \"::\", and
  1161. anything after that, matches the regexp.
  1162. In a custom command string, %1, %2, etc. are replaced with
  1163. the parts of the link that were matched by the groups.
  1164. For backwards compatibility, if a command string is given
  1165. that does not use any of the group matches, this case is
  1166. handled identically to the second one (i.e. match against
  1167. file name only).
  1168. In a custom function, you can access the group matches with
  1169. (match-string n link).
  1170. Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
  1171. \"evince -p %1 %s\")
  1172. to open [[file:document.pdf::5]] with evince at page 5.
  1173. `directory' Matches a directory
  1174. `remote' Matches a remote file, accessible through tramp or efs.
  1175. Remote files most likely should be visited through Emacs
  1176. because external applications cannot handle such paths.
  1177. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1178. so all files Emacs knows how to handle. Using this with
  1179. command `emacs' will open most files in Emacs. Beware that this
  1180. will also open html files inside Emacs, unless you add
  1181. (\"html\" . default) to the list as well.
  1182. `system' The system command to open files, like `open' on Windows
  1183. and macOS, and mailcap under GNU/Linux. This is the command
  1184. that will be selected if you call `org-open-at-point' with a
  1185. double prefix argument (`\\[universal-argument] \
  1186. \\[universal-argument] \\[org-open-at-point]').
  1187. t Default for files not matched by any of the other options.
  1188. Possible values for the command are:
  1189. `emacs' The file will be visited by the current Emacs process.
  1190. `default' Use the default application for this file type, which is the
  1191. association for t in the list, most likely in the system-specific
  1192. part. This can be used to overrule an unwanted setting in the
  1193. system-specific variable.
  1194. `system' Use the system command for opening files, like \"open\".
  1195. This command is specified by the entry whose car is `system'.
  1196. Most likely, the system-specific version of this variable
  1197. does define this command, but you can overrule/replace it
  1198. here.
  1199. `mailcap' Use command specified in the mailcaps.
  1200. string A command to be executed by a shell; %s will be replaced
  1201. by the path to the file.
  1202. function A Lisp function, which will be called with two arguments:
  1203. the file path and the original link string, without the
  1204. \"file:\" prefix.
  1205. For more examples, see the system specific constants
  1206. `org-file-apps-macos'
  1207. `org-file-apps-windowsnt'
  1208. `org-file-apps-gnu'."
  1209. :group 'org
  1210. :package-version '(Org . "9.4")
  1211. :type '(repeat
  1212. (cons (choice :value ""
  1213. (string :tag "Extension")
  1214. (const :tag "System command to open files" system)
  1215. (const :tag "Default for unrecognized files" t)
  1216. (const :tag "Remote file" remote)
  1217. (const :tag "Links to a directory" directory)
  1218. (const :tag "Any files that have Emacs modes"
  1219. auto-mode))
  1220. (choice :value ""
  1221. (const :tag "Visit with Emacs" emacs)
  1222. (const :tag "Use default" default)
  1223. (const :tag "Use the system command" system)
  1224. (string :tag "Command")
  1225. (function :tag "Function")))))
  1226. (defcustom org-open-non-existing-files nil
  1227. "Non-nil means `org-open-file' opens non-existing files.
  1228. When nil, an error is thrown.
  1229. This variable applies only to external applications because they
  1230. might choke on non-existing files. If the link is to a file that
  1231. will be opened in Emacs, the variable is ignored."
  1232. :group 'org
  1233. :type 'boolean
  1234. :safe #'booleanp)
  1235. (defcustom org-open-directory-means-index-dot-org nil
  1236. "When non-nil a link to a directory really means to \"index.org\".
  1237. When nil, following a directory link runs Dired or opens
  1238. a finder/explorer window on that directory."
  1239. :group 'org
  1240. :type 'boolean
  1241. :safe #'booleanp)
  1242. (defcustom org-bookmark-names-plist
  1243. '(:last-capture "org-capture-last-stored"
  1244. :last-refile "org-refile-last-stored"
  1245. :last-capture-marker "org-capture-last-stored-marker")
  1246. "Names for bookmarks automatically set by some Org commands.
  1247. This can provide strings as names for a number of bookmarks Org sets
  1248. automatically. The following keys are currently implemented:
  1249. :last-capture
  1250. :last-capture-marker
  1251. :last-refile
  1252. When a key does not show up in the property list, the corresponding bookmark
  1253. is not set."
  1254. :group 'org-structure
  1255. :type 'plist)
  1256. (defgroup org-cycle nil
  1257. "Options concerning visibility cycling in Org mode."
  1258. :tag "Org Cycle"
  1259. :group 'org-structure)
  1260. (defcustom org-cycle-skip-children-state-if-no-children t
  1261. "Non-nil means skip CHILDREN state in entries that don't have any."
  1262. :group 'org-cycle
  1263. :type 'boolean)
  1264. (defcustom org-cycle-max-level nil
  1265. "Maximum level which should still be subject to visibility cycling.
  1266. Levels higher than this will, for cycling, be treated as text, not a headline.
  1267. When `org-odd-levels-only' is set, a value of N in this variable actually
  1268. means 2N-1 stars as the limiting headline.
  1269. When nil, cycle all levels.
  1270. Note that the limiting level of cycling is also influenced by
  1271. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1272. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1273. than its value."
  1274. :group 'org-cycle
  1275. :type '(choice
  1276. (const :tag "No limit" nil)
  1277. (integer :tag "Maximum level")))
  1278. (defcustom org-hide-block-startup nil
  1279. "Non-nil means entering Org mode will fold all blocks.
  1280. This can also be set in on a per-file basis with
  1281. #+STARTUP: hideblocks
  1282. #+STARTUP: showblocks"
  1283. :group 'org-startup
  1284. :group 'org-cycle
  1285. :type 'boolean)
  1286. (defcustom org-cycle-global-at-bob nil
  1287. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1288. This makes it possible to do global cycling without having to use `S-TAB'
  1289. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1290. line of the buffer
  1291. must not be a headline -- it may be empty or some other text.
  1292. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1293. sure the cursor stays at the beginning of the buffer.
  1294. When this option is nil, don't do anything special at the beginning of
  1295. the buffer."
  1296. :group 'org-cycle
  1297. :type 'boolean)
  1298. (defcustom org-cycle-level-after-item/entry-creation t
  1299. "Non-nil means cycle entry level or item indentation in new empty entries.
  1300. When the cursor is at the end of an empty headline, i.e., with only stars
  1301. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1302. and then all possible ancestor states, before returning to the original state.
  1303. This makes data entry extremely fast: M-RET to create a new headline,
  1304. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1305. When the cursor is at the end of an empty plain list item, one TAB will
  1306. make it a subitem, two or more tabs will back up to make this an item
  1307. higher up in the item hierarchy."
  1308. :group 'org-cycle
  1309. :type 'boolean)
  1310. (defcustom org-cycle-emulate-tab t
  1311. "Where should `org-cycle' emulate TAB.
  1312. nil Never
  1313. white Only in completely white lines
  1314. whitestart Only at the beginning of lines, before the first non-white char
  1315. t Everywhere except in headlines
  1316. exc-hl-bol Everywhere except at the start of a headline
  1317. If TAB is used in a place where it does not emulate TAB, the current subtree
  1318. visibility is cycled."
  1319. :group 'org-cycle
  1320. :type '(choice (const :tag "Never" nil)
  1321. (const :tag "Only in completely white lines" white)
  1322. (const :tag "Before first char in a line" whitestart)
  1323. (const :tag "Everywhere except in headlines" t)
  1324. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1325. (defcustom org-cycle-separator-lines 2
  1326. "Number of empty lines needed to keep an empty line between collapsed trees.
  1327. If you leave an empty line between the end of a subtree and the following
  1328. headline, this empty line is hidden when the subtree is folded.
  1329. Org mode will leave (exactly) one empty line visible if the number of
  1330. empty lines is equal or larger to the number given in this variable.
  1331. So the default 2 means at least 2 empty lines after the end of a subtree
  1332. are needed to produce free space between a collapsed subtree and the
  1333. following headline.
  1334. If the number is negative, and the number of empty lines is at least -N,
  1335. all empty lines are shown.
  1336. Special case: when 0, never leave empty lines in collapsed view."
  1337. :group 'org-cycle
  1338. :type 'integer)
  1339. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1340. (defcustom org-pre-cycle-hook nil
  1341. "Hook that is run before visibility cycling is happening.
  1342. The function(s) in this hook must accept a single argument which indicates
  1343. the new state that will be set right after running this hook. The
  1344. argument is a symbol. Before a global state change, it can have the values
  1345. `overview', `content', or `all'. Before a local state change, it can have
  1346. the values `folded', `children', or `subtree'."
  1347. :group 'org-cycle
  1348. :type 'hook)
  1349. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1350. org-cycle-hide-drawers
  1351. org-cycle-show-empty-lines
  1352. org-optimize-window-after-visibility-change)
  1353. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1354. The function(s) in this hook must accept a single argument which indicates
  1355. the new state that was set by the most recent `org-cycle' command. The
  1356. argument is a symbol. After a global state change, it can have the values
  1357. `overview', `contents', or `all'. After a local state change, it can have
  1358. the values `folded', `children', or `subtree'."
  1359. :group 'org-cycle
  1360. :package-version '(Org . "9.4")
  1361. :type 'hook)
  1362. (defgroup org-edit-structure nil
  1363. "Options concerning structure editing in Org mode."
  1364. :tag "Org Edit Structure"
  1365. :group 'org-structure)
  1366. (defcustom org-odd-levels-only nil
  1367. "Non-nil means skip even levels and only use odd levels for the outline.
  1368. This has the effect that two stars are being added/taken away in
  1369. promotion/demotion commands. It also influences how levels are
  1370. handled by the exporters.
  1371. Changing it requires restart of `font-lock-mode' to become effective
  1372. for fontification also in regions already fontified.
  1373. You may also set this on a per-file basis by adding one of the following
  1374. lines to the buffer:
  1375. #+STARTUP: odd
  1376. #+STARTUP: oddeven"
  1377. :group 'org-edit-structure
  1378. :group 'org-appearance
  1379. :type 'boolean)
  1380. (defcustom org-adapt-indentation nil
  1381. "Non-nil means adapt indentation to outline node level.
  1382. When set to t, Org assumes that you write outlines by indenting
  1383. text in each node to align with the headline, after the stars.
  1384. When this variable is set to `headline-data', Org only adapts the
  1385. indentation of the data lines right below the headline, such as
  1386. planning/clock lines and property/logbook drawers.
  1387. The following issues are influenced by this variable:
  1388. - The indentation is increased by one space in a demotion
  1389. command, and decreased by one in a promotion command. However,
  1390. in the latter case, if shifting some line in the entry body
  1391. would alter document structure (e.g., insert a new headline),
  1392. indentation is not changed at all.
  1393. - Property drawers and planning information is inserted indented
  1394. when this variable is set. When nil, they will not be indented.
  1395. - TAB indents a line relative to current level. The lines below
  1396. a headline will be indented when this variable is set to t.
  1397. Note that this is all about true indentation, by adding and
  1398. removing space characters. See also \"org-indent.el\" which does
  1399. level-dependent indentation in a virtual way, i.e. at display
  1400. time in Emacs."
  1401. :group 'org-edit-structure
  1402. :type '(choice
  1403. (const :tag "Adapt indentation for all lines" t)
  1404. (const :tag "Adapt indentation for headline data lines"
  1405. headline-data)
  1406. (const :tag "Do not adapt indentation at all" nil))
  1407. :safe (lambda (x) (memq x '(t nil headline-data))))
  1408. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1409. (defcustom org-special-ctrl-a/e nil
  1410. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1411. When t, `C-a' will bring back the cursor to the beginning of the
  1412. headline text, i.e. after the stars and after a possible TODO
  1413. keyword. In an item, this will be the position after bullet and
  1414. check-box, if any. When the cursor is already at that position,
  1415. another `C-a' will bring it to the beginning of the line.
  1416. `C-e' will jump to the end of the headline, ignoring the presence
  1417. of tags in the headline. A second `C-e' will then jump to the
  1418. true end of the line, after any tags. This also means that, when
  1419. this variable is non-nil, `C-e' also will never jump beyond the
  1420. end of the heading of a folded section, i.e. not after the
  1421. ellipses.
  1422. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1423. normally, going to the true line boundary first. Only a directly
  1424. following, identical keypress will bring the cursor to the
  1425. special positions.
  1426. This may also be a cons cell where the behavior for `C-a' and
  1427. `C-e' is set separately."
  1428. :group 'org-edit-structure
  1429. :type '(choice
  1430. (const :tag "off" nil)
  1431. (const :tag "on: after stars/bullet and before tags first" t)
  1432. (const :tag "reversed: true line boundary first" reversed)
  1433. (cons :tag "Set C-a and C-e separately"
  1434. (choice :tag "Special C-a"
  1435. (const :tag "off" nil)
  1436. (const :tag "on: after stars/bullet first" t)
  1437. (const :tag "reversed: before stars/bullet first" reversed))
  1438. (choice :tag "Special C-e"
  1439. (const :tag "off" nil)
  1440. (const :tag "on: before tags first" t)
  1441. (const :tag "reversed: after tags first" reversed)))))
  1442. (defcustom org-special-ctrl-k nil
  1443. "Non-nil means `C-k' will behave specially in headlines.
  1444. When nil, `C-k' will call the default `kill-line' command.
  1445. When t, the following will happen while the cursor is in the headline:
  1446. - When at the beginning of a headline, kill the entire subtree.
  1447. - When in the middle of the headline text, kill the text up to the tags.
  1448. - When after the headline text and before the tags, kill all the tags."
  1449. :group 'org-edit-structure
  1450. :type 'boolean)
  1451. (defcustom org-ctrl-k-protect-subtree nil
  1452. "Non-nil means, do not delete a hidden subtree with `C-k'.
  1453. When set to the symbol `error', simply throw an error when `C-k' is
  1454. used to kill (part-of) a headline that has hidden text behind it.
  1455. Any other non-nil value will result in a query to the user, if it is
  1456. OK to kill that hidden subtree. When nil, kill without remorse."
  1457. :group 'org-edit-structure
  1458. :version "24.1"
  1459. :type '(choice
  1460. (const :tag "Do not protect hidden subtrees" nil)
  1461. (const :tag "Protect hidden subtrees with a security query" t)
  1462. (const :tag "Never kill a hidden subtree with C-k" error)))
  1463. (defcustom org-special-ctrl-o t
  1464. "Non-nil means, make `C-o' insert a row in tables."
  1465. :group 'org-edit-structure
  1466. :type 'boolean)
  1467. (defcustom org-catch-invisible-edits nil
  1468. "Check if in invisible region before inserting or deleting a character.
  1469. Valid values are:
  1470. nil Do not check, so just do invisible edits.
  1471. error Throw an error and do nothing.
  1472. show Make point visible, and do the requested edit.
  1473. show-and-error Make point visible, then throw an error and abort the edit.
  1474. smart Make point visible, and do insertion/deletion if it is
  1475. adjacent to visible text and the change feels predictable.
  1476. Never delete a previously invisible character or add in the
  1477. middle or right after an invisible region. Basically, this
  1478. allows insertion and backward-delete right before ellipses.
  1479. FIXME: maybe in this case we should not even show?"
  1480. :group 'org-edit-structure
  1481. :version "24.1"
  1482. :type '(choice
  1483. (const :tag "Do not check" nil)
  1484. (const :tag "Throw error when trying to edit" error)
  1485. (const :tag "Unhide, but do not do the edit" show-and-error)
  1486. (const :tag "Show invisible part and do the edit" show)
  1487. (const :tag "Be smart and do the right thing" smart)))
  1488. (defcustom org-yank-folded-subtrees t
  1489. "Non-nil means when yanking subtrees, fold them.
  1490. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1491. it starts with a heading and all other headings in it are either children
  1492. or siblings, then fold all the subtrees. However, do this only if no
  1493. text after the yank would be swallowed into a folded tree by this action."
  1494. :group 'org-edit-structure
  1495. :type 'boolean)
  1496. (defcustom org-yank-adjusted-subtrees nil
  1497. "Non-nil means when yanking subtrees, adjust the level.
  1498. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1499. this function for details."
  1500. :group 'org-edit-structure
  1501. :type 'boolean)
  1502. (defcustom org-M-RET-may-split-line '((default . t))
  1503. "Non-nil means M-RET will split the line at the cursor position.
  1504. When nil, it will go to the end of the line before making a
  1505. new line.
  1506. You may also set this option in a different way for different
  1507. contexts. Valid contexts are:
  1508. headline when creating a new headline
  1509. item when creating a new item
  1510. table in a table field
  1511. default the value to be used for all contexts not explicitly
  1512. customized"
  1513. :group 'org-structure
  1514. :group 'org-table
  1515. :type '(choice
  1516. (const :tag "Always" t)
  1517. (const :tag "Never" nil)
  1518. (repeat :greedy t :tag "Individual contexts"
  1519. (cons
  1520. (choice :tag "Context"
  1521. (const headline)
  1522. (const item)
  1523. (const table)
  1524. (const default))
  1525. (boolean)))))
  1526. (defcustom org-insert-heading-respect-content nil
  1527. "Non-nil means insert new headings after the current subtree.
  1528. \\<org-mode-map>
  1529. When nil, the new heading is created directly after the current line.
  1530. The commands `\\[org-insert-heading-respect-content]' and \
  1531. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1532. for the duration of the command."
  1533. :group 'org-structure
  1534. :type 'boolean)
  1535. (defcustom org-blank-before-new-entry '((heading . auto)
  1536. (plain-list-item . auto))
  1537. "Should `org-insert-heading' leave a blank line before new heading/item?
  1538. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1539. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1540. which case Org will look at the surrounding headings/items and try to
  1541. make an intelligent decision whether to insert a blank line or not."
  1542. :group 'org-edit-structure
  1543. :type '(list
  1544. (cons (const heading)
  1545. (choice (const :tag "Never" nil)
  1546. (const :tag "Always" t)
  1547. (const :tag "Auto" auto)))
  1548. (cons (const plain-list-item)
  1549. (choice (const :tag "Never" nil)
  1550. (const :tag "Always" t)
  1551. (const :tag "Auto" auto)))))
  1552. (defcustom org-insert-heading-hook nil
  1553. "Hook being run after inserting a new heading."
  1554. :group 'org-edit-structure
  1555. :type 'hook)
  1556. (defgroup org-sparse-trees nil
  1557. "Options concerning sparse trees in Org mode."
  1558. :tag "Org Sparse Trees"
  1559. :group 'org-structure)
  1560. (defcustom org-highlight-sparse-tree-matches t
  1561. "Non-nil means highlight all matches that define a sparse tree.
  1562. The highlights will automatically disappear the next time the buffer is
  1563. changed by an edit command."
  1564. :group 'org-sparse-trees
  1565. :type 'boolean)
  1566. (defcustom org-remove-highlights-with-change t
  1567. "Non-nil means any change to the buffer will remove temporary highlights.
  1568. \\<org-mode-map>\
  1569. Such highlights are created by `org-occur' and `org-clock-display'.
  1570. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1571. to get rid of the highlights.
  1572. The highlights created by `org-latex-preview' always need
  1573. `\\[org-latex-preview]' to be removed."
  1574. :group 'org-sparse-trees
  1575. :group 'org-time
  1576. :type 'boolean)
  1577. (defcustom org-occur-case-fold-search t
  1578. "Non-nil means `org-occur' should be case-insensitive.
  1579. If set to `smart' the search will be case-insensitive only if it
  1580. doesn't specify any upper case character."
  1581. :group 'org-sparse-trees
  1582. :version "26.1"
  1583. :type '(choice
  1584. (const :tag "Case-sensitive" nil)
  1585. (const :tag "Case-insensitive" t)
  1586. (const :tag "Case-insensitive for lower case searches only" smart)))
  1587. (defcustom org-occur-hook '(org-first-headline-recenter)
  1588. "Hook that is run after `org-occur' has constructed a sparse tree.
  1589. This can be used to recenter the window to show as much of the structure
  1590. as possible."
  1591. :group 'org-sparse-trees
  1592. :type 'hook)
  1593. (defcustom org-self-insert-cluster-for-undo nil
  1594. "Non-nil means cluster self-insert commands for undo when possible.
  1595. If this is set, then, like in the Emacs command loop, 20 consecutive
  1596. characters will be undone together.
  1597. This is configurable, because there is some impact on typing performance."
  1598. :group 'org-table
  1599. :type 'boolean)
  1600. (defvaralias 'org-activate-links 'org-highlight-links)
  1601. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1602. "Types of links that should be highlighted in Org files.
  1603. This is a list of symbols, each one of them leading to the
  1604. highlighting of a certain link type.
  1605. You can still open links that are not highlighted.
  1606. In principle, it does not hurt to turn on highlighting for all
  1607. link types. There may be a small gain when turning off unused
  1608. link types. The types are:
  1609. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1610. angle Links in angular brackets that may contain whitespace like
  1611. <bbdb:Carsten Dominik>.
  1612. plain Plain links in normal text, no whitespace, like https://gnu.org.
  1613. radio Text that is matched by a radio target, see manual for details.
  1614. tag Tag settings in a headline (link to tag search).
  1615. date Time stamps (link to calendar).
  1616. footnote Footnote labels.
  1617. If you set this variable during an Emacs session, use `org-mode-restart'
  1618. in the Org buffer so that the change takes effect."
  1619. :group 'org-appearance
  1620. :type '(set :greedy t
  1621. (const :tag "Double bracket links" bracket)
  1622. (const :tag "Angular bracket links" angle)
  1623. (const :tag "Plain text links" plain)
  1624. (const :tag "Radio target matches" radio)
  1625. (const :tag "Tags" tag)
  1626. (const :tag "Timestamps" date)
  1627. (const :tag "Footnotes" footnote)))
  1628. (defcustom org-mark-ring-length 4
  1629. "Number of different positions to be recorded in the ring.
  1630. Changing this requires a restart of Emacs to work correctly."
  1631. :group 'org-link-follow
  1632. :type 'integer)
  1633. (defgroup org-todo nil
  1634. "Options concerning TODO items in Org mode."
  1635. :tag "Org TODO"
  1636. :group 'org)
  1637. (defgroup org-progress nil
  1638. "Options concerning Progress logging in Org mode."
  1639. :tag "Org Progress"
  1640. :group 'org-time)
  1641. (defvar org-todo-interpretation-widgets
  1642. '((:tag "Sequence (cycling hits every state)" sequence)
  1643. (:tag "Type (cycling directly to DONE)" type))
  1644. "The available interpretation symbols for customizing `org-todo-keywords'.
  1645. Interested libraries should add to this list.")
  1646. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  1647. "List of TODO entry keyword sequences and their interpretation.
  1648. \\<org-mode-map>This is a list of sequences.
  1649. Each sequence starts with a symbol, either `sequence' or `type',
  1650. indicating if the keywords should be interpreted as a sequence of
  1651. action steps, or as different types of TODO items. The first
  1652. keywords are states requiring action - these states will select a headline
  1653. for inclusion into the global TODO list Org produces. If one of the
  1654. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  1655. signify that no further action is necessary. If \"|\" is not found,
  1656. the last keyword is treated as the only DONE state of the sequence.
  1657. The command `\\[org-todo]' cycles an entry through these states, and one
  1658. additional state where no keyword is present. For details about this
  1659. cycling, see the manual.
  1660. TODO keywords and interpretation can also be set on a per-file basis with
  1661. the special #+SEQ_TODO and #+TYP_TODO lines.
  1662. Each keyword can optionally specify a character for fast state selection
  1663. \(in combination with the variable `org-use-fast-todo-selection')
  1664. and specifiers for state change logging, using the same syntax that
  1665. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  1666. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  1667. indicates to record a time stamp each time this state is selected.
  1668. Each keyword may also specify if a timestamp or a note should be
  1669. recorded when entering or leaving the state, by adding additional
  1670. characters in the parenthesis after the keyword. This looks like this:
  1671. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  1672. record only the time of the state change. With X and Y being either
  1673. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  1674. Y when leaving the state if and only if the *target* state does not
  1675. define X. You may omit any of the fast-selection key or X or /Y,
  1676. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  1677. For backward compatibility, this variable may also be just a list
  1678. of keywords. In this case the interpretation (sequence or type) will be
  1679. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  1680. :group 'org-todo
  1681. :group 'org-keywords
  1682. :type '(choice
  1683. (repeat :tag "Old syntax, just keywords"
  1684. (string :tag "Keyword"))
  1685. (repeat :tag "New syntax"
  1686. (cons
  1687. (choice
  1688. :tag "Interpretation"
  1689. ;;Quick and dirty way to see
  1690. ;;`org-todo-interpretation'. This takes the
  1691. ;;place of item arguments
  1692. :convert-widget
  1693. (lambda (widget)
  1694. (widget-put widget
  1695. :args (mapcar
  1696. (lambda (x)
  1697. (widget-convert
  1698. (cons 'const x)))
  1699. org-todo-interpretation-widgets))
  1700. widget))
  1701. (repeat
  1702. (string :tag "Keyword"))))))
  1703. (defvar-local org-todo-keywords-1 nil
  1704. "All TODO and DONE keywords active in a buffer.")
  1705. (defvar org-todo-keywords-for-agenda nil)
  1706. (defvar org-done-keywords-for-agenda nil)
  1707. (defvar org-todo-keyword-alist-for-agenda nil)
  1708. (defvar org-tag-alist-for-agenda nil
  1709. "Alist of all tags from all agenda files.")
  1710. (defvar org-tag-groups-alist-for-agenda nil
  1711. "Alist of all groups tags from all current agenda files.")
  1712. (defvar-local org-tag-groups-alist nil)
  1713. (defvar org-agenda-contributing-files nil)
  1714. (defvar-local org-current-tag-alist nil
  1715. "Alist of all tag groups in current buffer.
  1716. This variable takes into consideration `org-tag-alist',
  1717. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  1718. (defvar-local org-not-done-keywords nil)
  1719. (defvar-local org-done-keywords nil)
  1720. (defvar-local org-todo-heads nil)
  1721. (defvar-local org-todo-sets nil)
  1722. (defvar-local org-todo-log-states nil)
  1723. (defvar-local org-todo-kwd-alist nil)
  1724. (defvar-local org-todo-key-alist nil)
  1725. (defvar-local org-todo-key-trigger nil)
  1726. (defcustom org-todo-interpretation 'sequence
  1727. "Controls how TODO keywords are interpreted.
  1728. This variable is in principle obsolete and is only used for
  1729. backward compatibility, if the interpretation of todo keywords is
  1730. not given already in `org-todo-keywords'. See that variable for
  1731. more information."
  1732. :group 'org-todo
  1733. :group 'org-keywords
  1734. :type '(choice (const sequence)
  1735. (const type)))
  1736. (defcustom org-use-fast-todo-selection 'auto
  1737. "\\<org-mode-map>\
  1738. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  1739. This variable describes if and under what circumstances the cycling
  1740. mechanism for TODO keywords will be replaced by a single-key, direct
  1741. selection scheme, where the choices are displayed in a little window.
  1742. When nil, fast selection is never used. This means that the command
  1743. will always switch to the next state.
  1744. When it is the symbol `auto', fast selection is whenever selection
  1745. keys have been defined.
  1746. `expert' is like `auto', but no special window with the keyword
  1747. will be shown, choices will only be listed in the prompt.
  1748. In all cases, the special interface is only used if access keys have
  1749. actually been assigned by the user, i.e. if keywords in the configuration
  1750. are followed by a letter in parenthesis, like TODO(t)."
  1751. :group 'org-todo
  1752. :set (lambda (var val)
  1753. (cond
  1754. ((eq var t) (set var 'auto))
  1755. ((eq var 'prefix) (set var nil))
  1756. (t (set var val))))
  1757. :type '(choice
  1758. (const :tag "Never" nil)
  1759. (const :tag "Automatically, when key letter have been defined" auto)
  1760. (const :tag "Automatically, but don't show the selection window" expert)))
  1761. (defcustom org-provide-todo-statistics t
  1762. "Non-nil means update todo statistics after insert and toggle.
  1763. ALL-HEADLINES means update todo statistics by including headlines
  1764. with no TODO keyword as well, counting them as not done.
  1765. A list of TODO keywords means the same, but skip keywords that are
  1766. not in this list.
  1767. When set to a list of two lists, the first list contains keywords
  1768. to consider as TODO keywords, the second list contains keywords
  1769. to consider as DONE keywords.
  1770. When this is set, todo statistics is updated in the parent of the
  1771. current entry each time a todo state is changed."
  1772. :group 'org-todo
  1773. :type '(choice
  1774. (const :tag "Yes, only for TODO entries" t)
  1775. (const :tag "Yes, including all entries" all-headlines)
  1776. (repeat :tag "Yes, for TODOs in this list"
  1777. (string :tag "TODO keyword"))
  1778. (list :tag "Yes, for TODOs and DONEs in these lists"
  1779. (repeat (string :tag "TODO keyword"))
  1780. (repeat (string :tag "DONE keyword")))
  1781. (other :tag "No TODO statistics" nil)))
  1782. (defcustom org-hierarchical-todo-statistics t
  1783. "Non-nil means TODO statistics covers just direct children.
  1784. When nil, all entries in the subtree are considered.
  1785. This has only an effect if `org-provide-todo-statistics' is set.
  1786. To set this to nil for only a single subtree, use a COOKIE_DATA
  1787. property and include the word \"recursive\" into the value."
  1788. :group 'org-todo
  1789. :type 'boolean)
  1790. (defcustom org-after-todo-state-change-hook nil
  1791. "Hook which is run after the state of a TODO item was changed.
  1792. The new state (a string with a TODO keyword, or nil) is available in the
  1793. Lisp variable `org-state'."
  1794. :group 'org-todo
  1795. :type 'hook)
  1796. (defvar org-blocker-hook nil
  1797. "Hook for functions that are allowed to block a state change.
  1798. Functions in this hook should not modify the buffer.
  1799. Each function gets as its single argument a property list,
  1800. see `org-trigger-hook' for more information about this list.
  1801. If any of the functions in this hook returns nil, the state change
  1802. is blocked.")
  1803. (defvar org-trigger-hook nil
  1804. "Hook for functions that are triggered by a state change.
  1805. Each function gets as its single argument a property list with at
  1806. least the following elements:
  1807. (:type type-of-change :position pos-at-entry-start
  1808. :from old-state :to new-state)
  1809. Depending on the type, more properties may be present.
  1810. This mechanism is currently implemented for:
  1811. TODO state changes
  1812. ------------------
  1813. :type todo-state-change
  1814. :from previous state (keyword as a string), or nil, or a symbol
  1815. `todo' or `done', to indicate the general type of state.
  1816. :to new state, like in :from")
  1817. (defcustom org-enforce-todo-dependencies nil
  1818. "Non-nil means undone TODO entries will block switching the parent to DONE.
  1819. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  1820. be blocked if any prior sibling is not yet done.
  1821. Finally, if the parent is blocked because of ordered siblings of its own,
  1822. the child will also be blocked."
  1823. :set (lambda (var val)
  1824. (set var val)
  1825. (if val
  1826. (add-hook 'org-blocker-hook
  1827. 'org-block-todo-from-children-or-siblings-or-parent)
  1828. (remove-hook 'org-blocker-hook
  1829. 'org-block-todo-from-children-or-siblings-or-parent)))
  1830. :group 'org-todo
  1831. :type 'boolean)
  1832. (defcustom org-enforce-todo-checkbox-dependencies nil
  1833. "Non-nil means unchecked boxes will block switching the parent to DONE.
  1834. When this is nil, checkboxes have no influence on switching TODO states.
  1835. When non-nil, you first need to check off all check boxes before the TODO
  1836. entry can be switched to DONE.
  1837. This variable needs to be set before org.el is loaded, and you need to
  1838. restart Emacs after a change to make the change effective. The only way
  1839. to change it while Emacs is running is through the customize interface."
  1840. :set (lambda (var val)
  1841. (set var val)
  1842. (if val
  1843. (add-hook 'org-blocker-hook
  1844. 'org-block-todo-from-checkboxes)
  1845. (remove-hook 'org-blocker-hook
  1846. 'org-block-todo-from-checkboxes)))
  1847. :group 'org-todo
  1848. :type 'boolean)
  1849. (defcustom org-treat-insert-todo-heading-as-state-change nil
  1850. "Non-nil means inserting a TODO heading is treated as state change.
  1851. So when the command `\\[org-insert-todo-heading]' is used, state change
  1852. logging will apply if appropriate. When nil, the new TODO item will
  1853. be inserted directly, and no logging will take place."
  1854. :group 'org-todo
  1855. :type 'boolean)
  1856. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  1857. "Non-nil means switching TODO states with S-cursor counts as state change.
  1858. This is the default behavior. However, setting this to nil allows a
  1859. convenient way to select a TODO state and bypass any logging associated
  1860. with that."
  1861. :group 'org-todo
  1862. :type 'boolean)
  1863. (defcustom org-todo-state-tags-triggers nil
  1864. "Tag changes that should be triggered by TODO state changes.
  1865. This is a list. Each entry is
  1866. (state-change (tag . flag) .......)
  1867. State-change can be a string with a state, and empty string to indicate the
  1868. state that has no TODO keyword, or it can be one of the symbols `todo'
  1869. or `done', meaning any not-done or done state, respectively."
  1870. :group 'org-todo
  1871. :group 'org-tags
  1872. :type '(repeat
  1873. (cons (choice :tag "When changing to"
  1874. (const :tag "Not-done state" todo)
  1875. (const :tag "Done state" done)
  1876. (string :tag "State"))
  1877. (repeat
  1878. (cons :tag "Tag action"
  1879. (string :tag "Tag")
  1880. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  1881. (defcustom org-log-done nil
  1882. "Information to record when a task moves to the DONE state.
  1883. Possible values are:
  1884. nil Don't add anything, just change the keyword
  1885. time Add a time stamp to the task
  1886. note Prompt for a note and add it with template `org-log-note-headings'
  1887. This option can also be set with on a per-file-basis with
  1888. #+STARTUP: nologdone
  1889. #+STARTUP: logdone
  1890. #+STARTUP: lognotedone
  1891. You can have local logging settings for a subtree by setting the LOGGING
  1892. property to one or more of these keywords."
  1893. :group 'org-todo
  1894. :group 'org-progress
  1895. :type '(choice
  1896. (const :tag "No logging" nil)
  1897. (const :tag "Record CLOSED timestamp" time)
  1898. (const :tag "Record CLOSED timestamp with note." note)))
  1899. ;; Normalize old uses of org-log-done.
  1900. (cond
  1901. ((eq org-log-done t) (setq org-log-done 'time))
  1902. ((and (listp org-log-done) (memq 'done org-log-done))
  1903. (setq org-log-done 'note)))
  1904. (defcustom org-log-reschedule nil
  1905. "Information to record when the scheduling date of a task is modified.
  1906. Possible values are:
  1907. nil Don't add anything, just change the date
  1908. time Add a time stamp to the task
  1909. note Prompt for a note and add it with template `org-log-note-headings'
  1910. This option can also be set with on a per-file-basis with
  1911. #+STARTUP: nologreschedule
  1912. #+STARTUP: logreschedule
  1913. #+STARTUP: lognotereschedule
  1914. You can have local logging settings for a subtree by setting the LOGGING
  1915. property to one or more of these keywords.
  1916. This variable has an effect when calling `org-schedule' or
  1917. `org-agenda-schedule' only."
  1918. :group 'org-todo
  1919. :group 'org-progress
  1920. :type '(choice
  1921. (const :tag "No logging" nil)
  1922. (const :tag "Record timestamp" time)
  1923. (const :tag "Record timestamp with note" note)))
  1924. (defcustom org-log-redeadline nil
  1925. "Information to record when the deadline date of a task is modified.
  1926. Possible values are:
  1927. nil Don't add anything, just change the date
  1928. time Add a time stamp to the task
  1929. note Prompt for a note and add it with template `org-log-note-headings'
  1930. This option can also be set with on a per-file-basis with
  1931. #+STARTUP: nologredeadline
  1932. #+STARTUP: logredeadline
  1933. #+STARTUP: lognoteredeadline
  1934. You can have local logging settings for a subtree by setting the LOGGING
  1935. property to one or more of these keywords.
  1936. This variable has an effect when calling `org-deadline' or
  1937. `org-agenda-deadline' only."
  1938. :group 'org-todo
  1939. :group 'org-progress
  1940. :type '(choice
  1941. (const :tag "No logging" nil)
  1942. (const :tag "Record timestamp" time)
  1943. (const :tag "Record timestamp with note." note)))
  1944. (defcustom org-log-note-clock-out nil
  1945. "Non-nil means record a note when clocking out of an item.
  1946. This can also be configured on a per-file basis by adding one of
  1947. the following lines anywhere in the buffer:
  1948. #+STARTUP: lognoteclock-out
  1949. #+STARTUP: nolognoteclock-out"
  1950. :group 'org-todo
  1951. :group 'org-progress
  1952. :type 'boolean)
  1953. (defcustom org-log-done-with-time t
  1954. "Non-nil means the CLOSED time stamp will contain date and time.
  1955. When nil, only the date will be recorded."
  1956. :group 'org-progress
  1957. :type 'boolean)
  1958. (defcustom org-log-note-headings
  1959. '((done . "CLOSING NOTE %t")
  1960. (state . "State %-12s from %-12S %t")
  1961. (note . "Note taken on %t")
  1962. (reschedule . "Rescheduled from %S on %t")
  1963. (delschedule . "Not scheduled, was %S on %t")
  1964. (redeadline . "New deadline from %S on %t")
  1965. (deldeadline . "Removed deadline, was %S on %t")
  1966. (refile . "Refiled on %t")
  1967. (clock-out . ""))
  1968. "Headings for notes added to entries.
  1969. The value is an alist, with the car being a symbol indicating the
  1970. note context, and the cdr is the heading to be used. The heading
  1971. may also be the empty string. The following placeholders can be
  1972. used:
  1973. %t a time stamp.
  1974. %T an active time stamp instead the default inactive one
  1975. %d a short-format time stamp.
  1976. %D an active short-format time stamp.
  1977. %s the new TODO state or time stamp (inactive), in double quotes.
  1978. %S the old TODO state or time stamp (inactive), in double quotes.
  1979. %u the user name.
  1980. %U full user name.
  1981. In fact, it is not a good idea to change the `state' entry,
  1982. because Agenda Log mode depends on the format of these entries."
  1983. :group 'org-todo
  1984. :group 'org-progress
  1985. :type '(list :greedy t
  1986. (cons (const :tag "Heading when closing an item" done) string)
  1987. (cons (const :tag
  1988. "Heading when changing todo state (todo sequence only)"
  1989. state) string)
  1990. (cons (const :tag "Heading when just taking a note" note) string)
  1991. (cons (const :tag "Heading when rescheduling" reschedule) string)
  1992. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  1993. (cons (const :tag "Heading when changing deadline" redeadline) string)
  1994. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  1995. (cons (const :tag "Heading when refiling" refile) string)
  1996. (cons (const :tag "Heading when clocking out" clock-out) string)))
  1997. (unless (assq 'note org-log-note-headings)
  1998. (push '(note . "%t") org-log-note-headings))
  1999. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2000. (defcustom org-log-into-drawer nil
  2001. "Non-nil means insert state change notes and time stamps into a drawer.
  2002. When nil, state changes notes will be inserted after the headline and
  2003. any scheduling and clock lines, but not inside a drawer.
  2004. The value of this variable should be the name of the drawer to use.
  2005. LOGBOOK is proposed as the default drawer for this purpose, you can
  2006. also set this to a string to define the drawer of your choice.
  2007. A value of t is also allowed, representing \"LOGBOOK\".
  2008. A value of t or nil can also be set with on a per-file-basis with
  2009. #+STARTUP: logdrawer
  2010. #+STARTUP: nologdrawer
  2011. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2012. will be ignored.
  2013. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2014. a subtree.
  2015. Do not check directly this variable in a Lisp program. Call
  2016. function `org-log-into-drawer' instead."
  2017. :group 'org-todo
  2018. :group 'org-progress
  2019. :type '(choice
  2020. (const :tag "Not into a drawer" nil)
  2021. (const :tag "LOGBOOK" t)
  2022. (string :tag "Other")))
  2023. (defun org-log-into-drawer ()
  2024. "Name of the log drawer, as a string, or nil.
  2025. This is the value of `org-log-into-drawer'. However, if the
  2026. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2027. be used instead of the default value."
  2028. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2029. (cond ((equal p "nil") nil)
  2030. ((equal p "t") "LOGBOOK")
  2031. ((stringp p) p)
  2032. (p "LOGBOOK")
  2033. ((stringp org-log-into-drawer) org-log-into-drawer)
  2034. (org-log-into-drawer "LOGBOOK"))))
  2035. (defcustom org-log-state-notes-insert-after-drawers nil
  2036. "Non-nil means insert state change notes after any drawers in entry.
  2037. Only the drawers that *immediately* follow the headline and the
  2038. deadline/scheduled line are skipped.
  2039. When nil, insert notes right after the heading and perhaps the line
  2040. with deadline/scheduling if present.
  2041. This variable will have no effect if `org-log-into-drawer' is
  2042. set."
  2043. :group 'org-todo
  2044. :group 'org-progress
  2045. :type 'boolean)
  2046. (defcustom org-log-states-order-reversed t
  2047. "Non-nil means the latest state note will be directly after heading.
  2048. When nil, the state change notes will be ordered according to time.
  2049. This option can also be set with on a per-file-basis with
  2050. #+STARTUP: logstatesreversed
  2051. #+STARTUP: nologstatesreversed"
  2052. :group 'org-todo
  2053. :group 'org-progress
  2054. :type 'boolean)
  2055. (defcustom org-todo-repeat-to-state nil
  2056. "The TODO state to which a repeater should return the repeating task.
  2057. By default this is the first task of a TODO sequence or the
  2058. previous state of a TYPE_TODO set. But you can specify to use
  2059. the previous state in a TODO sequence or a string.
  2060. Alternatively, you can set the :REPEAT_TO_STATE: property of the
  2061. entry, which has precedence over this option."
  2062. :group 'org-todo
  2063. :version "24.1"
  2064. :type '(choice (const :tag "Use the previous TODO state" t)
  2065. (const :tag "Use the head of the TODO sequence" nil)
  2066. (string :tag "Use a specific TODO state")))
  2067. (defcustom org-log-repeat 'time
  2068. "Non-nil means record moving through the DONE state when triggering repeat.
  2069. An auto-repeating task is immediately switched back to TODO when
  2070. marked DONE. If you are not logging state changes (by adding \"@\"
  2071. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2072. record a closing note, there will be no record of the task moving
  2073. through DONE. This variable forces taking a note anyway.
  2074. nil Don't force a record
  2075. time Record a time stamp
  2076. note Prompt for a note and add it with template `org-log-note-headings'
  2077. This option can also be set with on a per-file-basis with
  2078. #+STARTUP: nologrepeat
  2079. #+STARTUP: logrepeat
  2080. #+STARTUP: lognoterepeat
  2081. You can have local logging settings for a subtree by setting the LOGGING
  2082. property to one or more of these keywords."
  2083. :group 'org-todo
  2084. :group 'org-progress
  2085. :type '(choice
  2086. (const :tag "Don't force a record" nil)
  2087. (const :tag "Force recording the DONE state" time)
  2088. (const :tag "Force recording a note with the DONE state" note)))
  2089. (defcustom org-todo-repeat-hook nil
  2090. "Hook that is run after a task has been repeated."
  2091. :package-version '(Org . "9.2")
  2092. :group 'org-todo
  2093. :type 'hook)
  2094. (defgroup org-priorities nil
  2095. "Priorities in Org mode."
  2096. :tag "Org Priorities"
  2097. :group 'org-todo)
  2098. (defvaralias 'org-enable-priority-commands 'org-priority-enable-commands)
  2099. (defcustom org-priority-enable-commands t
  2100. "Non-nil means priority commands are active.
  2101. When nil, these commands will be disabled, so that you never accidentally
  2102. set a priority."
  2103. :group 'org-priorities
  2104. :type 'boolean)
  2105. (defvaralias 'org-highest-priority 'org-priority-highest)
  2106. (defcustom org-priority-highest ?A
  2107. "The highest priority of TODO items.
  2108. A character like ?A, ?B, etc., or a numeric value like 1, 2, etc.
  2109. The default is the character ?A, which is 65 as a numeric value.
  2110. If you set `org-priority-highest' to a numeric value inferior to
  2111. 65, Org assumes you want to use digits for the priority cookie.
  2112. If you set it to >=65, Org assumes you want to use alphabetical
  2113. characters.
  2114. In both cases, the value of `org-priority-highest' must be
  2115. smaller than `org-priority-lowest': for example, if \"A\" is the
  2116. highest priority, it is smaller than the lowest \"C\" priority:
  2117. 65 < 67."
  2118. :group 'org-priorities
  2119. :type '(choice
  2120. (character :tag "Character")
  2121. (integer :tag "Integer (< 65)")))
  2122. (defvaralias 'org-lowest-priority 'org-priority-lowest)
  2123. (defcustom org-priority-lowest ?C
  2124. "The lowest priority of TODO items.
  2125. A character like ?C, ?B, etc., or a numeric value like 9, 8, etc.
  2126. The default is the character ?C, which is 67 as a numeric value.
  2127. If you set `org-priority-lowest' to a numeric value inferior to
  2128. 65, Org assumes you want to use digits for the priority cookie.
  2129. If you set it to >=65, Org assumes you want to use alphabetical
  2130. characters.
  2131. In both cases, the value of `org-priority-lowest' must be greater
  2132. than `org-priority-highest': for example, if \"C\" is the lowest
  2133. priority, it is greater than the highest \"A\" priority: 67 >
  2134. 65."
  2135. :group 'org-priorities
  2136. :type '(choice
  2137. (character :tag "Character")
  2138. (integer :tag "Integer (< 65)")))
  2139. (defvaralias 'org-default-priority 'org-priority-default)
  2140. (defcustom org-priority-default ?B
  2141. "The default priority of TODO items.
  2142. This is the priority an item gets if no explicit priority is given.
  2143. When starting to cycle on an empty priority the first step in the cycle
  2144. depends on `org-priority-start-cycle-with-default'. The resulting first
  2145. step priority must not exceed the range from `org-priority-highest' to
  2146. `org-priority-lowest' which means that `org-priority-default' has to be
  2147. in this range exclusive or inclusive to the range boundaries. Else the
  2148. first step refuses to set the default and the second will fall back on
  2149. \(depending on the command used) the highest or lowest priority."
  2150. :group 'org-priorities
  2151. :type '(choice
  2152. (character :tag "Character")
  2153. (integer :tag "Integer (< 65)")))
  2154. (defcustom org-priority-start-cycle-with-default t
  2155. "Non-nil means start with default priority when starting to cycle.
  2156. When this is nil, the first step in the cycle will be (depending on the
  2157. command used) one higher or lower than the default priority.
  2158. See also `org-priority-default'."
  2159. :group 'org-priorities
  2160. :type 'boolean)
  2161. (defvaralias 'org-get-priority-function 'org-priority-get-priority-function)
  2162. (defcustom org-priority-get-priority-function nil
  2163. "Function to extract the priority from a string.
  2164. The string is normally the headline. If this is nil, Org
  2165. computes the priority from the priority cookie like [#A] in the
  2166. headline. It returns an integer, increasing by 1000 for each
  2167. priority level.
  2168. The user can set a different function here, which should take a
  2169. string as an argument and return the numeric priority."
  2170. :group 'org-priorities
  2171. :version "24.1"
  2172. :type '(choice
  2173. (const nil)
  2174. (function)))
  2175. (defgroup org-time nil
  2176. "Options concerning time stamps and deadlines in Org mode."
  2177. :tag "Org Time"
  2178. :group 'org)
  2179. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2180. "Number of minutes to round time stamps to.
  2181. \\<org-mode-map>\
  2182. These are two values, the first applies when first creating a time stamp.
  2183. The second applies when changing it with the commands `S-up' and `S-down'.
  2184. When changing the time stamp, this means that it will change in steps
  2185. of N minutes, as given by the second value.
  2186. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2187. numbers should be factors of 60, so for example 5, 10, 15.
  2188. When this is larger than 1, you can still force an exact time stamp by using
  2189. a double prefix argument to a time stamp command like \
  2190. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2191. and by using a prefix arg to `S-up/down' to specify the exact number
  2192. of minutes to shift."
  2193. :group 'org-time
  2194. :get (lambda (var) ; Make sure both elements are there
  2195. (if (integerp (default-value var))
  2196. (list (default-value var) 5)
  2197. (default-value var)))
  2198. :type '(list
  2199. (integer :tag "when inserting times")
  2200. (integer :tag "when modifying times")))
  2201. ;; Normalize old customizations of this variable.
  2202. (when (integerp org-time-stamp-rounding-minutes)
  2203. (setq org-time-stamp-rounding-minutes
  2204. (list org-time-stamp-rounding-minutes
  2205. org-time-stamp-rounding-minutes)))
  2206. (defcustom org-display-custom-times nil
  2207. "Non-nil means overlay custom formats over all time stamps.
  2208. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2209. To turn this on on a per-file basis, insert anywhere in the file:
  2210. #+STARTUP: customtime"
  2211. :group 'org-time
  2212. :set 'set-default
  2213. :type 'sexp)
  2214. (make-variable-buffer-local 'org-display-custom-times)
  2215. (defcustom org-time-stamp-custom-formats
  2216. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2217. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2218. These are overlaid over the default ISO format if the variable
  2219. `org-display-custom-times' is set. Time like %H:%M should be at the
  2220. end of the second format. The custom formats are also honored by export
  2221. commands, if custom time display is turned on at the time of export."
  2222. :group 'org-time
  2223. :type 'sexp)
  2224. (defun org-time-stamp-format (&optional long inactive)
  2225. "Get the right format for a time string."
  2226. (let ((f (if long (cdr org-time-stamp-formats)
  2227. (car org-time-stamp-formats))))
  2228. (if inactive
  2229. (concat "[" (substring f 1 -1) "]")
  2230. f)))
  2231. (defcustom org-deadline-warning-days 14
  2232. "Number of days before expiration during which a deadline becomes active.
  2233. This variable governs the display in sparse trees and in the agenda.
  2234. When 0 or negative, it means use this number (the absolute value of it)
  2235. even if a deadline has a different individual lead time specified.
  2236. Custom commands can set this variable in the options section."
  2237. :group 'org-time
  2238. :group 'org-agenda-daily/weekly
  2239. :type 'integer)
  2240. (defcustom org-scheduled-delay-days 0
  2241. "Number of days before a scheduled item becomes active.
  2242. This variable governs the display in sparse trees and in the agenda.
  2243. The default value (i.e. 0) means: don't delay scheduled item.
  2244. When negative, it means use this number (the absolute value of it)
  2245. even if a scheduled item has a different individual delay time
  2246. specified.
  2247. Custom commands can set this variable in the options section."
  2248. :group 'org-time
  2249. :group 'org-agenda-daily/weekly
  2250. :version "24.4"
  2251. :package-version '(Org . "8.0")
  2252. :type 'integer)
  2253. (defcustom org-read-date-prefer-future t
  2254. "Non-nil means assume future for incomplete date input from user.
  2255. This affects the following situations:
  2256. 1. The user gives a month but not a year.
  2257. For example, if it is April and you enter \"feb 2\", this will be read
  2258. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2259. 2. The user gives a day, but no month.
  2260. For example, if today is the 15th, and you enter \"3\", Org will read
  2261. this as the third of *next* month. However, if you enter \"17\",
  2262. it will be considered as *this* month.
  2263. If you set this variable to the symbol `time', then also the following
  2264. will work:
  2265. 3. If the user gives a time.
  2266. If the time is before now, it will be interpreted as tomorrow.
  2267. Currently none of this works for ISO week specifications.
  2268. When this option is nil, the current day, month and year will always be
  2269. used as defaults.
  2270. See also `org-agenda-jump-prefer-future'."
  2271. :group 'org-time
  2272. :type '(choice
  2273. (const :tag "Never" nil)
  2274. (const :tag "Check month and day" t)
  2275. (const :tag "Check month, day, and time" time)))
  2276. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2277. "Should the agenda jump command prefer the future for incomplete dates?
  2278. The default is to do the same as configured in `org-read-date-prefer-future'.
  2279. But you can also set a deviating value here.
  2280. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2281. :group 'org-agenda
  2282. :group 'org-time
  2283. :version "24.1"
  2284. :type '(choice
  2285. (const :tag "Use org-read-date-prefer-future"
  2286. org-read-date-prefer-future)
  2287. (const :tag "Never" nil)
  2288. (const :tag "Always" t)))
  2289. (defcustom org-read-date-force-compatible-dates t
  2290. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2291. Depending on the system Emacs is running on, certain dates cannot
  2292. be represented with the type used internally to represent time.
  2293. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2294. correctly. Some systems allow for earlier dates, some for later,
  2295. some for both. One way to find out is to insert any date into an
  2296. Org buffer, putting the cursor on the year and hitting S-up and
  2297. S-down to test the range.
  2298. When this variable is set to t, the date/time prompt will not let
  2299. you specify dates outside the 1970-2037 range, so it is certain that
  2300. these dates will work in whatever version of Emacs you are
  2301. running, and also that you can move a file from one Emacs implementation
  2302. to another. Whenever Org is forcing the year for you, it will display
  2303. a message and beep.
  2304. When this variable is nil, Org will check if the date is
  2305. representable in the specific Emacs implementation you are using.
  2306. If not, it will force a year, usually the current year, and beep
  2307. to remind you. Currently this setting is not recommended because
  2308. the likelihood that you will open your Org files in an Emacs that
  2309. has limited date range is not negligible.
  2310. A workaround for this problem is to use diary sexp dates for time
  2311. stamps outside of this range."
  2312. :group 'org-time
  2313. :version "24.1"
  2314. :type 'boolean)
  2315. (defcustom org-read-date-display-live t
  2316. "Non-nil means display current interpretation of date prompt live.
  2317. This display will be in an overlay, in the minibuffer. Note that
  2318. live display is only active when `org-read-date-popup-calendar'
  2319. is non-nil."
  2320. :group 'org-time
  2321. :type 'boolean)
  2322. (defvaralias 'org-popup-calendar-for-date-prompt
  2323. 'org-read-date-popup-calendar)
  2324. (defcustom org-read-date-popup-calendar t
  2325. "Non-nil means pop up a calendar when prompting for a date.
  2326. In the calendar, the date can be selected with mouse-1. However, the
  2327. minibuffer will also be active, and you can simply enter the date as well.
  2328. When nil, only the minibuffer will be available."
  2329. :group 'org-time
  2330. :type 'boolean)
  2331. (defcustom org-extend-today-until 0
  2332. "The hour when your day really ends. Must be an integer.
  2333. This has influence for the following applications:
  2334. - When switching the agenda to \"today\". If it is still earlier than
  2335. the time given here, the day recognized as TODAY is actually yesterday.
  2336. - When a date is read from the user and it is still before the time given
  2337. here, the current date and time will be assumed to be yesterday, 23:59.
  2338. Also, timestamps inserted in capture templates follow this rule.
  2339. IMPORTANT: This is a feature whose implementation is and likely will
  2340. remain incomplete. Really, it is only here because past midnight seems to
  2341. be the favorite working time of John Wiegley :-)"
  2342. :group 'org-time
  2343. :type 'integer)
  2344. (defcustom org-use-effective-time nil
  2345. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2346. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2347. \"effective time\" of any timestamps between midnight and 8am will be
  2348. 23:59 of the previous day."
  2349. :group 'org-time
  2350. :version "24.1"
  2351. :type 'boolean)
  2352. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2353. "When non-nil, use the last clock out time for `org-todo'.
  2354. Note that this option has precedence over the combined use of
  2355. `org-use-effective-time' and `org-extend-today-until'."
  2356. :group 'org-time
  2357. :version "24.4"
  2358. :package-version '(Org . "8.0")
  2359. :type 'boolean)
  2360. (defcustom org-edit-timestamp-down-means-later nil
  2361. "Non-nil means S-down will increase the time in a time stamp.
  2362. When nil, S-up will increase."
  2363. :group 'org-time
  2364. :type 'boolean)
  2365. (defcustom org-calendar-follow-timestamp-change t
  2366. "Non-nil means make the calendar window follow timestamp changes.
  2367. When a timestamp is modified and the calendar window is visible, it will be
  2368. moved to the new date."
  2369. :group 'org-time
  2370. :type 'boolean)
  2371. (defgroup org-tags nil
  2372. "Options concerning tags in Org mode."
  2373. :tag "Org Tags"
  2374. :group 'org)
  2375. (defcustom org-tag-alist nil
  2376. "Default tags available in Org files.
  2377. The value of this variable is an alist. Associations either:
  2378. (TAG)
  2379. (TAG . SELECT)
  2380. (SPECIAL)
  2381. where TAG is a tag as a string, SELECT is character, used to
  2382. select that tag through the fast tag selection interface, and
  2383. SPECIAL is one of the following keywords: `:startgroup',
  2384. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2385. `:newline'. These keywords are used to define a hierarchy of
  2386. tags. See manual for details.
  2387. When this variable is nil, Org mode bases tag input on what is
  2388. already in the buffer. The value can be overridden locally by
  2389. using a TAGS keyword, e.g.,
  2390. #+TAGS: tag1 tag2
  2391. See also `org-tag-persistent-alist' to sidestep this behavior."
  2392. :group 'org-tags
  2393. :type '(repeat
  2394. (choice
  2395. (cons :tag "Tag with key"
  2396. (string :tag "Tag name")
  2397. (character :tag "Access char"))
  2398. (list :tag "Tag" (string :tag "Tag name"))
  2399. (const :tag "Start radio group" (:startgroup))
  2400. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2401. (const :tag "Group tags delimiter" (:grouptags))
  2402. (const :tag "End radio group" (:endgroup))
  2403. (const :tag "End tag group, non distinct" (:endgrouptag))
  2404. (const :tag "New line" (:newline)))))
  2405. (defcustom org-tag-persistent-alist nil
  2406. "Tags always available in Org files.
  2407. The value of this variable is an alist. Associations either:
  2408. (TAG)
  2409. (TAG . SELECT)
  2410. (SPECIAL)
  2411. where TAG is a tag as a string, SELECT is a character, used to
  2412. select that tag through the fast tag selection interface, and
  2413. SPECIAL is one of the following keywords: `:startgroup',
  2414. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2415. `:newline'. These keywords are used to define a hierarchy of
  2416. tags. See manual for details.
  2417. Unlike to `org-tag-alist', tags defined in this variable do not
  2418. depend on a local TAGS keyword. Instead, to disable these tags
  2419. on a per-file basis, insert anywhere in the file:
  2420. #+STARTUP: noptag"
  2421. :group 'org-tags
  2422. :type '(repeat
  2423. (choice
  2424. (cons :tag "Tag with key"
  2425. (string :tag "Tag name")
  2426. (character :tag "Access char"))
  2427. (list :tag "Tag" (string :tag "Tag name"))
  2428. (const :tag "Start radio group" (:startgroup))
  2429. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2430. (const :tag "Group tags delimiter" (:grouptags))
  2431. (const :tag "End radio group" (:endgroup))
  2432. (const :tag "End tag group, non distinct" (:endgrouptag))
  2433. (const :tag "New line" (:newline)))))
  2434. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2435. "If non-nil, always offer completion for all tags of all agenda files.
  2436. Setting this variable locally allows for dynamic generation of tag
  2437. completions in capture buffers.
  2438. (add-hook \\='org-capture-mode-hook
  2439. (lambda ()
  2440. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  2441. :group 'org-tags
  2442. :version "24.1"
  2443. :type 'boolean)
  2444. (defvar org-file-tags nil
  2445. "List of tags that can be inherited by all entries in the file.
  2446. The tags will be inherited if the variable `org-use-tag-inheritance'
  2447. says they should be.
  2448. This variable is populated from #+FILETAGS lines.")
  2449. (defcustom org-use-fast-tag-selection 'auto
  2450. "Non-nil means use fast tag selection scheme.
  2451. This is a special interface to select and deselect tags with single keys.
  2452. When nil, fast selection is never used.
  2453. When the symbol `auto', fast selection is used if and only if selection
  2454. characters for tags have been configured, either through the variable
  2455. `org-tag-alist' or through a #+TAGS line in the buffer.
  2456. When t, fast selection is always used and selection keys are assigned
  2457. automatically if necessary."
  2458. :group 'org-tags
  2459. :type '(choice
  2460. (const :tag "Always" t)
  2461. (const :tag "Never" nil)
  2462. (const :tag "When selection characters are configured" auto)))
  2463. (defcustom org-fast-tag-selection-single-key nil
  2464. "Non-nil means fast tag selection exits after first change.
  2465. When nil, you have to press RET to exit it.
  2466. During fast tag selection, you can toggle this flag with `C-c'.
  2467. This variable can also have the value `expert'. In this case, the window
  2468. displaying the tags menu is not even shown, until you press `C-c' again."
  2469. :group 'org-tags
  2470. :type '(choice
  2471. (const :tag "No" nil)
  2472. (const :tag "Yes" t)
  2473. (const :tag "Expert" expert)))
  2474. (defvar org-fast-tag-selection-include-todo nil
  2475. "Non-nil means fast tags selection interface will also offer TODO states.
  2476. This is an undocumented feature, you should not rely on it.")
  2477. (defcustom org-tags-column -77
  2478. "The column to which tags should be indented in a headline.
  2479. If this number is positive, it specifies the column. If it is negative,
  2480. it means that the tags should be flushright to that column. For example,
  2481. -80 works well for a normal 80 character screen.
  2482. When 0, place tags directly after headline text, with only one space in
  2483. between."
  2484. :group 'org-tags
  2485. :type 'integer)
  2486. (defcustom org-auto-align-tags t
  2487. "Non-nil keeps tags aligned when modifying headlines.
  2488. Some operations (i.e. demoting) change the length of a headline and
  2489. therefore shift the tags around. With this option turned on, after
  2490. each such operation the tags are again aligned to `org-tags-column'."
  2491. :group 'org-tags
  2492. :type 'boolean)
  2493. (defcustom org-use-tag-inheritance t
  2494. "Non-nil means tags in levels apply also for sublevels.
  2495. When nil, only the tags directly given in a specific line apply there.
  2496. This may also be a list of tags that should be inherited, or a regexp that
  2497. matches tags that should be inherited. Additional control is possible
  2498. with the variable `org-tags-exclude-from-inheritance' which gives an
  2499. explicit list of tags to be excluded from inheritance, even if the value of
  2500. `org-use-tag-inheritance' would select it for inheritance.
  2501. If this option is t, a match early-on in a tree can lead to a large
  2502. number of matches in the subtree when constructing the agenda or creating
  2503. a sparse tree. If you only want to see the first match in a tree during
  2504. a search, check out the variable `org-tags-match-list-sublevels'."
  2505. :group 'org-tags
  2506. :type '(choice
  2507. (const :tag "Not" nil)
  2508. (const :tag "Always" t)
  2509. (repeat :tag "Specific tags" (string :tag "Tag"))
  2510. (regexp :tag "Tags matched by regexp")))
  2511. (defcustom org-tags-exclude-from-inheritance nil
  2512. "List of tags that should never be inherited.
  2513. This is a way to exclude a few tags from inheritance. For way to do
  2514. the opposite, to actively allow inheritance for selected tags,
  2515. see the variable `org-use-tag-inheritance'."
  2516. :group 'org-tags
  2517. :type '(repeat (string :tag "Tag")))
  2518. (defun org-tag-inherit-p (tag)
  2519. "Check if TAG is one that should be inherited."
  2520. (cond
  2521. ((member tag org-tags-exclude-from-inheritance) nil)
  2522. ((eq org-use-tag-inheritance t) t)
  2523. ((not org-use-tag-inheritance) nil)
  2524. ((stringp org-use-tag-inheritance)
  2525. (string-match org-use-tag-inheritance tag))
  2526. ((listp org-use-tag-inheritance)
  2527. (member tag org-use-tag-inheritance))
  2528. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  2529. (defcustom org-tags-match-list-sublevels t
  2530. "Non-nil means list also sublevels of headlines matching a search.
  2531. This variable applies to tags/property searches, and also to stuck
  2532. projects because this search is based on a tags match as well.
  2533. When set to the symbol `indented', sublevels are indented with
  2534. leading dots.
  2535. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  2536. the sublevels of a headline matching a tag search often also match
  2537. the same search. Listing all of them can create very long lists.
  2538. Setting this variable to nil causes subtrees of a match to be skipped.
  2539. This variable is semi-obsolete and probably should always be true. It
  2540. is better to limit inheritance to certain tags using the variables
  2541. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  2542. :group 'org-tags
  2543. :type '(choice
  2544. (const :tag "No, don't list them" nil)
  2545. (const :tag "Yes, do list them" t)
  2546. (const :tag "List them, indented with leading dots" indented)))
  2547. (defcustom org-tags-sort-function nil
  2548. "When set, tags are sorted using this function as a comparator."
  2549. :group 'org-tags
  2550. :type '(choice
  2551. (const :tag "No sorting" nil)
  2552. (const :tag "Alphabetical" string-collate-lessp)
  2553. (const :tag "Reverse alphabetical" org-string-collate-greaterp)
  2554. (function :tag "Custom function" nil)))
  2555. (defvar org-tags-history nil
  2556. "History of minibuffer reads for tags.")
  2557. (defvar org-last-tags-completion-table nil
  2558. "The last used completion table for tags.")
  2559. (defvar org-after-tags-change-hook nil
  2560. "Hook that is run after the tags in a line have changed.")
  2561. (defgroup org-properties nil
  2562. "Options concerning properties in Org mode."
  2563. :tag "Org Properties"
  2564. :group 'org)
  2565. (defcustom org-property-format "%-10s %s"
  2566. "How property key/value pairs should be formatted by `indent-line'.
  2567. When `indent-line' hits a property definition, it will format the line
  2568. according to this format, mainly to make sure that the values are
  2569. lined-up with respect to each other."
  2570. :group 'org-properties
  2571. :type 'string)
  2572. (defcustom org-properties-postprocess-alist nil
  2573. "Alist of properties and functions to adjust inserted values.
  2574. Elements of this alist must be of the form
  2575. ([string] [function])
  2576. where [string] must be a property name and [function] must be a
  2577. lambda expression: this lambda expression must take one argument,
  2578. the value to adjust, and return the new value as a string.
  2579. For example, this element will allow the property \"Remaining\"
  2580. to be updated wrt the relation between the \"Effort\" property
  2581. and the clock summary:
  2582. ((\"Remaining\" (lambda(value)
  2583. (let ((clocksum (org-clock-sum-current-item))
  2584. (effort (org-duration-to-minutes
  2585. (org-entry-get (point) \"Effort\"))))
  2586. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  2587. :group 'org-properties
  2588. :version "24.1"
  2589. :type '(alist :key-type (string :tag "Property")
  2590. :value-type (function :tag "Function")))
  2591. (defcustom org-use-property-inheritance nil
  2592. "Non-nil means properties apply also for sublevels.
  2593. This setting is chiefly used during property searches. Turning it on can
  2594. cause significant overhead when doing a search, which is why it is not
  2595. on by default.
  2596. When nil, only the properties directly given in the current entry count.
  2597. When t, every property is inherited. The value may also be a list of
  2598. properties that should have inheritance, or a regular expression matching
  2599. properties that should be inherited.
  2600. However, note that some special properties use inheritance under special
  2601. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  2602. and the properties ending in \"_ALL\" when they are used as descriptor
  2603. for valid values of a property.
  2604. Note for programmers:
  2605. When querying an entry with `org-entry-get', you can control if inheritance
  2606. should be used. By default, `org-entry-get' looks only at the local
  2607. properties. You can request inheritance by setting the inherit argument
  2608. to t (to force inheritance) or to `selective' (to respect the setting
  2609. in this variable)."
  2610. :group 'org-properties
  2611. :type '(choice
  2612. (const :tag "Not" nil)
  2613. (const :tag "Always" t)
  2614. (repeat :tag "Specific properties" (string :tag "Property"))
  2615. (regexp :tag "Properties matched by regexp")))
  2616. (defun org-property-inherit-p (property)
  2617. "Return a non-nil value if PROPERTY should be inherited."
  2618. (cond
  2619. ((eq org-use-property-inheritance t) t)
  2620. ((not org-use-property-inheritance) nil)
  2621. ((stringp org-use-property-inheritance)
  2622. (string-match org-use-property-inheritance property))
  2623. ((listp org-use-property-inheritance)
  2624. (member-ignore-case property org-use-property-inheritance))
  2625. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  2626. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  2627. "The default column format, if no other format has been defined.
  2628. This variable can be set on the per-file basis by inserting a line
  2629. #+COLUMNS: %25ITEM ....."
  2630. :group 'org-properties
  2631. :type 'string)
  2632. (defcustom org-columns-default-format-for-agenda nil
  2633. "The default column format in an agenda buffer.
  2634. This will be used for column view in the agenda unless a format has
  2635. been set by adding `org-overriding-columns-format' to the local
  2636. settings list of a custom agenda view. When nil, the columns format
  2637. for the first item in the agenda list will be used, or as a fall-back,
  2638. `org-columns-default-format'."
  2639. :group 'org-properties
  2640. :type '(choice
  2641. (const :tag "No default" nil)
  2642. (string :tag "Format string")))
  2643. (defcustom org-columns-ellipses ".."
  2644. "The ellipses to be used when a field in column view is truncated.
  2645. When this is the empty string, as many characters as possible are shown,
  2646. but then there will be no visual indication that the field has been truncated.
  2647. When this is a string of length N, the last N characters of a truncated
  2648. field are replaced by this string. If the column is narrower than the
  2649. ellipses string, only part of the ellipses string will be shown."
  2650. :group 'org-properties
  2651. :type 'string)
  2652. (defconst org-global-properties-fixed
  2653. '(("VISIBILITY_ALL" . "folded children content all")
  2654. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  2655. "List of property/value pairs that can be inherited by any entry.
  2656. These are fixed values, for the preset properties. The user variable
  2657. that can be used to add to this list is `org-global-properties'.
  2658. The entries in this list are cons cells where the car is a property
  2659. name and cdr is a string with the value. If the value represents
  2660. multiple items like an \"_ALL\" property, separate the items by
  2661. spaces.")
  2662. (defcustom org-global-properties nil
  2663. "List of property/value pairs that can be inherited by any entry.
  2664. This list will be combined with the constant `org-global-properties-fixed'.
  2665. The entries in this list are cons cells where the car is a property
  2666. name and cdr is a string with the value.
  2667. Buffer local properties are added either by a document property drawer
  2668. :PROPERTIES:
  2669. :NAME: VALUE
  2670. :END:
  2671. or by adding lines like
  2672. #+PROPERTY: NAME VALUE"
  2673. :group 'org-properties
  2674. :type '(repeat
  2675. (cons (string :tag "Property")
  2676. (string :tag "Value"))))
  2677. (defvar-local org-keyword-properties nil
  2678. "List of property/value pairs inherited by any entry.
  2679. Valid for the current buffer. This variable is populated from
  2680. PROPERTY keywords.
  2681. Note that properties are defined also in property drawers.
  2682. Properties defined there take precedence over properties defined
  2683. as keywords.")
  2684. (defgroup org-agenda nil
  2685. "Options concerning agenda views in Org mode."
  2686. :tag "Org Agenda"
  2687. :group 'org)
  2688. (defvar-local org-category nil
  2689. "Variable used by Org files to set a category for agenda display.
  2690. There are multiple ways to set the category. One way is to set
  2691. it in the document property drawer. For example:
  2692. :PROPERTIES:
  2693. :CATEGORY: ELisp
  2694. :END:
  2695. Other ways to define it is as an Emacs file variable, for example
  2696. # -*- mode: org; org-category: \"ELisp\"
  2697. or for the file to contain a special line:
  2698. #+CATEGORY: ELisp
  2699. If the file does not specify a category, then file's base name
  2700. is used instead.")
  2701. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  2702. (defcustom org-agenda-files nil
  2703. "The files to be used for agenda display.
  2704. If an entry is a directory, all files in that directory that are matched
  2705. by `org-agenda-file-regexp' will be part of the file list.
  2706. If the value of the variable is not a list but a single file name, then
  2707. the list of agenda files is actually stored and maintained in that file,
  2708. one agenda file per line. In this file paths can be given relative to
  2709. `org-directory'. Tilde expansion and environment variable substitution
  2710. are also made.
  2711. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  2712. and removed with `\\[org-remove-file]'."
  2713. :group 'org-agenda
  2714. :type '(choice
  2715. (repeat :tag "List of files and directories" file)
  2716. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  2717. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  2718. "Regular expression to match files for `org-agenda-files'.
  2719. If any element in the list in that variable contains a directory instead
  2720. of a normal file, all files in that directory that are matched by this
  2721. regular expression will be included."
  2722. :group 'org-agenda
  2723. :type 'regexp)
  2724. (defvaralias 'org-agenda-multi-occur-extra-files
  2725. 'org-agenda-text-search-extra-files)
  2726. (defcustom org-agenda-text-search-extra-files nil
  2727. "List of extra files to be searched by text search commands.
  2728. These files will be searched in addition to the agenda files by the
  2729. commands `org-search-view' (`\\[org-agenda] s') \
  2730. and `org-occur-in-agenda-files'.
  2731. Note that these files will only be searched for text search commands,
  2732. not for the other agenda views like todo lists, tag searches or the weekly
  2733. agenda. This variable is intended to list notes and possibly archive files
  2734. that should also be searched by these two commands.
  2735. In fact, if the first element in the list is the symbol `agenda-archives',
  2736. then all archive files of all agenda files will be added to the search
  2737. scope."
  2738. :group 'org-agenda
  2739. :type '(set :greedy t
  2740. (const :tag "Agenda Archives" agenda-archives)
  2741. (repeat :inline t (file))))
  2742. (defcustom org-agenda-skip-unavailable-files nil
  2743. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  2744. A nil value means to remove them, after a query, from the list."
  2745. :group 'org-agenda
  2746. :type 'boolean)
  2747. (defgroup org-latex nil
  2748. "Options for embedding LaTeX code into Org mode."
  2749. :tag "Org LaTeX"
  2750. :group 'org)
  2751. (defcustom org-format-latex-options
  2752. '(:foreground default :background default :scale 1.0
  2753. :html-foreground "Black" :html-background "Transparent"
  2754. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  2755. "Options for creating images from LaTeX fragments.
  2756. This is a property list with the following properties:
  2757. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  2758. `default' means use the foreground of the default face.
  2759. `auto' means use the foreground from the text face.
  2760. :background the background color, or \"Transparent\".
  2761. `default' means use the background of the default face.
  2762. `auto' means use the background from the text face.
  2763. :scale a scaling factor for the size of the images, to get more pixels
  2764. :html-foreground, :html-background, :html-scale
  2765. the same numbers for HTML export.
  2766. :matchers a list indicating which matchers should be used to
  2767. find LaTeX fragments. Valid members of this list are:
  2768. \"begin\" find environments
  2769. \"$1\" find single characters surrounded by $.$
  2770. \"$\" find math expressions surrounded by $...$
  2771. \"$$\" find math expressions surrounded by $$....$$
  2772. \"\\(\" find math expressions surrounded by \\(...\\)
  2773. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  2774. :group 'org-latex
  2775. :type 'plist)
  2776. (defcustom org-format-latex-signal-error t
  2777. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  2778. When nil, just push out a message."
  2779. :group 'org-latex
  2780. :version "24.1"
  2781. :type 'boolean)
  2782. (defcustom org-latex-to-mathml-jar-file nil
  2783. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  2784. Use this to specify additional executable file say a jar file.
  2785. When using MathToWeb as the converter, specify the full-path to
  2786. your mathtoweb.jar file."
  2787. :group 'org-latex
  2788. :version "24.1"
  2789. :type '(choice
  2790. (const :tag "None" nil)
  2791. (file :tag "JAR file" :must-match t)))
  2792. (defcustom org-latex-to-mathml-convert-command nil
  2793. "Command to convert LaTeX fragments to MathML.
  2794. Replace format-specifiers in the command as noted below and use
  2795. `shell-command' to convert LaTeX to MathML.
  2796. %j: Executable file in fully expanded form as specified by
  2797. `org-latex-to-mathml-jar-file'.
  2798. %I: Input LaTeX file in fully expanded form.
  2799. %i: The latex fragment to be converted.
  2800. %o: Output MathML file.
  2801. This command is used by `org-create-math-formula'.
  2802. When using MathToWeb as the converter, set this option to
  2803. \"java -jar %j -unicode -force -df %o %I\".
  2804. When using LaTeXML set this option to
  2805. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  2806. :group 'org-latex
  2807. :version "24.1"
  2808. :type '(choice
  2809. (const :tag "None" nil)
  2810. (string :tag "\nShell command")))
  2811. (defcustom org-latex-to-html-convert-command nil
  2812. "Command to convert LaTeX fragments to HTML.
  2813. This command is very open-ended: the output of the command will
  2814. directly replace the LaTeX fragment in the resulting HTML.
  2815. Replace format-specifiers in the command as noted below and use
  2816. `shell-command' to convert LaTeX to HTML.
  2817. %i: The LaTeX fragment to be converted.
  2818. For example, this could be used with LaTeXML as
  2819. \"latexmlc 'literal:%i' --profile=math --preload=siunitx.sty 2>/dev/null\"."
  2820. :group 'org-latex
  2821. :package-version '(Org . "9.4")
  2822. :type '(choice
  2823. (const :tag "None" nil)
  2824. (string :tag "Shell command")))
  2825. (defcustom org-preview-latex-default-process 'dvipng
  2826. "The default process to convert LaTeX fragments to image files.
  2827. All available processes and theirs documents can be found in
  2828. `org-preview-latex-process-alist', which see."
  2829. :group 'org-latex
  2830. :version "26.1"
  2831. :package-version '(Org . "9.0")
  2832. :type 'symbol)
  2833. (defcustom org-preview-latex-process-alist
  2834. '((dvipng
  2835. :programs ("latex" "dvipng")
  2836. :description "dvi > png"
  2837. :message "you need to install the programs: latex and dvipng."
  2838. :image-input-type "dvi"
  2839. :image-output-type "png"
  2840. :image-size-adjust (1.0 . 1.0)
  2841. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2842. :image-converter ("dvipng -D %D -T tight -o %O %f")
  2843. :transparent-image-converter
  2844. ("dvipng -D %D -T tight -bg Transparent -o %O %f"))
  2845. (dvisvgm
  2846. :programs ("latex" "dvisvgm")
  2847. :description "dvi > svg"
  2848. :message "you need to install the programs: latex and dvisvgm."
  2849. :image-input-type "dvi"
  2850. :image-output-type "svg"
  2851. :image-size-adjust (1.7 . 1.5)
  2852. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2853. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  2854. (imagemagick
  2855. :programs ("latex" "convert")
  2856. :description "pdf > png"
  2857. :message "you need to install the programs: latex and imagemagick."
  2858. :image-input-type "pdf"
  2859. :image-output-type "png"
  2860. :image-size-adjust (1.0 . 1.0)
  2861. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  2862. :image-converter
  2863. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  2864. "Definitions of external processes for LaTeX previewing.
  2865. Org mode can use some external commands to generate TeX snippet's images for
  2866. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  2867. `org-create-formula-image' how to call them.
  2868. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  2869. PROPERTIES accepts the following attributes:
  2870. :programs list of strings, required programs.
  2871. :description string, describe the process.
  2872. :message string, message it when required programs cannot be found.
  2873. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  2874. :image-output-type string, output file type of image converter (e.g., \"png\").
  2875. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  2876. image size showed in buffer and the cdr element is for
  2877. HTML file. This option is only useful for process
  2878. developers, users should use variable
  2879. `org-format-latex-options' instead.
  2880. :post-clean list of strings, files matched are to be cleaned up once
  2881. the image is generated. When nil, the files with \".dvi\",
  2882. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  2883. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  2884. be cleaned up.
  2885. :latex-header list of strings, the LaTeX header of the snippet file.
  2886. When nil, the fallback value is used instead, which is
  2887. controlled by `org-format-latex-header',
  2888. `org-latex-default-packages-alist' and
  2889. `org-latex-packages-alist', which see.
  2890. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  2891. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  2892. replaced with values defined below.
  2893. :image-converter list of image converter commands strings. Each of them is
  2894. given to the shell and supports any of the following
  2895. place-holders defined below.
  2896. If set, :transparent-image-converter is used instead of :image-converter to
  2897. convert an image when the background color is nil or \"Transparent\".
  2898. Place-holders used by `:image-converter' and `:latex-compiler':
  2899. %f input file name
  2900. %b base name of input file
  2901. %o base directory of input file
  2902. %O absolute output file name
  2903. Place-holders only used by `:image-converter':
  2904. %D dpi, which is used to adjust image size by some processing commands.
  2905. %S the image size scale ratio, which is used to adjust image size by some
  2906. processing commands."
  2907. :group 'org-latex
  2908. :version "26.1"
  2909. :package-version '(Org . "9.0")
  2910. :type '(alist :tag "LaTeX to image backends"
  2911. :value-type (plist)))
  2912. (defcustom org-preview-latex-image-directory "ltximg/"
  2913. "Path to store latex preview images.
  2914. A relative path here creates many directories relative to the
  2915. processed Org files paths. An absolute path puts all preview
  2916. images at the same place."
  2917. :group 'org-latex
  2918. :version "26.1"
  2919. :package-version '(Org . "9.0")
  2920. :type 'string)
  2921. (defun org-format-latex-mathml-available-p ()
  2922. "Return t if `org-latex-to-mathml-convert-command' is usable."
  2923. (save-match-data
  2924. (when (and (boundp 'org-latex-to-mathml-convert-command)
  2925. org-latex-to-mathml-convert-command)
  2926. (let ((executable (car (split-string
  2927. org-latex-to-mathml-convert-command))))
  2928. (when (executable-find executable)
  2929. (if (string-match
  2930. "%j" org-latex-to-mathml-convert-command)
  2931. (file-readable-p org-latex-to-mathml-jar-file)
  2932. t))))))
  2933. (defcustom org-format-latex-header "\\documentclass{article}
  2934. \\usepackage[usenames]{color}
  2935. \[PACKAGES]
  2936. \[DEFAULT-PACKAGES]
  2937. \\pagestyle{empty} % do not remove
  2938. % The settings below are copied from fullpage.sty
  2939. \\setlength{\\textwidth}{\\paperwidth}
  2940. \\addtolength{\\textwidth}{-3cm}
  2941. \\setlength{\\oddsidemargin}{1.5cm}
  2942. \\addtolength{\\oddsidemargin}{-2.54cm}
  2943. \\setlength{\\evensidemargin}{\\oddsidemargin}
  2944. \\setlength{\\textheight}{\\paperheight}
  2945. \\addtolength{\\textheight}{-\\headheight}
  2946. \\addtolength{\\textheight}{-\\headsep}
  2947. \\addtolength{\\textheight}{-\\footskip}
  2948. \\addtolength{\\textheight}{-3cm}
  2949. \\setlength{\\topmargin}{1.5cm}
  2950. \\addtolength{\\topmargin}{-2.54cm}"
  2951. "The document header used for processing LaTeX fragments.
  2952. It is imperative that this header make sure that no page number
  2953. appears on the page. The package defined in the variables
  2954. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  2955. will either replace the placeholder \"[PACKAGES]\" in this
  2956. header, or they will be appended."
  2957. :group 'org-latex
  2958. :type 'string)
  2959. (defun org-set-packages-alist (var val)
  2960. "Set the packages alist and make sure it has 3 elements per entry."
  2961. (set var (mapcar (lambda (x)
  2962. (if (and (consp x) (= (length x) 2))
  2963. (list (car x) (nth 1 x) t)
  2964. x))
  2965. val)))
  2966. (defun org-get-packages-alist (var)
  2967. "Get the packages alist and make sure it has 3 elements per entry."
  2968. (mapcar (lambda (x)
  2969. (if (and (consp x) (= (length x) 2))
  2970. (list (car x) (nth 1 x) t)
  2971. x))
  2972. (default-value var)))
  2973. (defcustom org-latex-default-packages-alist
  2974. '(("AUTO" "inputenc" t ("pdflatex"))
  2975. ("T1" "fontenc" t ("pdflatex"))
  2976. ("" "graphicx" t)
  2977. ("" "longtable" nil)
  2978. ("" "wrapfig" nil)
  2979. ("" "rotating" nil)
  2980. ("normalem" "ulem" t)
  2981. ("" "amsmath" t)
  2982. ("" "amssymb" t)
  2983. ("" "capt-of" nil)
  2984. ("" "hyperref" nil))
  2985. "Alist of default packages to be inserted in the header.
  2986. Change this only if one of the packages here causes an
  2987. incompatibility with another package you are using.
  2988. The packages in this list are needed by one part or another of
  2989. Org mode to function properly:
  2990. - inputenc, fontenc: for basic font and character selection
  2991. - graphicx: for including images
  2992. - longtable: For multipage tables
  2993. - wrapfig: for figure placement
  2994. - rotating: for sideways figures and tables
  2995. - ulem: for underline and strike-through
  2996. - amsmath: for subscript and superscript and math environments
  2997. - amssymb: for various symbols used for interpreting the entities
  2998. in `org-entities'. You can skip some of this package if you don't
  2999. use any of the symbols.
  3000. - capt-of: for captions outside of floats
  3001. - hyperref: for cross references
  3002. Therefore you should not modify this variable unless you know
  3003. what you are doing. The one reason to change it anyway is that
  3004. you might be loading some other package that conflicts with one
  3005. of the default packages. Each element is either a cell or
  3006. a string.
  3007. A cell is of the format
  3008. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3009. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3010. when compiling LaTeX snippets into images for inclusion into
  3011. non-LaTeX output.
  3012. COMPILERS is a list of compilers that should include the package,
  3013. see `org-latex-compiler'. If the document compiler is not in the
  3014. list, and the list is non-nil, the package will not be inserted
  3015. in the final document.
  3016. A string will be inserted as-is in the header of the document."
  3017. :group 'org-latex
  3018. :group 'org-export-latex
  3019. :set 'org-set-packages-alist
  3020. :get 'org-get-packages-alist
  3021. :version "26.1"
  3022. :package-version '(Org . "8.3")
  3023. :type '(repeat
  3024. (choice
  3025. (list :tag "options/package pair"
  3026. (string :tag "options")
  3027. (string :tag "package")
  3028. (boolean :tag "Snippet")
  3029. (choice
  3030. (const :tag "For all compilers" nil)
  3031. (repeat :tag "Allowed compiler" string)))
  3032. (string :tag "A line of LaTeX"))))
  3033. (defcustom org-latex-packages-alist nil
  3034. "Alist of packages to be inserted in every LaTeX header.
  3035. These will be inserted after `org-latex-default-packages-alist'.
  3036. Each element is either a cell or a string.
  3037. A cell is of the format:
  3038. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3039. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3040. needed when turning LaTeX snippets into images for inclusion into
  3041. non-LaTeX output.
  3042. COMPILERS is a list of compilers that should include the package,
  3043. see `org-latex-compiler'. If the document compiler is not in the
  3044. list, and the list is non-nil, the package will not be inserted
  3045. in the final document.
  3046. A string will be inserted as-is in the header of the document.
  3047. Make sure that you only list packages here which:
  3048. - you want in every file;
  3049. - do not conflict with the setup in `org-format-latex-header';
  3050. - do not conflict with the default packages in
  3051. `org-latex-default-packages-alist'."
  3052. :group 'org-latex
  3053. :group 'org-export-latex
  3054. :set 'org-set-packages-alist
  3055. :get 'org-get-packages-alist
  3056. :type '(repeat
  3057. (choice
  3058. (list :tag "options/package pair"
  3059. (string :tag "options")
  3060. (string :tag "package")
  3061. (boolean :tag "Snippet"))
  3062. (string :tag "A line of LaTeX"))))
  3063. (defgroup org-appearance nil
  3064. "Settings for Org mode appearance."
  3065. :tag "Org Appearance"
  3066. :group 'org)
  3067. (defcustom org-level-color-stars-only nil
  3068. "Non-nil means fontify only the stars in each headline.
  3069. When nil, the entire headline is fontified.
  3070. Changing it requires restart of `font-lock-mode' to become effective
  3071. also in regions already fontified."
  3072. :group 'org-appearance
  3073. :type 'boolean)
  3074. (defcustom org-hide-leading-stars nil
  3075. "Non-nil means hide the first N-1 stars in a headline.
  3076. This works by using the face `org-hide' for these stars. This
  3077. face is white for a light background, and black for a dark
  3078. background. You may have to customize the face `org-hide' to
  3079. make this work.
  3080. Changing it requires restart of `font-lock-mode' to become effective
  3081. also in regions already fontified.
  3082. You may also set this on a per-file basis by adding one of the following
  3083. lines to the buffer:
  3084. #+STARTUP: hidestars
  3085. #+STARTUP: showstars"
  3086. :group 'org-appearance
  3087. :type 'boolean)
  3088. (defcustom org-hidden-keywords nil
  3089. "List of symbols corresponding to keywords to be hidden in the Org buffer.
  3090. For example, a value \\='(title) for this list makes the document's title
  3091. appear in the buffer without the initial \"#+TITLE:\" part."
  3092. :group 'org-appearance
  3093. :package-version '(Org . "9.5")
  3094. :type '(set (const :tag "#+AUTHOR" author)
  3095. (const :tag "#+DATE" date)
  3096. (const :tag "#+EMAIL" email)
  3097. (const :tag "#+SUBTITLE" subtitle)
  3098. (const :tag "#+TITLE" title)))
  3099. (defcustom org-custom-properties nil
  3100. "List of properties (as strings) with a special meaning.
  3101. The default use of these custom properties is to let the user
  3102. hide them with `org-toggle-custom-properties-visibility'."
  3103. :group 'org-properties
  3104. :group 'org-appearance
  3105. :version "24.3"
  3106. :type '(repeat (string :tag "Property Name")))
  3107. (defcustom org-fontify-todo-headline nil
  3108. "Non-nil means change the face of a headline if it is marked as TODO.
  3109. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3110. When this is non-nil, the headline after the keyword is set to the
  3111. `org-headline-todo' as an additional indication."
  3112. :group 'org-appearance
  3113. :package-version '(Org . "9.4")
  3114. :type 'boolean
  3115. :safe #'booleanp)
  3116. (defcustom org-fontify-done-headline t
  3117. "Non-nil means change the face of a headline if it is marked DONE.
  3118. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3119. When this is non-nil, the headline after the keyword is set to the
  3120. `org-headline-done' as an additional indication."
  3121. :group 'org-appearance
  3122. :package-version '(Org . "9.4")
  3123. :type 'boolean)
  3124. (defcustom org-fontify-emphasized-text t
  3125. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3126. Changing this variable requires a restart of Emacs to take effect."
  3127. :group 'org-appearance
  3128. :type 'boolean)
  3129. (defcustom org-fontify-whole-heading-line nil
  3130. "Non-nil means fontify the whole line for headings.
  3131. This is useful when setting a background color for the
  3132. org-level-* faces."
  3133. :group 'org-appearance
  3134. :type 'boolean)
  3135. (defcustom org-fontify-whole-block-delimiter-line t
  3136. "Non-nil means fontify the whole line for begin/end lines of blocks.
  3137. This is useful when setting a background color for the
  3138. org-block-begin-line and org-block-end-line faces."
  3139. :group 'org-appearance
  3140. :type 'boolean)
  3141. (defcustom org-highlight-latex-and-related nil
  3142. "Non-nil means highlight LaTeX related syntax in the buffer.
  3143. When non-nil, the value should be a list containing any of the
  3144. following symbols:
  3145. `native' Highlight LaTeX snippets and environments natively.
  3146. `latex' Highlight LaTeX snippets and environments.
  3147. `script' Highlight subscript and superscript.
  3148. `entities' Highlight entities."
  3149. :group 'org-appearance
  3150. :version "24.4"
  3151. :package-version '(Org . "8.0")
  3152. :type '(choice
  3153. (const :tag "No highlighting" nil)
  3154. (set :greedy t :tag "Highlight"
  3155. (const :tag "LaTeX snippets and environments (native)" native)
  3156. (const :tag "LaTeX snippets and environments" latex)
  3157. (const :tag "Subscript and superscript" script)
  3158. (const :tag "Entities" entities))))
  3159. (defcustom org-hide-emphasis-markers nil
  3160. "Non-nil mean font-lock should hide the emphasis marker characters."
  3161. :group 'org-appearance
  3162. :type 'boolean
  3163. :safe #'booleanp)
  3164. (defcustom org-hide-macro-markers nil
  3165. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3166. :group 'org-appearance
  3167. :type 'boolean)
  3168. (defcustom org-pretty-entities nil
  3169. "Non-nil means show entities as UTF8 characters.
  3170. When nil, the \\name form remains in the buffer."
  3171. :group 'org-appearance
  3172. :version "24.1"
  3173. :type 'boolean)
  3174. (defcustom org-pretty-entities-include-sub-superscripts t
  3175. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3176. :group 'org-appearance
  3177. :version "24.1"
  3178. :type 'boolean)
  3179. (defvar org-emph-re nil
  3180. "Regular expression for matching emphasis.
  3181. After a match, the match groups contain these elements:
  3182. 0 The match of the full regular expression, including the characters
  3183. before and after the proper match
  3184. 1 The character before the proper match, or empty at beginning of line
  3185. 2 The proper match, including the leading and trailing markers
  3186. 3 The leading marker like * or /, indicating the type of highlighting
  3187. 4 The text between the emphasis markers, not including the markers
  3188. 5 The character after the match, empty at the end of a line")
  3189. (defvar org-verbatim-re nil
  3190. "Regular expression for matching verbatim text.")
  3191. (defvar org-emphasis-regexp-components) ; defined just below
  3192. (defvar org-emphasis-alist) ; defined just below
  3193. (defun org-set-emph-re (var val)
  3194. "Set variable and compute the emphasis regular expression."
  3195. (set var val)
  3196. (when (and (boundp 'org-emphasis-alist)
  3197. (boundp 'org-emphasis-regexp-components)
  3198. org-emphasis-alist org-emphasis-regexp-components)
  3199. (pcase-let*
  3200. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3201. (body (if (<= nl 0) body
  3202. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3203. (template
  3204. (format (concat "\\([%s]\\|^\\)" ;before markers
  3205. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3206. "\\([%s]\\|$\\)") ;after markers
  3207. pre border border body border post)))
  3208. (setq org-emph-re (format template "*/_+"))
  3209. (setq org-verbatim-re (format template "=~")))))
  3210. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3211. ;; set this option proved cumbersome. See this message/thread:
  3212. ;; https://orgmode.org/list/B72CDC2B-72F6-43A8-AC70-E6E6295766EC@gmail.com
  3213. (defvar org-emphasis-regexp-components
  3214. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3215. "Components used to build the regular expression for emphasis.
  3216. This is a list with five entries. Terminology: In an emphasis string
  3217. like \" *strong word* \", we call the initial space PREMATCH, the final
  3218. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3219. and \"trong wor\" is the body. The different components in this variable
  3220. specify what is allowed/forbidden in each part:
  3221. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3222. post Chars allowed as postmatch. End of line will be allowed too.
  3223. border The chars *forbidden* as border characters.
  3224. body-regexp A regexp like \".\" to match a body character. Don't use
  3225. non-shy groups here, and don't allow newline here.
  3226. newline The maximum number of newlines allowed in an emphasis exp.
  3227. You need to reload Org or to restart Emacs after setting this.")
  3228. (defcustom org-emphasis-alist
  3229. '(("*" bold)
  3230. ("/" italic)
  3231. ("_" underline)
  3232. ("=" org-verbatim verbatim)
  3233. ("~" org-code verbatim)
  3234. ("+" (:strike-through t)))
  3235. "Alist of characters and faces to emphasize text.
  3236. Text starting and ending with a special character will be emphasized,
  3237. for example *bold*, _underlined_ and /italic/. This variable sets the
  3238. marker characters and the face to be used by font-lock for highlighting
  3239. in Org buffers.
  3240. You need to reload Org or to restart Emacs after customizing this."
  3241. :group 'org-appearance
  3242. :set 'org-set-emph-re
  3243. :version "24.4"
  3244. :package-version '(Org . "8.0")
  3245. :type '(repeat
  3246. (list
  3247. (string :tag "Marker character")
  3248. (choice
  3249. (face :tag "Font-lock-face")
  3250. (plist :tag "Face property list"))
  3251. (option (const verbatim)))))
  3252. (defvar org-protecting-blocks '("src" "example" "export")
  3253. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3254. This is needed for font-lock setup.")
  3255. ;;; Functions and variables from their packages
  3256. ;; Declared here to avoid compiler warnings
  3257. (defvar mark-active)
  3258. ;; Various packages
  3259. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3260. (declare-function calendar-forward-day "cal-move" (arg))
  3261. (declare-function calendar-goto-date "cal-move" (date))
  3262. (declare-function calendar-goto-today "cal-move" ())
  3263. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3264. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3265. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3266. (declare-function cdlatex-tab "ext:cdlatex" ())
  3267. (declare-function dired-get-filename
  3268. "dired"
  3269. (&optional localp no-error-if-not-filep))
  3270. (declare-function iswitchb-read-buffer
  3271. "iswitchb"
  3272. (prompt &optional
  3273. default require-match _predicate start matches-set))
  3274. (declare-function org-agenda-change-all-lines
  3275. "org-agenda"
  3276. (newhead hdmarker &optional fixface just-this))
  3277. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3278. "org-agenda"
  3279. (&optional end))
  3280. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3281. (declare-function org-agenda-format-item
  3282. "org-agenda"
  3283. (extra txt &optional level category tags dotime
  3284. remove-re habitp))
  3285. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3286. (declare-function org-agenda-save-markers-for-cut-and-paste
  3287. "org-agenda"
  3288. (beg end))
  3289. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3290. (declare-function org-agenda-skip "org-agenda" (&optional element))
  3291. (declare-function org-attach-expand "org-attach" (file))
  3292. (declare-function org-attach-reveal "org-attach" ())
  3293. (declare-function org-attach-reveal-in-emacs "org-attach" ())
  3294. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3295. (declare-function org-indent-mode "org-indent" (&optional arg))
  3296. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3297. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3298. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3299. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3300. (declare-function parse-time-string "parse-time" (string))
  3301. (defvar align-mode-rules-list)
  3302. (defvar calc-embedded-close-formula)
  3303. (defvar calc-embedded-open-formula)
  3304. (defvar calc-embedded-open-mode)
  3305. (defvar font-lock-unfontify-region-function)
  3306. (defvar iswitchb-temp-buflist)
  3307. (defvar org-agenda-tags-todo-honor-ignore-options)
  3308. (defvar remember-data-file)
  3309. (defvar texmathp-why)
  3310. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3311. (declare-function org-clock-update-mode-line "org-clock" (&optional refresh))
  3312. (declare-function org-resolve-clocks "org-clock"
  3313. (&optional also-non-dangling-p prompt last-valid))
  3314. (defvar org-clock-start-time)
  3315. (defvar org-clock-marker (make-marker)
  3316. "Marker recording the last clock-in.")
  3317. (defvar org-clock-hd-marker (make-marker)
  3318. "Marker recording the last clock-in, but the headline position.")
  3319. (defvar org-clock-heading ""
  3320. "The heading of the current clock entry.")
  3321. (defun org-clocking-buffer ()
  3322. "Return the buffer where the clock is currently running.
  3323. Return nil if no clock is running."
  3324. (marker-buffer org-clock-marker))
  3325. (defalias 'org-clock-is-active #'org-clocking-buffer)
  3326. (defun org-check-running-clock ()
  3327. "Check if the current buffer contains the running clock.
  3328. If yes, offer to stop it and to save the buffer with the changes."
  3329. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3330. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3331. (buffer-name))))
  3332. (org-clock-out)
  3333. (when (y-or-n-p "Save changed buffer?")
  3334. (save-buffer))))
  3335. (defun org-clocktable-try-shift (dir n)
  3336. "Check if this line starts a clock table, if yes, shift the time block."
  3337. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3338. (org-clocktable-shift dir n)))
  3339. ;;;###autoload
  3340. (defun org-clock-persistence-insinuate ()
  3341. "Set up hooks for clock persistence."
  3342. (require 'org-clock)
  3343. (add-hook 'org-mode-hook 'org-clock-load)
  3344. (add-hook 'kill-emacs-hook 'org-clock-save))
  3345. (defun org-clock-auto-clockout-insinuate ()
  3346. "Set up hook for auto clocking out when Emacs is idle.
  3347. See `org-clock-auto-clockout-timer'.
  3348. This function is meant to be added to the user configuration."
  3349. (require 'org-clock)
  3350. (add-hook 'org-clock-in-hook #'org-clock-auto-clockout t))
  3351. (defgroup org-archive nil
  3352. "Options concerning archiving in Org mode."
  3353. :tag "Org Archive"
  3354. :group 'org-structure)
  3355. (defcustom org-archive-location "%s_archive::"
  3356. "The location where subtrees should be archived.
  3357. The value of this variable is a string, consisting of two parts,
  3358. separated by a double-colon. The first part is a filename and
  3359. the second part is a headline.
  3360. When the filename is omitted, archiving happens in the same file.
  3361. %s in the filename will be replaced by the current file
  3362. name (without the directory part). Archiving to a different file
  3363. is useful to keep archived entries from contributing to the
  3364. Org Agenda.
  3365. The archived entries will be filed as subtrees of the specified
  3366. headline. When the headline is omitted, the subtrees are simply
  3367. filed away at the end of the file, as top-level entries. Also in
  3368. the heading you can use %s to represent the file name, this can be
  3369. useful when using the same archive for a number of different files.
  3370. Here are a few examples:
  3371. \"%s_archive::\"
  3372. If the current file is Projects.org, archive in file
  3373. Projects.org_archive, as top-level trees. This is the default.
  3374. \"::* Archived Tasks\"
  3375. Archive in the current file, under the top-level headline
  3376. \"* Archived Tasks\".
  3377. \"~/org/archive.org::\"
  3378. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3379. \"~/org/archive.org::* From %s\"
  3380. Archive in file ~/org/archive.org (absolute path), under headlines
  3381. \"From FILENAME\" where file name is the current file name.
  3382. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3383. The \"datetree/\" string is special, signifying to archive
  3384. items to the datetree. Items are placed in either the CLOSED
  3385. date of the item, or the current date if there is no CLOSED date.
  3386. The heading will be a subentry to the current date. There doesn't
  3387. need to be a heading, but there always needs to be a slash after
  3388. datetree. For example, to store archived items directly in the
  3389. datetree, use \"~/org/datetree.org::datetree/\".
  3390. \"basement::** Finished Tasks\"
  3391. Archive in file ./basement (relative path), as level 3 trees
  3392. below the level 2 heading \"** Finished Tasks\".
  3393. You may define it locally by setting an ARCHIVE property. If
  3394. such a property is found in the file or in an entry, and anywhere
  3395. up the hierarchy, it will be used.
  3396. You can also set it for the whole file using the keyword-syntax:
  3397. #+ARCHIVE: basement::** Finished Tasks"
  3398. :group 'org-archive
  3399. :type 'string)
  3400. (defcustom org-agenda-skip-archived-trees t
  3401. "Non-nil means the agenda will skip any items located in archived trees.
  3402. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3403. variable is no longer recommended, you should leave it at the value t.
  3404. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3405. :group 'org-archive
  3406. :group 'org-agenda-skip
  3407. :type 'boolean)
  3408. (defcustom org-columns-skip-archived-trees t
  3409. "Non-nil means ignore archived trees when creating column view."
  3410. :group 'org-archive
  3411. :group 'org-properties
  3412. :type 'boolean)
  3413. (defcustom org-cycle-open-archived-trees nil
  3414. "Non-nil means `org-cycle' will open archived trees.
  3415. An archived tree is a tree marked with the tag ARCHIVE.
  3416. When nil, archived trees will stay folded. You can still open them with
  3417. normal outline commands like `show-all', but not with the cycling commands."
  3418. :group 'org-archive
  3419. :group 'org-cycle
  3420. :type 'boolean)
  3421. (defcustom org-sparse-tree-open-archived-trees nil
  3422. "Non-nil means sparse tree construction shows matches in archived trees.
  3423. When nil, matches in these trees are highlighted, but the trees are kept in
  3424. collapsed state."
  3425. :group 'org-archive
  3426. :group 'org-sparse-trees
  3427. :type 'boolean)
  3428. (defcustom org-sparse-tree-default-date-type nil
  3429. "The default date type when building a sparse tree.
  3430. When this is nil, a date is a scheduled or a deadline timestamp.
  3431. Otherwise, these types are allowed:
  3432. all: all timestamps
  3433. active: only active timestamps (<...>)
  3434. inactive: only inactive timestamps ([...])
  3435. scheduled: only scheduled timestamps
  3436. deadline: only deadline timestamps"
  3437. :type '(choice (const :tag "Scheduled or deadline" nil)
  3438. (const :tag "All timestamps" all)
  3439. (const :tag "Only active timestamps" active)
  3440. (const :tag "Only inactive timestamps" inactive)
  3441. (const :tag "Only scheduled timestamps" scheduled)
  3442. (const :tag "Only deadline timestamps" deadline)
  3443. (const :tag "Only closed timestamps" closed))
  3444. :version "26.1"
  3445. :package-version '(Org . "8.3")
  3446. :group 'org-sparse-trees)
  3447. (defun org-cycle-hide-archived-subtrees (state)
  3448. "Re-hide all archived subtrees after a visibility state change.
  3449. STATE should be one of the symbols listed in the docstring of
  3450. `org-cycle-hook'."
  3451. (when (and (not org-cycle-open-archived-trees)
  3452. (not (memq state '(overview folded))))
  3453. (save-excursion
  3454. (let* ((globalp (memq state '(contents all)))
  3455. (beg (if globalp (point-min) (point)))
  3456. (end (if globalp (point-max) (org-end-of-subtree t))))
  3457. (org-hide-archived-subtrees beg end)
  3458. (goto-char beg)
  3459. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  3460. (message "%s" (substitute-command-keys
  3461. "Subtree is archived and stays closed. Use \
  3462. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  3463. (defun org-force-cycle-archived ()
  3464. "Cycle subtree even if it is archived."
  3465. (interactive)
  3466. (setq this-command 'org-cycle)
  3467. (let ((org-cycle-open-archived-trees t))
  3468. (call-interactively 'org-cycle)))
  3469. (defun org-hide-archived-subtrees (beg end)
  3470. "Re-hide all archived subtrees after a visibility state change."
  3471. (org-with-wide-buffer
  3472. (let ((case-fold-search nil)
  3473. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  3474. (goto-char beg)
  3475. ;; Include headline point is currently on.
  3476. (beginning-of-line)
  3477. (while (and (< (point) end) (re-search-forward re end t))
  3478. (when (member org-archive-tag (org-get-tags nil t))
  3479. (org-flag-subtree t)
  3480. (org-end-of-subtree t))))))
  3481. (defun org-flag-subtree (flag)
  3482. (save-excursion
  3483. (org-back-to-heading t)
  3484. (org-flag-region (line-end-position)
  3485. (progn (org-end-of-subtree t) (point))
  3486. flag
  3487. 'outline)))
  3488. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  3489. ;; Declare Column View Code
  3490. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  3491. (declare-function org-columns-compute "org-colview" (property))
  3492. ;; Declare ID code
  3493. (declare-function org-id-store-link "org-id")
  3494. (declare-function org-id-locations-load "org-id")
  3495. (declare-function org-id-locations-save "org-id")
  3496. (defvar org-id-track-globally)
  3497. ;;; Variables for pre-computed regular expressions, all buffer local
  3498. (defvar-local org-todo-regexp nil
  3499. "Matches any of the TODO state keywords.
  3500. Since TODO keywords are case-sensitive, `case-fold-search' is
  3501. expected to be bound to nil when matching against this regexp.")
  3502. (defvar-local org-not-done-regexp nil
  3503. "Matches any of the TODO state keywords except the last one.
  3504. Since TODO keywords are case-sensitive, `case-fold-search' is
  3505. expected to be bound to nil when matching against this regexp.")
  3506. (defvar-local org-not-done-heading-regexp nil
  3507. "Matches a TODO headline that is not done.
  3508. Since TODO keywords are case-sensitive, `case-fold-search' is
  3509. expected to be bound to nil when matching against this regexp.")
  3510. (defvar-local org-todo-line-regexp nil
  3511. "Matches a headline and puts TODO state into group 2 if present.
  3512. Since TODO keywords are case-sensitive, `case-fold-search' is
  3513. expected to be bound to nil when matching against this regexp.")
  3514. (defvar-local org-complex-heading-regexp nil
  3515. "Matches a headline and puts everything into groups:
  3516. group 1: Stars
  3517. group 2: The TODO keyword, maybe
  3518. group 3: Priority cookie
  3519. group 4: True headline
  3520. group 5: Tags
  3521. Since TODO keywords are case-sensitive, `case-fold-search' is
  3522. expected to be bound to nil when matching against this regexp.")
  3523. (defvar-local org-complex-heading-regexp-format nil
  3524. "Printf format to make regexp to match an exact headline.
  3525. This regexp will match the headline of any node which has the
  3526. exact headline text that is put into the format, but may have any
  3527. TODO state, priority and tags.")
  3528. (defvar-local org-todo-line-tags-regexp nil
  3529. "Matches a headline and puts TODO state into group 2 if present.
  3530. Also put tags into group 4 if tags are present.")
  3531. (defconst org-plain-time-of-day-regexp
  3532. (concat
  3533. "\\(\\<[012]?[0-9]"
  3534. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3535. "\\(--?"
  3536. "\\(\\<[012]?[0-9]"
  3537. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3538. "\\)?")
  3539. "Regular expression to match a plain time or time range.
  3540. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3541. groups carry important information:
  3542. 0 the full match
  3543. 1 the first time, range or not
  3544. 8 the second time, if it is a range.")
  3545. (defconst org-plain-time-extension-regexp
  3546. (concat
  3547. "\\(\\<[012]?[0-9]"
  3548. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3549. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  3550. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  3551. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3552. groups carry important information:
  3553. 0 the full match
  3554. 7 hours of duration
  3555. 9 minutes of duration")
  3556. (defconst org-stamp-time-of-day-regexp
  3557. (concat
  3558. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  3559. "\\([012][0-9]:[0-5][0-9]\\)\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?>"
  3560. "\\(--?"
  3561. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  3562. "Regular expression to match a timestamp time or time range.
  3563. After a match, the following groups carry important information:
  3564. 0 the full match
  3565. 1 date plus weekday, for back referencing to make sure
  3566. both times are on the same day
  3567. 2 the first time, range or not
  3568. 4 the second time, if it is a range.")
  3569. (defconst org-startup-options
  3570. '(("fold" org-startup-folded t)
  3571. ("overview" org-startup-folded t)
  3572. ("nofold" org-startup-folded nil)
  3573. ("showall" org-startup-folded nil)
  3574. ("show2levels" org-startup-folded show2levels)
  3575. ("show3levels" org-startup-folded show3levels)
  3576. ("show4levels" org-startup-folded show4levels)
  3577. ("show5levels" org-startup-folded show5levels)
  3578. ("showeverything" org-startup-folded showeverything)
  3579. ("content" org-startup-folded content)
  3580. ("indent" org-startup-indented t)
  3581. ("noindent" org-startup-indented nil)
  3582. ("num" org-startup-numerated t)
  3583. ("nonum" org-startup-numerated nil)
  3584. ("hidestars" org-hide-leading-stars t)
  3585. ("showstars" org-hide-leading-stars nil)
  3586. ("odd" org-odd-levels-only t)
  3587. ("oddeven" org-odd-levels-only nil)
  3588. ("align" org-startup-align-all-tables t)
  3589. ("noalign" org-startup-align-all-tables nil)
  3590. ("shrink" org-startup-shrink-all-tables t)
  3591. ("inlineimages" org-startup-with-inline-images t)
  3592. ("noinlineimages" org-startup-with-inline-images nil)
  3593. ("latexpreview" org-startup-with-latex-preview t)
  3594. ("nolatexpreview" org-startup-with-latex-preview nil)
  3595. ("customtime" org-display-custom-times t)
  3596. ("logdone" org-log-done time)
  3597. ("lognotedone" org-log-done note)
  3598. ("nologdone" org-log-done nil)
  3599. ("lognoteclock-out" org-log-note-clock-out t)
  3600. ("nolognoteclock-out" org-log-note-clock-out nil)
  3601. ("logrepeat" org-log-repeat state)
  3602. ("lognoterepeat" org-log-repeat note)
  3603. ("logdrawer" org-log-into-drawer t)
  3604. ("nologdrawer" org-log-into-drawer nil)
  3605. ("logstatesreversed" org-log-states-order-reversed t)
  3606. ("nologstatesreversed" org-log-states-order-reversed nil)
  3607. ("nologrepeat" org-log-repeat nil)
  3608. ("logreschedule" org-log-reschedule time)
  3609. ("lognotereschedule" org-log-reschedule note)
  3610. ("nologreschedule" org-log-reschedule nil)
  3611. ("logredeadline" org-log-redeadline time)
  3612. ("lognoteredeadline" org-log-redeadline note)
  3613. ("nologredeadline" org-log-redeadline nil)
  3614. ("logrefile" org-log-refile time)
  3615. ("lognoterefile" org-log-refile note)
  3616. ("nologrefile" org-log-refile nil)
  3617. ("fninline" org-footnote-define-inline t)
  3618. ("nofninline" org-footnote-define-inline nil)
  3619. ("fnlocal" org-footnote-section nil)
  3620. ("fnauto" org-footnote-auto-label t)
  3621. ("fnprompt" org-footnote-auto-label nil)
  3622. ("fnconfirm" org-footnote-auto-label confirm)
  3623. ("fnplain" org-footnote-auto-label plain)
  3624. ("fnadjust" org-footnote-auto-adjust t)
  3625. ("nofnadjust" org-footnote-auto-adjust nil)
  3626. ("constcgs" constants-unit-system cgs)
  3627. ("constSI" constants-unit-system SI)
  3628. ("noptag" org-tag-persistent-alist nil)
  3629. ("hideblocks" org-hide-block-startup t)
  3630. ("nohideblocks" org-hide-block-startup nil)
  3631. ("beamer" org-startup-with-beamer-mode t)
  3632. ("entitiespretty" org-pretty-entities t)
  3633. ("entitiesplain" org-pretty-entities nil))
  3634. "Variable associated with STARTUP options for Org.
  3635. Each element is a list of three items: the startup options (as written
  3636. in the #+STARTUP line), the corresponding variable, and the value to set
  3637. this variable to if the option is found. An optional fourth element PUSH
  3638. means to push this value onto the list in the variable.")
  3639. (defcustom org-group-tags t
  3640. "When non-nil (the default), use group tags.
  3641. This can be turned on/off through `org-toggle-tags-groups'."
  3642. :group 'org-tags
  3643. :group 'org-startup
  3644. :type 'boolean)
  3645. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  3646. (defun org-toggle-tags-groups ()
  3647. "Toggle support for group tags.
  3648. Support for group tags is controlled by the option
  3649. `org-group-tags', which is non-nil by default."
  3650. (interactive)
  3651. (setq org-group-tags (not org-group-tags))
  3652. (cond ((and (derived-mode-p 'org-agenda-mode)
  3653. org-group-tags)
  3654. (org-agenda-redo))
  3655. ((derived-mode-p 'org-mode)
  3656. (let ((org-inhibit-startup t)) (org-mode))))
  3657. (message "Groups tags support has been turned %s"
  3658. (if org-group-tags "on" "off")))
  3659. (defun org--tag-add-to-alist (alist1 alist2)
  3660. "Merge tags from ALIST1 into ALIST2.
  3661. Duplicates tags outside a group are removed. Keywords and order
  3662. are preserved.
  3663. The function assumes ALIST1 and ALIST2 are proper tag alists.
  3664. See `org-tag-alist' for their structure."
  3665. (cond
  3666. ((null alist2) alist1)
  3667. ((null alist1) alist2)
  3668. (t
  3669. (let ((to-add nil)
  3670. (group-flag nil))
  3671. (dolist (tag-pair alist1)
  3672. (pcase tag-pair
  3673. (`(,(or :startgrouptag :startgroup))
  3674. (setq group-flag t)
  3675. (push tag-pair to-add))
  3676. (`(,(or :endgrouptag :endgroup))
  3677. (setq group-flag nil)
  3678. (push tag-pair to-add))
  3679. (`(,(or :grouptags :newline))
  3680. (push tag-pair to-add))
  3681. (`(,tag . ,_)
  3682. ;; Remove duplicates from ALIST1, unless they are in
  3683. ;; a group. Indeed, it makes sense to have a tag appear in
  3684. ;; multiple groups.
  3685. (when (or group-flag (not (assoc tag alist2)))
  3686. (push tag-pair to-add)))
  3687. (_ (error "Invalid association in tag alist: %S" tag-pair))))
  3688. ;; Preserve order of ALIST1.
  3689. (append (nreverse to-add) alist2)))))
  3690. (defun org-priority-to-value (s)
  3691. "Convert priority string S to its numeric value."
  3692. (or (save-match-data
  3693. (and (string-match "\\([0-9]+\\)" s)
  3694. (string-to-number (match-string 1 s))))
  3695. (string-to-char s)))
  3696. (defun org-set-regexps-and-options (&optional tags-only)
  3697. "Precompute regular expressions used in the current buffer.
  3698. When optional argument TAGS-ONLY is non-nil, only compute tags
  3699. related expressions."
  3700. (when (derived-mode-p 'org-mode)
  3701. (let ((alist (org-collect-keywords
  3702. (append '("FILETAGS" "TAGS")
  3703. (and (not tags-only)
  3704. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  3705. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  3706. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))
  3707. '("ARCHIVE" "CATEGORY" "COLUMNS" "PRIORITIES"))))
  3708. ;; Startup options. Get this early since it does change
  3709. ;; behavior for other options (e.g., tags).
  3710. (let ((startup (cl-mapcan (lambda (value) (split-string value))
  3711. (cdr (assoc "STARTUP" alist)))))
  3712. (dolist (option startup)
  3713. (pcase (assoc-string option org-startup-options t)
  3714. (`(,_ ,variable ,value t)
  3715. (unless (listp (symbol-value variable))
  3716. (set (make-local-variable variable) nil))
  3717. (add-to-list variable value))
  3718. (`(,_ ,variable ,value . ,_)
  3719. (set (make-local-variable variable) value))
  3720. (_ nil))))
  3721. (setq-local org-file-tags
  3722. (mapcar #'org-add-prop-inherited
  3723. (cl-mapcan (lambda (value)
  3724. (cl-mapcan
  3725. (lambda (k) (org-split-string k ":"))
  3726. (split-string value)))
  3727. (cdr (assoc "FILETAGS" alist)))))
  3728. (setq org-current-tag-alist
  3729. (org--tag-add-to-alist
  3730. org-tag-persistent-alist
  3731. (let ((tags (cdr (assoc "TAGS" alist))))
  3732. (if tags
  3733. (org-tag-string-to-alist
  3734. (mapconcat #'identity tags "\n"))
  3735. org-tag-alist))))
  3736. (setq org-tag-groups-alist
  3737. (org-tag-alist-to-groups org-current-tag-alist))
  3738. (unless tags-only
  3739. ;; Properties.
  3740. (let ((properties nil))
  3741. (dolist (value (cdr (assoc "PROPERTY" alist)))
  3742. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  3743. (setq properties (org--update-property-plist
  3744. (match-string-no-properties 1 value)
  3745. (match-string-no-properties 2 value)
  3746. properties))))
  3747. (setq-local org-keyword-properties properties))
  3748. ;; Archive location.
  3749. (let ((archive (cdr (assoc "ARCHIVE" alist))))
  3750. (when archive (setq-local org-archive-location archive)))
  3751. ;; Category.
  3752. (let ((category (cdr (assoc "CATEGORY" alist))))
  3753. (when category
  3754. (setq-local org-category (intern category))
  3755. (setq-local org-keyword-properties
  3756. (org--update-property-plist
  3757. "CATEGORY" category org-keyword-properties))))
  3758. ;; Columns.
  3759. (let ((column (cdr (assoc "COLUMNS" alist))))
  3760. (when column (setq-local org-columns-default-format column)))
  3761. ;; Constants.
  3762. (let ((store nil))
  3763. (dolist (pair (cl-mapcan #'split-string
  3764. (cdr (assoc "CONSTANTS" alist))))
  3765. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" pair)
  3766. (let* ((name (match-string 1 pair))
  3767. (value (match-string 2 pair))
  3768. (old (assoc name store)))
  3769. (if old (setcdr old value)
  3770. (push (cons name value) store)))))
  3771. (setq org-table-formula-constants-local store))
  3772. ;; Link abbreviations.
  3773. (let ((links
  3774. (delq nil
  3775. (mapcar
  3776. (lambda (value)
  3777. (and (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  3778. (cons (match-string-no-properties 1 value)
  3779. (match-string-no-properties 2 value))))
  3780. (cdr (assoc "LINK" alist))))))
  3781. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  3782. ;; Priorities.
  3783. (let ((value (cdr (assoc "PRIORITIES" alist))))
  3784. (pcase (and value (split-string value))
  3785. (`(,high ,low ,default . ,_)
  3786. (setq-local org-priority-highest (org-priority-to-value high))
  3787. (setq-local org-priority-lowest (org-priority-to-value low))
  3788. (setq-local org-priority-default (org-priority-to-value default)))))
  3789. ;; Scripts.
  3790. (let ((value (cdr (assoc "OPTIONS" alist))))
  3791. (dolist (option value)
  3792. (when (string-match "\\^:\\(t\\|nil\\|{}\\)" option)
  3793. (setq-local org-use-sub-superscripts
  3794. (read (match-string 1 option))))))
  3795. ;; TODO keywords.
  3796. (setq-local org-todo-kwd-alist nil)
  3797. (setq-local org-todo-key-alist nil)
  3798. (setq-local org-todo-key-trigger nil)
  3799. (setq-local org-todo-keywords-1 nil)
  3800. (setq-local org-done-keywords nil)
  3801. (setq-local org-todo-heads nil)
  3802. (setq-local org-todo-sets nil)
  3803. (setq-local org-todo-log-states nil)
  3804. (let ((todo-sequences
  3805. (or (append (mapcar (lambda (value)
  3806. (cons 'type (split-string value)))
  3807. (cdr (assoc "TYP_TODO" alist)))
  3808. (mapcar (lambda (value)
  3809. (cons 'sequence (split-string value)))
  3810. (append (cdr (assoc "TODO" alist))
  3811. (cdr (assoc "SEQ_TODO" alist)))))
  3812. (let ((d (default-value 'org-todo-keywords)))
  3813. (if (not (stringp (car d))) d
  3814. ;; XXX: Backward compatibility code.
  3815. (list (cons org-todo-interpretation d)))))))
  3816. (dolist (sequence todo-sequences)
  3817. (let* ((sequence (or (run-hook-with-args-until-success
  3818. 'org-todo-setup-filter-hook sequence)
  3819. sequence))
  3820. (sequence-type (car sequence))
  3821. (keywords (cdr sequence))
  3822. (sep (member "|" keywords))
  3823. names alist)
  3824. (dolist (k (remove "|" keywords))
  3825. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  3826. k)
  3827. (error "Invalid TODO keyword %s" k))
  3828. (let ((name (match-string 1 k))
  3829. (key (match-string 2 k))
  3830. (log (org-extract-log-state-settings k)))
  3831. (push name names)
  3832. (push (cons name (and key (string-to-char key))) alist)
  3833. (when log (push log org-todo-log-states))))
  3834. (let* ((names (nreverse names))
  3835. (done (if sep (org-remove-keyword-keys (cdr sep))
  3836. (last names)))
  3837. (head (car names))
  3838. (tail (list sequence-type head (car done) (org-last done))))
  3839. (add-to-list 'org-todo-heads head 'append)
  3840. (push names org-todo-sets)
  3841. (setq org-done-keywords (append org-done-keywords done nil))
  3842. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  3843. (setq org-todo-key-alist
  3844. (append org-todo-key-alist
  3845. (and alist
  3846. (append '((:startgroup))
  3847. (nreverse alist)
  3848. '((:endgroup))))))
  3849. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  3850. (setq org-todo-sets (nreverse org-todo-sets)
  3851. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  3852. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  3853. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  3854. ;; Compute the regular expressions and other local variables.
  3855. ;; Using `org-outline-regexp-bol' would complicate them much,
  3856. ;; because of the fixed white space at the end of that string.
  3857. (unless org-done-keywords
  3858. (setq org-done-keywords
  3859. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  3860. (setq org-not-done-keywords
  3861. (org-delete-all org-done-keywords
  3862. (copy-sequence org-todo-keywords-1))
  3863. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  3864. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  3865. org-not-done-heading-regexp
  3866. (format org-heading-keyword-regexp-format org-not-done-regexp)
  3867. org-todo-line-regexp
  3868. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  3869. org-complex-heading-regexp
  3870. (concat "^\\(\\*+\\)"
  3871. "\\(?: +" org-todo-regexp "\\)?"
  3872. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3873. "\\(?: +\\(.*?\\)\\)??"
  3874. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  3875. "[ \t]*$")
  3876. org-complex-heading-regexp-format
  3877. (concat "^\\(\\*+\\)"
  3878. "\\(?: +" org-todo-regexp "\\)?"
  3879. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3880. "\\(?: +"
  3881. ;; Stats cookies can be stuck to body.
  3882. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  3883. "\\(%s\\)"
  3884. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  3885. "\\)"
  3886. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  3887. "[ \t]*$")
  3888. org-todo-line-tags-regexp
  3889. (concat "^\\(\\*+\\)"
  3890. "\\(?: +" org-todo-regexp "\\)?"
  3891. "\\(?: +\\(.*?\\)\\)??"
  3892. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  3893. "[ \t]*$"))
  3894. (org-compute-latex-and-related-regexp)))))
  3895. (defun org-collect-keywords (keywords &optional unique directory)
  3896. "Return values for KEYWORDS in current buffer, as an alist.
  3897. KEYWORDS is a list of strings. Return value is a list of
  3898. elements with the pattern:
  3899. (NAME . LIST-OF-VALUES)
  3900. where NAME is the upcase name of the keyword, and LIST-OF-VALUES
  3901. is a list of non-empty values, as strings, in order of appearance
  3902. in the buffer.
  3903. When KEYWORD appears in UNIQUE list, LIST-OF-VALUE is its first
  3904. value, empty or not, appearing in the buffer, as a string.
  3905. When KEYWORD appears in DIRECTORIES, each value is a cons cell:
  3906. (VALUE . DIRECTORY)
  3907. where VALUE is the regular value, and DIRECTORY is the variable
  3908. `default-directory' for the buffer containing the keyword. This
  3909. is important for values containing relative file names, since the
  3910. function follows SETUPFILE keywords, and may change its working
  3911. directory."
  3912. (let* ((keywords (cons "SETUPFILE" (mapcar #'upcase keywords)))
  3913. (unique (mapcar #'upcase unique))
  3914. (alist (org--collect-keywords-1
  3915. keywords unique directory
  3916. (and buffer-file-name (list buffer-file-name))
  3917. nil)))
  3918. ;; Re-order results.
  3919. (dolist (entry alist)
  3920. (pcase entry
  3921. (`(,_ . ,(and value (pred consp)))
  3922. (setcdr entry (nreverse value)))))
  3923. (nreverse alist)))
  3924. (defun org--collect-keywords-1 (keywords unique directory files alist)
  3925. (org-with-point-at 1
  3926. (let ((case-fold-search t)
  3927. (regexp (org-make-options-regexp keywords)))
  3928. (while (and keywords (re-search-forward regexp nil t))
  3929. (let ((element (org-with-point-at (match-beginning 0) (org-element-keyword-parser (line-end-position) (list (match-beginning 0))))))
  3930. (when (eq 'keyword (org-element-type element))
  3931. (let ((value (org-element-property :value element)))
  3932. (pcase (org-element-property :key element)
  3933. ("SETUPFILE"
  3934. (when (and (org-string-nw-p value)
  3935. (not buffer-read-only)) ;FIXME: bug in Gnus?
  3936. (let* ((uri (org-strip-quotes value))
  3937. (uri-is-url (org-url-p uri))
  3938. (uri (if uri-is-url
  3939. uri
  3940. (expand-file-name uri))))
  3941. (unless (member uri files)
  3942. (with-temp-buffer
  3943. (unless uri-is-url
  3944. (setq default-directory (file-name-directory uri)))
  3945. (let ((contents (org-file-contents uri :noerror)))
  3946. (when contents
  3947. (insert contents)
  3948. ;; Fake Org mode: `org-element-at-point'
  3949. ;; doesn't need full set-up.
  3950. (let ((major-mode 'org-mode))
  3951. (setq alist
  3952. (org--collect-keywords-1
  3953. keywords unique directory
  3954. (cons uri files)
  3955. alist))))))))))
  3956. (keyword
  3957. (let ((entry (assoc keyword alist))
  3958. (final
  3959. (cond ((not (member keyword directory)) value)
  3960. (buffer-file-name
  3961. (cons value
  3962. (file-name-directory buffer-file-name)))
  3963. (t (cons value default-directory)))))
  3964. (cond ((member keyword unique)
  3965. (push (cons keyword final) alist)
  3966. (setq keywords (remove keyword keywords))
  3967. (setq regexp (org-make-options-regexp keywords)))
  3968. ((null entry) (push (list keyword final) alist))
  3969. (t (push final (cdr entry)))))))))))
  3970. alist)))
  3971. (defun org-tag-string-to-alist (s)
  3972. "Return tag alist associated to string S.
  3973. S is a value for TAGS keyword or produced with
  3974. `org-tag-alist-to-string'. Return value is an alist suitable for
  3975. `org-tag-alist' or `org-tag-persistent-alist'."
  3976. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  3977. (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
  3978. "\\(?:(\\(.\\))\\)?\\'"))
  3979. alist group-flag)
  3980. (dolist (tokens lines (cdr (nreverse alist)))
  3981. (push '(:newline) alist)
  3982. (while tokens
  3983. (let ((token (pop tokens)))
  3984. (pcase token
  3985. ("{"
  3986. (push '(:startgroup) alist)
  3987. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3988. ("}"
  3989. (push '(:endgroup) alist)
  3990. (setq group-flag nil))
  3991. ("["
  3992. (push '(:startgrouptag) alist)
  3993. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3994. ("]"
  3995. (push '(:endgrouptag) alist)
  3996. (setq group-flag nil))
  3997. (":"
  3998. (push '(:grouptags) alist))
  3999. ((guard (string-match tag-re token))
  4000. (let ((tag (match-string 1 token))
  4001. (key (and (match-beginning 2)
  4002. (string-to-char (match-string 2 token)))))
  4003. ;; Push all tags in groups, no matter if they already
  4004. ;; appear somewhere else in the list.
  4005. (when (or group-flag (not (assoc tag alist)))
  4006. (push (cons tag key) alist))))))))))
  4007. (defun org-tag-alist-to-string (alist &optional skip-key)
  4008. "Return tag string associated to ALIST.
  4009. ALIST is an alist, as defined in `org-tag-alist' or
  4010. `org-tag-persistent-alist', or produced with
  4011. `org-tag-string-to-alist'.
  4012. Return value is a string suitable as a value for \"TAGS\"
  4013. keyword.
  4014. When optional argument SKIP-KEY is non-nil, skip selection keys
  4015. next to tags."
  4016. (mapconcat (lambda (token)
  4017. (pcase token
  4018. (`(:startgroup) "{")
  4019. (`(:endgroup) "}")
  4020. (`(:startgrouptag) "[")
  4021. (`(:endgrouptag) "]")
  4022. (`(:grouptags) ":")
  4023. (`(:newline) "\\n")
  4024. ((and
  4025. (guard (not skip-key))
  4026. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4027. (format "%s(%c)" tag key))
  4028. (`(,(and tag (pred stringp)) . ,_) tag)
  4029. (_ (user-error "Invalid tag token: %S" token))))
  4030. alist
  4031. " "))
  4032. (defun org-tag-alist-to-groups (alist)
  4033. "Return group alist from tag ALIST.
  4034. ALIST is an alist, as defined in `org-tag-alist' or
  4035. `org-tag-persistent-alist', or produced with
  4036. `org-tag-string-to-alist'. Return value is an alist following
  4037. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4038. a string, summarizing TAGS, as a list of strings."
  4039. (let (groups group-status current-group)
  4040. (dolist (token alist (nreverse groups))
  4041. (pcase token
  4042. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4043. (`(,(or :endgroup :endgrouptag))
  4044. (when (eq group-status 'append)
  4045. (push (nreverse current-group) groups))
  4046. (setq group-status nil current-group nil))
  4047. (`(:grouptags) (setq group-status 'append))
  4048. ((and `(,tag . ,_) (guard group-status))
  4049. (if (eq group-status 'append) (push tag current-group)
  4050. (setq current-group (list tag))))
  4051. (_ nil)))))
  4052. (defvar org--file-cache (make-hash-table :test #'equal)
  4053. "Hash table to store contents of files referenced via a URL.
  4054. This is the cache of file URLs read using `org-file-contents'.")
  4055. (defun org-reset-file-cache ()
  4056. "Reset the cache of files downloaded by `org-file-contents'."
  4057. (clrhash org--file-cache))
  4058. (defun org-file-contents (file &optional noerror nocache)
  4059. "Return the contents of FILE, as a string.
  4060. FILE can be a file name or URL.
  4061. If FILE is a URL, download the contents. If the URL contents are
  4062. already cached in the `org--file-cache' hash table, the download step
  4063. is skipped.
  4064. If NOERROR is non-nil, ignore the error when unable to read the FILE
  4065. from file or URL, and return nil.
  4066. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  4067. is available. This option applies only if FILE is a URL."
  4068. (let* ((is-url (org-url-p file))
  4069. (cache (and is-url
  4070. (not nocache)
  4071. (gethash file org--file-cache))))
  4072. (cond
  4073. (cache)
  4074. (is-url
  4075. (with-current-buffer (url-retrieve-synchronously file)
  4076. (goto-char (point-min))
  4077. ;; Move point to after the url-retrieve header.
  4078. (search-forward "\n\n" nil :move)
  4079. ;; Search for the success code only in the url-retrieve header.
  4080. (if (save-excursion
  4081. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  4082. ;; Update the cache `org--file-cache' and return contents.
  4083. (puthash file
  4084. (buffer-substring-no-properties (point) (point-max))
  4085. org--file-cache)
  4086. (funcall (if noerror #'message #'user-error)
  4087. "Unable to fetch file from %S"
  4088. file)
  4089. nil)))
  4090. (t
  4091. (with-temp-buffer
  4092. (condition-case nil
  4093. (progn
  4094. (insert-file-contents file)
  4095. (buffer-string))
  4096. (file-error
  4097. (funcall (if noerror #'message #'user-error)
  4098. "Unable to read file %S"
  4099. file)
  4100. nil)))))))
  4101. (defun org-extract-log-state-settings (x)
  4102. "Extract the log state setting from a TODO keyword string.
  4103. This will extract info from a string like \"WAIT(w@/!)\"."
  4104. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4105. (let ((kw (match-string 1 x))
  4106. (log1 (and (match-end 3) (match-string 3 x)))
  4107. (log2 (and (match-end 4) (match-string 4 x))))
  4108. (and (or log1 log2)
  4109. (list kw
  4110. (and log1 (if (equal log1 "!") 'time 'note))
  4111. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4112. (defun org-remove-keyword-keys (list)
  4113. "Remove a pair of parenthesis at the end of each string in LIST."
  4114. (mapcar (lambda (x)
  4115. (if (string-match "(.*)$" x)
  4116. (substring x 0 (match-beginning 0))
  4117. x))
  4118. list))
  4119. (defun org-assign-fast-keys (alist)
  4120. "Assign fast keys to a keyword-key alist.
  4121. Respect keys that are already there."
  4122. (let (new e (alt ?0))
  4123. (while (setq e (pop alist))
  4124. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4125. (cdr e)) ;; Key already assigned.
  4126. (push e new)
  4127. (let ((clist (string-to-list (downcase (car e))))
  4128. (used (append new alist)))
  4129. (when (= (car clist) ?@)
  4130. (pop clist))
  4131. (while (and clist (rassoc (car clist) used))
  4132. (pop clist))
  4133. (unless clist
  4134. (while (rassoc alt used)
  4135. (cl-incf alt)))
  4136. (push (cons (car e) (or (car clist) alt)) new))))
  4137. (nreverse new)))
  4138. ;;; Some variables used in various places
  4139. (defvar org-window-configuration nil
  4140. "Used in various places to store a window configuration.")
  4141. (defvar org-selected-window nil
  4142. "Used in various places to store a window configuration.")
  4143. (defvar org-finish-function nil
  4144. "Function to be called when `C-c C-c' is used.
  4145. This is for getting out of special buffers like capture.")
  4146. (defvar org-last-state)
  4147. ;; Defined somewhere in this file, but used before definition.
  4148. (defvar org-entities) ;; defined in org-entities.el
  4149. (defvar org-struct-menu)
  4150. (defvar org-org-menu)
  4151. (defvar org-tbl-menu)
  4152. ;;;; Define the Org mode
  4153. (defun org-before-change-function (_beg _end)
  4154. "Every change indicates that a table might need an update."
  4155. (setq org-table-may-need-update t))
  4156. (defvar org-mode-map)
  4157. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4158. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4159. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4160. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4161. (defvar bidi-paragraph-direction)
  4162. (defvar buffer-face-mode-face)
  4163. (require 'outline)
  4164. ;; Other stuff we need.
  4165. (require 'time-date)
  4166. (when (< emacs-major-version 28) ; preloaded in Emacs 28
  4167. (require 'easymenu))
  4168. (require 'org-entities)
  4169. (require 'org-faces)
  4170. (require 'org-list)
  4171. (require 'org-pcomplete)
  4172. (require 'org-src)
  4173. (require 'org-footnote)
  4174. (require 'org-macro)
  4175. ;; babel
  4176. (require 'ob)
  4177. (defvar org-element-cache-persistent); Defined in org-element.el
  4178. (defvar org-element-use-cache); Defined in org-element.el
  4179. ;;;###autoload
  4180. (define-derived-mode org-mode outline-mode "Org"
  4181. "Outline-based notes management and organizer, alias
  4182. \"Carsten's outline-mode for keeping track of everything.\"
  4183. Org mode develops organizational tasks around a NOTES file which
  4184. contains information about projects as plain text. Org mode is
  4185. implemented on top of Outline mode, which is ideal to keep the content
  4186. of large files well structured. It supports ToDo items, deadlines and
  4187. time stamps, which magically appear in the diary listing of the Emacs
  4188. calendar. Tables are easily created with a built-in table editor.
  4189. Plain text URL-like links connect to websites, emails (VM), Usenet
  4190. messages (Gnus), BBDB entries, and any files related to the project.
  4191. For printing and sharing of notes, an Org file (or a part of it)
  4192. can be exported as a structured ASCII or HTML file.
  4193. The following commands are available:
  4194. \\{org-mode-map}"
  4195. (org-load-modules-maybe)
  4196. (org-install-agenda-files-menu)
  4197. (when org-link-descriptive (add-to-invisibility-spec '(org-link)))
  4198. (make-local-variable 'org-link-descriptive)
  4199. (add-to-invisibility-spec '(org-hide-block . t))
  4200. (setq-local outline-regexp org-outline-regexp)
  4201. (setq-local outline-level 'org-outline-level)
  4202. (setq bidi-paragraph-direction 'left-to-right)
  4203. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4204. (unless org-display-table
  4205. (setq org-display-table (make-display-table)))
  4206. (set-display-table-slot
  4207. org-display-table 4
  4208. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4209. org-ellipsis)))
  4210. (setq buffer-display-table org-display-table))
  4211. (org-set-regexps-and-options)
  4212. (org-set-font-lock-defaults)
  4213. (when (and org-tag-faces (not org-tags-special-faces-re))
  4214. ;; tag faces set outside customize.... force initialization.
  4215. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4216. ;; Calc embedded
  4217. (setq-local calc-embedded-open-mode "# ")
  4218. ;; Modify a few syntax entries
  4219. (modify-syntax-entry ?\" "\"")
  4220. (modify-syntax-entry ?\\ "_")
  4221. (modify-syntax-entry ?~ "_")
  4222. (modify-syntax-entry ?< "(>")
  4223. (modify-syntax-entry ?> ")<")
  4224. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4225. ;; Activate before-change-function
  4226. (setq-local org-table-may-need-update t)
  4227. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4228. ;; Check for running clock before killing a buffer
  4229. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4230. ;; Initialize macros templates.
  4231. (org-macro-initialize-templates)
  4232. ;; Initialize radio targets.
  4233. (org-update-radio-target-regexp)
  4234. ;; Indentation.
  4235. (setq-local indent-line-function 'org-indent-line)
  4236. (setq-local indent-region-function 'org-indent-region)
  4237. ;; Filling and auto-filling.
  4238. (org-setup-filling)
  4239. ;; Comments.
  4240. (org-setup-comments-handling)
  4241. ;; Initialize cache.
  4242. (org-element-cache-reset)
  4243. (when (and org-element-cache-persistent
  4244. org-element-use-cache)
  4245. (org-persist-read 'org-element--cache (current-buffer)))
  4246. ;; Beginning/end of defun
  4247. (setq-local beginning-of-defun-function 'org-backward-element)
  4248. (setq-local end-of-defun-function
  4249. (lambda ()
  4250. (if (not (org-at-heading-p))
  4251. (org-forward-element)
  4252. (org-forward-element)
  4253. (forward-char -1))))
  4254. ;; Next error for sparse trees
  4255. (setq-local next-error-function 'org-occur-next-match)
  4256. ;; Make commit log messages from Org documents easier.
  4257. (setq-local add-log-current-defun-function #'org-add-log-current-headline)
  4258. ;; Make sure dependence stuff works reliably, even for users who set it
  4259. ;; too late :-(
  4260. (if org-enforce-todo-dependencies
  4261. (add-hook 'org-blocker-hook
  4262. 'org-block-todo-from-children-or-siblings-or-parent)
  4263. (remove-hook 'org-blocker-hook
  4264. 'org-block-todo-from-children-or-siblings-or-parent))
  4265. (if org-enforce-todo-checkbox-dependencies
  4266. (add-hook 'org-blocker-hook
  4267. 'org-block-todo-from-checkboxes)
  4268. (remove-hook 'org-blocker-hook
  4269. 'org-block-todo-from-checkboxes))
  4270. ;; Align options lines
  4271. (setq-local
  4272. align-mode-rules-list
  4273. '((org-in-buffer-settings
  4274. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4275. (modes . '(org-mode)))))
  4276. ;; Setup the pcomplete hooks
  4277. (setq-local pcomplete-command-completion-function #'org-pcomplete-initial)
  4278. (setq-local pcomplete-command-name-function #'org-command-at-point)
  4279. (setq-local pcomplete-default-completion-function #'ignore)
  4280. (setq-local pcomplete-parse-arguments-function #'org-parse-arguments)
  4281. (setq-local pcomplete-termination-string "")
  4282. (add-hook 'completion-at-point-functions
  4283. #'pcomplete-completions-at-point nil t)
  4284. (setq-local buffer-face-mode-face 'org-default)
  4285. ;; If empty file that did not turn on Org mode automatically, make
  4286. ;; it to.
  4287. (when (and org-insert-mode-line-in-empty-file
  4288. (called-interactively-p 'any)
  4289. (= (point-min) (point-max)))
  4290. (insert "# -*- mode: org -*-\n\n"))
  4291. (unless org-inhibit-startup
  4292. (org-unmodified
  4293. (when org-startup-with-beamer-mode (org-beamer-mode))
  4294. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4295. (org-table-map-tables
  4296. (cond ((and org-startup-align-all-tables
  4297. org-startup-shrink-all-tables)
  4298. (lambda () (org-table-align) (org-table-shrink)))
  4299. (org-startup-align-all-tables #'org-table-align)
  4300. (t #'org-table-shrink))
  4301. t))
  4302. (when org-startup-with-inline-images (org-display-inline-images))
  4303. (when org-startup-with-latex-preview (org-latex-preview '(16)))
  4304. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4305. (when org-startup-truncated (setq truncate-lines t))
  4306. (when org-startup-numerated (require 'org-num) (org-num-mode 1))
  4307. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))))
  4308. ;; Add a custom keymap for `visual-line-mode' so that activating
  4309. ;; this minor mode does not override Org's keybindings.
  4310. ;; FIXME: Probably `visual-line-mode' should take care of this.
  4311. (let ((oldmap (cdr (assoc 'visual-line-mode minor-mode-map-alist)))
  4312. (newmap (make-sparse-keymap)))
  4313. (set-keymap-parent newmap oldmap)
  4314. (define-key newmap [remap move-beginning-of-line] nil)
  4315. (define-key newmap [remap move-end-of-line] nil)
  4316. (define-key newmap [remap kill-line] nil)
  4317. (make-local-variable 'minor-mode-overriding-map-alist)
  4318. (push `(visual-line-mode . ,newmap) minor-mode-overriding-map-alist))
  4319. ;; Activate `org-table-header-line-mode'
  4320. (when org-table-header-line-p
  4321. (org-table-header-line-mode 1))
  4322. ;; Try to set `org-hide' face correctly.
  4323. (let ((foreground (org-find-invisible-foreground)))
  4324. (when foreground
  4325. (set-face-foreground 'org-hide foreground)))
  4326. ;; Set face extension as requested.
  4327. (org--set-faces-extend '(org-block-begin-line org-block-end-line)
  4328. org-fontify-whole-block-delimiter-line)
  4329. (org--set-faces-extend org-level-faces org-fontify-whole-heading-line))
  4330. ;; Update `customize-package-emacs-version-alist'
  4331. (add-to-list 'customize-package-emacs-version-alist
  4332. '(Org ("8.0" . "24.4")
  4333. ("8.1" . "24.4")
  4334. ("8.2" . "24.4")
  4335. ("8.2.7" . "24.4")
  4336. ("8.3" . "26.1")
  4337. ("9.0" . "26.1")
  4338. ("9.1" . "26.1")
  4339. ("9.2" . "27.1")
  4340. ("9.3" . "27.1")
  4341. ("9.4" . "27.2")
  4342. ("9.5" . "28.1")))
  4343. (defvar org-mode-transpose-word-syntax-table
  4344. (let ((st (make-syntax-table text-mode-syntax-table)))
  4345. (dolist (c org-emphasis-alist st)
  4346. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4347. (when (fboundp 'abbrev-table-put)
  4348. (abbrev-table-put org-mode-abbrev-table
  4349. :parents (list text-mode-abbrev-table)))
  4350. (defun org-find-invisible-foreground ()
  4351. (let ((candidates (remove
  4352. "unspecified-bg"
  4353. (nconc
  4354. (list (face-background 'default)
  4355. (face-background 'org-default))
  4356. (mapcar
  4357. (lambda (alist)
  4358. (when (boundp alist)
  4359. (cdr (assq 'background-color (symbol-value alist)))))
  4360. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4361. (list (face-foreground 'org-hide))))))
  4362. (car (remove nil candidates))))
  4363. (defun org-current-time (&optional rounding-minutes past)
  4364. "Current time, possibly rounded to ROUNDING-MINUTES.
  4365. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4366. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4367. the rounding returns a past time."
  4368. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4369. (car org-time-stamp-rounding-minutes)))
  4370. (now (current-time)))
  4371. (if (< r 1)
  4372. now
  4373. (let* ((time (decode-time now))
  4374. (res (apply #'encode-time 0 (* r (round (nth 1 time) r))
  4375. (nthcdr 2 time))))
  4376. (if (or (not past) (time-less-p res now))
  4377. res
  4378. (time-subtract res (* r 60)))))))
  4379. (defun org-today ()
  4380. "Return today date, considering `org-extend-today-until'."
  4381. (time-to-days
  4382. (time-since (* 3600 org-extend-today-until))))
  4383. ;;;; Font-Lock stuff, including the activators
  4384. (defconst org-match-sexp-depth 3
  4385. "Number of stacked braces for sub/superscript matching.")
  4386. (defun org-create-multibrace-regexp (left right n)
  4387. "Create a regular expression which will match a balanced sexp.
  4388. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4389. as single character strings.
  4390. The regexp returned will match the entire expression including the
  4391. delimiters. It will also define a single group which contains the
  4392. match except for the outermost delimiters. The maximum depth of
  4393. stacked delimiters is N. Escaping delimiters is not possible."
  4394. (let* ((nothing (concat "[^" left right "]*?"))
  4395. (or "\\|")
  4396. (re nothing)
  4397. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4398. (while (> n 1)
  4399. (setq n (1- n)
  4400. re (concat re or next)
  4401. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4402. (concat left "\\(" re "\\)" right)))
  4403. (defconst org-match-substring-regexp
  4404. (concat
  4405. "\\(\\S-\\)\\([_^]\\)\\("
  4406. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4407. "\\|"
  4408. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4409. "\\|"
  4410. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4411. "The regular expression matching a sub- or superscript.")
  4412. (defconst org-match-substring-with-braces-regexp
  4413. (concat
  4414. "\\(\\S-\\)\\([_^]\\)"
  4415. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4416. "The regular expression matching a sub- or superscript, forcing braces.")
  4417. (defvar org-emph-face nil)
  4418. (defun org-do-emphasis-faces (limit)
  4419. "Run through the buffer and emphasize strings."
  4420. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  4421. (car org-emphasis-regexp-components))))
  4422. (catch :exit
  4423. (while (re-search-forward quick-re limit t)
  4424. (let* ((marker (match-string 2))
  4425. (verbatim? (member marker '("~" "="))))
  4426. (when (save-excursion
  4427. (goto-char (match-beginning 0))
  4428. (and
  4429. ;; Do not match table hlines.
  4430. (not (and (equal marker "+")
  4431. (org-match-line
  4432. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  4433. ;; Do not match headline stars. Do not consider
  4434. ;; stars of a headline as closing marker for bold
  4435. ;; markup either.
  4436. (not (and (equal marker "*")
  4437. (save-excursion
  4438. (forward-char)
  4439. (skip-chars-backward "*")
  4440. (looking-at-p org-outline-regexp-bol))))
  4441. ;; Match full emphasis markup regexp.
  4442. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  4443. ;; Do not span over paragraph boundaries.
  4444. (not (string-match-p org-element-paragraph-separate
  4445. (match-string 2)))
  4446. ;; Do not span over cells in table rows.
  4447. (not (and (save-match-data (org-match-line "[ \t]*|"))
  4448. (string-match-p "|" (match-string 4))))))
  4449. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist))
  4450. (m (if org-hide-emphasis-markers 4 2)))
  4451. (font-lock-prepend-text-property
  4452. (match-beginning m) (match-end m) 'face face)
  4453. (when verbatim?
  4454. (org-remove-flyspell-overlays-in
  4455. (match-beginning 0) (match-end 0))
  4456. (remove-text-properties (match-beginning 2) (match-end 2)
  4457. '(display t invisible t intangible t)))
  4458. (add-text-properties (match-beginning 2) (match-end 2)
  4459. '(font-lock-multiline t org-emphasis t))
  4460. (when (and org-hide-emphasis-markers
  4461. (not (org-at-comment-p)))
  4462. (add-text-properties (match-end 4) (match-beginning 5)
  4463. '(invisible t))
  4464. (add-text-properties (match-beginning 3) (match-end 3)
  4465. '(invisible t)))
  4466. (goto-char (match-end 0))
  4467. (throw :exit t))))))))
  4468. (defun org-emphasize (&optional char)
  4469. "Insert or change an emphasis, i.e. a font like bold or italic.
  4470. If there is an active region, change that region to a new emphasis.
  4471. If there is no region, just insert the marker characters and position
  4472. the cursor between them.
  4473. CHAR should be the marker character. If it is a space, it means to
  4474. remove the emphasis of the selected region.
  4475. If CHAR is not given (for example in an interactive call) it will be
  4476. prompted for."
  4477. (interactive)
  4478. (let ((erc org-emphasis-regexp-components)
  4479. (string "") beg end move s)
  4480. (if (org-region-active-p)
  4481. (setq beg (region-beginning)
  4482. end (region-end)
  4483. string (buffer-substring beg end))
  4484. (setq move t))
  4485. (unless char
  4486. (message "Emphasis marker or tag: [%s]"
  4487. (mapconcat #'car org-emphasis-alist ""))
  4488. (setq char (read-char-exclusive)))
  4489. (if (equal char ?\s)
  4490. (setq s ""
  4491. move nil)
  4492. (unless (assoc (char-to-string char) org-emphasis-alist)
  4493. (user-error "No such emphasis marker: \"%c\"" char))
  4494. (setq s (char-to-string char)))
  4495. (while (and (> (length string) 1)
  4496. (equal (substring string 0 1) (substring string -1))
  4497. (assoc (substring string 0 1) org-emphasis-alist))
  4498. (setq string (substring string 1 -1)))
  4499. (setq string (concat s string s))
  4500. (when beg (delete-region beg end))
  4501. (unless (or (bolp)
  4502. (string-match (concat "[" (nth 0 erc) "\n]")
  4503. (char-to-string (char-before (point)))))
  4504. (insert " "))
  4505. (unless (or (eobp)
  4506. (string-match (concat "[" (nth 1 erc) "\n]")
  4507. (char-to-string (char-after (point)))))
  4508. (insert " ") (backward-char 1))
  4509. (insert string)
  4510. (and move (backward-char 1))))
  4511. (defconst org-nonsticky-props
  4512. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  4513. (defsubst org-rear-nonsticky-at (pos)
  4514. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  4515. (defun org-activate-links (limit)
  4516. "Add link properties to links.
  4517. This includes angle, plain, and bracket links."
  4518. (catch :exit
  4519. (while (re-search-forward org-link-any-re limit t)
  4520. (let* ((start (match-beginning 0))
  4521. (end (match-end 0))
  4522. (visible-start (or (match-beginning 3) (match-beginning 2)))
  4523. (visible-end (or (match-end 3) (match-end 2)))
  4524. (style (cond ((eq ?< (char-after start)) 'angle)
  4525. ((eq ?\[ (char-after (1+ start))) 'bracket)
  4526. (t 'plain))))
  4527. (when (and (memq style org-highlight-links)
  4528. ;; Do not span over paragraph boundaries.
  4529. (not (string-match-p org-element-paragraph-separate
  4530. (match-string 0)))
  4531. ;; Do not confuse plain links with tags.
  4532. (not (and (eq style 'plain)
  4533. (let ((face (get-text-property
  4534. (max (1- start) (point-min)) 'face)))
  4535. (if (consp face) (memq 'org-tag face)
  4536. (eq 'org-tag face))))))
  4537. (let* ((link-object (save-excursion
  4538. (goto-char start)
  4539. (save-match-data (org-element-link-parser))))
  4540. (link (org-element-property :raw-link link-object))
  4541. (type (org-element-property :type link-object))
  4542. (path (org-element-property :path link-object))
  4543. (face-property (pcase (org-link-get-parameter type :face)
  4544. ((and (pred functionp) face) (funcall face path))
  4545. ((and (pred facep) face) face)
  4546. ((and (pred consp) face) face) ;anonymous
  4547. (_ 'org-link)))
  4548. (properties ;for link's visible part
  4549. (list 'mouse-face (or (org-link-get-parameter type :mouse-face)
  4550. 'highlight)
  4551. 'keymap (or (org-link-get-parameter type :keymap)
  4552. org-mouse-map)
  4553. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  4554. ((and (pred stringp) echo) echo)
  4555. ((and (pred functionp) echo) echo)
  4556. (_ (concat "LINK: " link)))
  4557. 'htmlize-link (pcase (org-link-get-parameter type
  4558. :htmlize-link)
  4559. ((and (pred functionp) f) (funcall f))
  4560. (_ `(:uri ,link)))
  4561. 'font-lock-multiline t)))
  4562. (org-remove-flyspell-overlays-in start end)
  4563. (org-rear-nonsticky-at end)
  4564. (if (not (eq 'bracket style))
  4565. (progn
  4566. (add-face-text-property start end face-property)
  4567. (add-text-properties start end properties))
  4568. ;; Handle invisible parts in bracket links.
  4569. (remove-text-properties start end '(invisible nil))
  4570. (let ((hidden
  4571. (append `(invisible
  4572. ,(or (org-link-get-parameter type :display)
  4573. 'org-link))
  4574. properties)))
  4575. (add-text-properties start visible-start hidden)
  4576. (add-face-text-property start end face-property)
  4577. (add-text-properties visible-start visible-end properties)
  4578. (add-text-properties visible-end end hidden)
  4579. (org-rear-nonsticky-at visible-start)
  4580. (org-rear-nonsticky-at visible-end)))
  4581. (let ((f (org-link-get-parameter type :activate-func)))
  4582. (when (functionp f)
  4583. (funcall f start end path (eq style 'bracket))))
  4584. (throw :exit t))))) ;signal success
  4585. nil))
  4586. (defun org-activate-code (limit)
  4587. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  4588. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4589. (remove-text-properties (match-beginning 0) (match-end 0)
  4590. '(display t invisible t intangible t))
  4591. t))
  4592. (defcustom org-src-fontify-natively t
  4593. "When non-nil, fontify code in code blocks.
  4594. See also the `org-block' face."
  4595. :type 'boolean
  4596. :version "26.1"
  4597. :package-version '(Org . "8.3")
  4598. :group 'org-appearance
  4599. :group 'org-babel)
  4600. (defcustom org-allow-promoting-top-level-subtree nil
  4601. "When non-nil, allow promoting a top level subtree.
  4602. The leading star of the top level headline will be replaced
  4603. by a #."
  4604. :type 'boolean
  4605. :version "24.1"
  4606. :group 'org-appearance)
  4607. (defun org-fontify-meta-lines-and-blocks (limit)
  4608. (condition-case nil
  4609. (org-fontify-meta-lines-and-blocks-1 limit)
  4610. (error (message "Org mode fontification error in %S at %d"
  4611. (current-buffer)
  4612. (line-number-at-pos)))))
  4613. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  4614. "Fontify #+ lines and blocks."
  4615. (let ((case-fold-search t))
  4616. (when (re-search-forward
  4617. (rx bol (group (zero-or-more (any " \t")) "#"
  4618. (group (group (or (seq "+" (one-or-more (any "a-zA-Z")) (optional ":"))
  4619. (any " \t")
  4620. eol))
  4621. (optional (group "_" (group (one-or-more (any "a-zA-Z"))))))
  4622. (zero-or-more (any " \t"))
  4623. (group (group (zero-or-more (not (any " \t\n"))))
  4624. (zero-or-more (any " \t"))
  4625. (group (zero-or-more any)))))
  4626. limit t)
  4627. (let ((beg (match-beginning 0))
  4628. (end-of-beginline (match-end 0))
  4629. ;; Including \n at end of #+begin line will include \n
  4630. ;; after the end of block content.
  4631. (block-start (match-end 0))
  4632. (block-end nil)
  4633. (lang (match-string 7)) ; The language, if it is a source block.
  4634. (bol-after-beginline (line-beginning-position 2))
  4635. (dc1 (downcase (match-string 2)))
  4636. (dc3 (downcase (match-string 3)))
  4637. (whole-blockline org-fontify-whole-block-delimiter-line)
  4638. beg-of-endline end-of-endline nl-before-endline quoting block-type)
  4639. (cond
  4640. ((and (match-end 4) (equal dc3 "+begin"))
  4641. ;; Truly a block
  4642. (setq block-type (downcase (match-string 5))
  4643. ;; Src, example, export, maybe more.
  4644. quoting (member block-type org-protecting-blocks))
  4645. (when (re-search-forward
  4646. (rx-to-string `(group bol (or (seq (one-or-more "*") space)
  4647. (seq (zero-or-more (any " \t"))
  4648. "#+end"
  4649. ,(match-string 4)
  4650. word-end
  4651. (zero-or-more any)))))
  4652. ;; We look further than LIMIT on purpose.
  4653. nil t)
  4654. ;; We do have a matching #+end line.
  4655. (setq beg-of-endline (match-beginning 0)
  4656. end-of-endline (match-end 0)
  4657. nl-before-endline (1- (match-beginning 0)))
  4658. (setq block-end (match-beginning 0)) ; Include the final newline.
  4659. (when quoting
  4660. (org-remove-flyspell-overlays-in bol-after-beginline nl-before-endline)
  4661. (remove-text-properties beg end-of-endline
  4662. '(display t invisible t intangible t)))
  4663. (add-text-properties
  4664. beg end-of-endline '(font-lock-fontified t font-lock-multiline t))
  4665. (org-remove-flyspell-overlays-in beg bol-after-beginline)
  4666. (org-remove-flyspell-overlays-in nl-before-endline end-of-endline)
  4667. (cond
  4668. ((and lang (not (string= lang "")) org-src-fontify-natively)
  4669. (save-match-data
  4670. (org-src-font-lock-fontify-block lang block-start block-end))
  4671. (add-text-properties bol-after-beginline block-end '(src-block t)))
  4672. (quoting
  4673. (add-text-properties
  4674. bol-after-beginline beg-of-endline
  4675. (list 'face
  4676. (list :inherit
  4677. (let ((face-name
  4678. (intern (format "org-block-%s" lang))))
  4679. (append (and (facep face-name) (list face-name))
  4680. '(org-block)))))))
  4681. ((not org-fontify-quote-and-verse-blocks))
  4682. ((string= block-type "quote")
  4683. (add-face-text-property
  4684. bol-after-beginline beg-of-endline 'org-quote t))
  4685. ((string= block-type "verse")
  4686. (add-face-text-property
  4687. bol-after-beginline beg-of-endline 'org-verse t)))
  4688. ;; Fontify the #+begin and #+end lines of the blocks
  4689. (add-text-properties
  4690. beg (if whole-blockline bol-after-beginline end-of-beginline)
  4691. '(face org-block-begin-line))
  4692. (unless (eq (char-after beg-of-endline) ?*)
  4693. (add-text-properties
  4694. beg-of-endline
  4695. (if whole-blockline
  4696. (let ((beg-of-next-line (1+ end-of-endline)))
  4697. (min (point-max) beg-of-next-line))
  4698. (min (point-max) end-of-endline))
  4699. '(face org-block-end-line)))
  4700. t))
  4701. ((member dc1 '("+title:" "+subtitle:" "+author:" "+email:" "+date:"))
  4702. (org-remove-flyspell-overlays-in
  4703. (match-beginning 0)
  4704. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  4705. (add-text-properties
  4706. beg (match-end 3)
  4707. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  4708. '(font-lock-fontified t invisible t)
  4709. '(font-lock-fontified t face org-document-info-keyword)))
  4710. (add-text-properties
  4711. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  4712. (if (string-equal dc1 "+title:")
  4713. '(font-lock-fontified t face org-document-title)
  4714. '(font-lock-fontified t face org-document-info))))
  4715. ((string-prefix-p "+caption" dc1)
  4716. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  4717. (remove-text-properties (match-beginning 0) (match-end 0)
  4718. '(display t invisible t intangible t))
  4719. ;; Handle short captions
  4720. (save-excursion
  4721. (beginning-of-line)
  4722. (looking-at (rx (group (zero-or-more (any " \t"))
  4723. "#+caption"
  4724. (optional "[" (zero-or-more any) "]")
  4725. ":")
  4726. (zero-or-more (any " \t")))))
  4727. (add-text-properties (line-beginning-position) (match-end 1)
  4728. '(font-lock-fontified t face org-meta-line))
  4729. (add-text-properties (match-end 0) (line-end-position)
  4730. '(font-lock-fontified t face org-block))
  4731. t)
  4732. ((member dc3 '(" " ""))
  4733. ;; Just a comment, the plus was not there
  4734. (org-remove-flyspell-overlays-in beg (match-end 0))
  4735. (add-text-properties
  4736. beg (match-end 0)
  4737. '(font-lock-fontified t face font-lock-comment-face)))
  4738. (t ;; Just any other in-buffer setting, but not indented
  4739. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4740. (remove-text-properties (match-beginning 0) (match-end 0)
  4741. '(display t invisible t intangible t))
  4742. (add-text-properties beg (match-end 0)
  4743. '(font-lock-fontified t face org-meta-line))
  4744. t))))))
  4745. (defun org-fontify-drawers (limit)
  4746. "Fontify drawers."
  4747. (when (re-search-forward org-drawer-regexp limit t)
  4748. (add-text-properties (1- (match-beginning 1)) (1+ (match-end 1))
  4749. '(font-lock-fontified t face org-drawer))
  4750. (org-remove-flyspell-overlays-in
  4751. (line-beginning-position) (line-beginning-position 2))
  4752. t))
  4753. (defun org-fontify-macros (limit)
  4754. "Fontify macros."
  4755. (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
  4756. (let ((begin (match-beginning 0))
  4757. (opening-end (match-beginning 1)))
  4758. (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
  4759. (match-string 1))
  4760. (let ((end (match-end 1))
  4761. (closing-start (match-beginning 1)))
  4762. (add-text-properties
  4763. begin end
  4764. '(font-lock-multiline t font-lock-fontified t face org-macro))
  4765. (org-remove-flyspell-overlays-in begin end)
  4766. (when org-hide-macro-markers
  4767. (add-text-properties begin opening-end '(invisible t))
  4768. (add-text-properties closing-start end '(invisible t)))
  4769. t)))))
  4770. (defun org-fontify-extend-region (beg end _old-len)
  4771. (let ((end (if (progn (goto-char end) (looking-at-p "^[*#]"))
  4772. (1+ end) end))
  4773. (begin-re "\\(\\\\\\[\\|\\(#\\+begin_\\|\\\\begin{\\)\\S-+\\)")
  4774. (end-re "\\(\\\\\\]\\|\\(#\\+end_\\|\\\\end{\\)\\S-+\\)")
  4775. (extend
  4776. (lambda (r1 r2 dir)
  4777. (let ((re (replace-regexp-in-string
  4778. "\\(begin\\|end\\)" r1
  4779. (replace-regexp-in-string
  4780. "[][]" r2
  4781. (match-string-no-properties 0)))))
  4782. (re-search-forward (regexp-quote re) nil t dir)))))
  4783. (goto-char beg)
  4784. (back-to-indentation)
  4785. (save-match-data
  4786. (cond ((looking-at end-re)
  4787. (cons (or (funcall extend "begin" "[" -1) beg) end))
  4788. ((looking-at begin-re)
  4789. (cons beg (or (funcall extend "end" "]" 1) end)))
  4790. (t (cons beg end))))))
  4791. (defun org-activate-footnote-links (limit)
  4792. "Add text properties for footnotes."
  4793. (let ((fn (org-footnote-next-reference-or-definition limit)))
  4794. (when fn
  4795. (let* ((beg (nth 1 fn))
  4796. (end (nth 2 fn))
  4797. (label (car fn))
  4798. (referencep (/= (line-beginning-position) beg)))
  4799. (when (and referencep (nth 3 fn))
  4800. (save-excursion
  4801. (goto-char beg)
  4802. (search-forward (or label "fn:"))
  4803. (org-remove-flyspell-overlays-in beg (match-end 0))))
  4804. (add-text-properties beg end
  4805. (list 'mouse-face 'highlight
  4806. 'keymap org-mouse-map
  4807. 'help-echo
  4808. (if referencep "Footnote reference"
  4809. "Footnote definition")
  4810. 'font-lock-fontified t
  4811. 'font-lock-multiline t
  4812. 'face 'org-footnote))))))
  4813. (defun org-activate-dates (limit)
  4814. "Add text properties for dates."
  4815. (when (and (re-search-forward org-tsr-regexp-both limit t)
  4816. (not (equal (char-before (match-beginning 0)) 91)))
  4817. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4818. (add-text-properties (match-beginning 0) (match-end 0)
  4819. (list 'mouse-face 'highlight
  4820. 'keymap org-mouse-map))
  4821. (org-rear-nonsticky-at (match-end 0))
  4822. (when org-display-custom-times
  4823. ;; If it's a date range, activate custom time for second date.
  4824. (when (match-end 3)
  4825. (org-display-custom-time (match-beginning 3) (match-end 3)))
  4826. (org-display-custom-time (match-beginning 1) (match-end 1)))
  4827. t))
  4828. (defun org-activate-target-links (limit)
  4829. "Add text properties for target matches."
  4830. (when org-target-link-regexp
  4831. (let ((case-fold-search t))
  4832. ;; `org-target-link-regexp' matches one character before the
  4833. ;; actual target.
  4834. (unless (bolp) (forward-char -1))
  4835. (when (re-search-forward org-target-link-regexp limit t)
  4836. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4837. (add-text-properties (match-beginning 1) (match-end 1)
  4838. (list 'mouse-face 'highlight
  4839. 'keymap org-mouse-map
  4840. 'help-echo "Radio target link"
  4841. 'org-linked-text t))
  4842. (org-rear-nonsticky-at (match-end 1))
  4843. t))))
  4844. (defvar org-latex-and-related-regexp nil
  4845. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  4846. (defun org-compute-latex-and-related-regexp ()
  4847. "Compute regular expression for LaTeX, entities and sub/superscript.
  4848. Result depends on variable `org-highlight-latex-and-related'."
  4849. (let ((re-sub
  4850. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  4851. ((eq org-use-sub-superscripts '{})
  4852. (list org-match-substring-with-braces-regexp))
  4853. (org-use-sub-superscripts (list org-match-substring-regexp))))
  4854. (re-latex
  4855. (when (or (memq 'latex org-highlight-latex-and-related)
  4856. (memq 'native org-highlight-latex-and-related))
  4857. (let ((matchers (plist-get org-format-latex-options :matchers)))
  4858. (delq nil
  4859. (mapcar (lambda (x)
  4860. (and (member (car x) matchers) (nth 1 x)))
  4861. org-latex-regexps)))))
  4862. (re-entities
  4863. (when (memq 'entities org-highlight-latex-and-related)
  4864. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\
  4865. \\($\\|{}\\|[^[:alpha:]]\\)"))))
  4866. (setq-local org-latex-and-related-regexp
  4867. (mapconcat #'identity
  4868. (append re-latex re-entities re-sub)
  4869. "\\|"))))
  4870. (defun org-do-latex-and-related (limit)
  4871. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  4872. Stop at first highlighted object, if any. Return t if some
  4873. highlighting was done, nil otherwise."
  4874. (when (org-string-nw-p org-latex-and-related-regexp)
  4875. (let ((latex-prefix-re (rx (or "$" "\\(" "\\[")))
  4876. (blank-line-re (rx (and "\n" (zero-or-more (or " " "\t")) "\n"))))
  4877. (catch 'found
  4878. (while (and (< (point) limit)
  4879. (re-search-forward org-latex-and-related-regexp nil t))
  4880. (cond
  4881. ((>= (match-beginning 0) limit)
  4882. (throw 'found nil))
  4883. ((cl-some (lambda (f)
  4884. (memq f '(org-code org-verbatim underline
  4885. org-special-keyword)))
  4886. (save-excursion
  4887. (goto-char (1+ (match-beginning 0)))
  4888. (face-at-point nil t))))
  4889. ;; Try to limit false positives. In this case, ignore
  4890. ;; $$...$$, \(...\), and \[...\] LaTeX constructs if they
  4891. ;; contain an empty line.
  4892. ((save-excursion
  4893. (goto-char (match-beginning 0))
  4894. (and (looking-at-p latex-prefix-re)
  4895. (save-match-data
  4896. (re-search-forward blank-line-re (1- (match-end 0)) t)))))
  4897. (t
  4898. (let* ((offset (if (memq (char-after (1+ (match-beginning 0)))
  4899. '(?_ ?^))
  4900. 1
  4901. 0))
  4902. (start (+ offset (match-beginning 0)))
  4903. (end (match-end 0)))
  4904. (if (memq 'native org-highlight-latex-and-related)
  4905. (org-src-font-lock-fontify-block "latex" start end)
  4906. (font-lock-prepend-text-property start end
  4907. 'face 'org-latex-and-related))
  4908. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  4909. '(font-lock-multiline t))
  4910. (throw 'found t)))))
  4911. nil))))
  4912. (defun org-restart-font-lock ()
  4913. "Restart `font-lock-mode', to force refontification."
  4914. (when font-lock-mode
  4915. (font-lock-mode -1)
  4916. (font-lock-mode 1)))
  4917. (defun org-activate-tags (limit)
  4918. (when (re-search-forward org-tag-line-re limit t)
  4919. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4920. (add-text-properties (match-beginning 1) (match-end 1)
  4921. (list 'mouse-face 'highlight
  4922. 'keymap org-mouse-map))
  4923. (org-rear-nonsticky-at (match-end 1))
  4924. t))
  4925. (defun org-outline-level ()
  4926. "Compute the outline level of the heading at point.
  4927. If this is called at a normal headline, the level is the number
  4928. of stars. Use `org-reduced-level' to remove the effect of
  4929. `org-odd-levels'. Unlike to `org-current-level', this function
  4930. takes into consideration inlinetasks."
  4931. (org-with-wide-buffer
  4932. (end-of-line)
  4933. (if (re-search-backward org-outline-regexp-bol nil t)
  4934. (1- (- (match-end 0) (match-beginning 0)))
  4935. 0)))
  4936. (defvar org-font-lock-keywords nil)
  4937. (defsubst org-re-property (property &optional literal allow-null value)
  4938. "Return a regexp matching a PROPERTY line.
  4939. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  4940. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  4941. non-nil, match properties even without a value.
  4942. Match group 3 is set to the value when it exists. If there is no
  4943. value and ALLOW-NULL is non-nil, it is set to the empty string.
  4944. With optional argument VALUE, match only property lines with
  4945. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  4946. unless LITERAL is non-nil."
  4947. (concat
  4948. "^\\(?4:[ \t]*\\)"
  4949. (format "\\(?1::\\(?2:%s\\):\\)"
  4950. (if literal property (regexp-quote property)))
  4951. (cond (value
  4952. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  4953. (if literal value (regexp-quote value))))
  4954. (allow-null
  4955. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  4956. (t
  4957. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  4958. (defconst org-property-re
  4959. (org-re-property "\\S-+" 'literal t)
  4960. "Regular expression matching a property line.
  4961. There are four matching groups:
  4962. 1: :PROPKEY: including the leading and trailing colon,
  4963. 2: PROPKEY without the leading and trailing colon,
  4964. 3: PROPVAL without leading or trailing spaces,
  4965. 4: the indentation of the current line,
  4966. 5: trailing whitespace.")
  4967. (defvar org-font-lock-hook nil
  4968. "Functions to be called for special font lock stuff.")
  4969. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  4970. (defvar org-font-lock-set-keywords-hook nil
  4971. "Functions that can manipulate `org-font-lock-extra-keywords'.
  4972. This is called after `org-font-lock-extra-keywords' is defined, but before
  4973. it is installed to be used by font lock. This can be useful if something
  4974. needs to be inserted at a specific position in the font-lock sequence.")
  4975. (defun org-font-lock-hook (limit)
  4976. "Run `org-font-lock-hook' within LIMIT."
  4977. (run-hook-with-args 'org-font-lock-hook limit))
  4978. (defun org-set-font-lock-defaults ()
  4979. "Set font lock defaults for the current buffer."
  4980. (let ((org-font-lock-extra-keywords
  4981. (list
  4982. ;; Call the hook
  4983. '(org-font-lock-hook)
  4984. ;; Headlines
  4985. `(,(if org-fontify-whole-heading-line
  4986. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  4987. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  4988. (1 (org-get-level-face 1))
  4989. (2 (org-get-level-face 2))
  4990. (3 (org-get-level-face 3)))
  4991. ;; Table lines
  4992. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  4993. (1 'org-table t))
  4994. ;; Table internals
  4995. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  4996. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  4997. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  4998. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  4999. ;; Properties
  5000. (list org-property-re
  5001. '(1 'org-special-keyword t)
  5002. '(3 'org-property-value t))
  5003. ;; Drawers
  5004. '(org-fontify-drawers)
  5005. ;; Link related fontification.
  5006. '(org-activate-links)
  5007. (when (memq 'tag org-highlight-links) '(org-activate-tags (1 'org-tag prepend)))
  5008. (when (memq 'radio org-highlight-links) '(org-activate-target-links (1 'org-link t)))
  5009. (when (memq 'date org-highlight-links) '(org-activate-dates (0 'org-date t)))
  5010. (when (memq 'footnote org-highlight-links) '(org-activate-footnote-links))
  5011. ;; Targets.
  5012. (list org-radio-target-regexp '(0 'org-target t))
  5013. (list org-target-regexp '(0 'org-target t))
  5014. ;; Diary sexps.
  5015. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5016. ;; Macro
  5017. '(org-fontify-macros)
  5018. ;; TODO keyword
  5019. (list (format org-heading-keyword-regexp-format
  5020. org-todo-regexp)
  5021. '(2 (org-get-todo-face 2) prepend))
  5022. ;; TODO
  5023. (when org-fontify-todo-headline
  5024. (list (format org-heading-keyword-regexp-format
  5025. (concat
  5026. "\\(?:"
  5027. (mapconcat 'regexp-quote org-not-done-keywords "\\|")
  5028. "\\)"))
  5029. '(2 'org-headline-todo prepend)))
  5030. ;; DONE
  5031. (when org-fontify-done-headline
  5032. (list (format org-heading-keyword-regexp-format
  5033. (concat
  5034. "\\(?:"
  5035. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5036. "\\)"))
  5037. '(2 'org-headline-done prepend)))
  5038. ;; Priorities
  5039. '(org-font-lock-add-priority-faces)
  5040. ;; Tags
  5041. '(org-font-lock-add-tag-faces)
  5042. ;; Tags groups
  5043. (when (and org-group-tags org-tag-groups-alist)
  5044. (list (concat org-outline-regexp-bol ".+\\(:"
  5045. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5046. ":\\).*$")
  5047. '(1 'org-tag-group prepend)))
  5048. ;; Special keywords
  5049. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5050. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5051. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5052. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5053. ;; Emphasis
  5054. (when org-fontify-emphasized-text '(org-do-emphasis-faces))
  5055. ;; Checkboxes
  5056. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5057. 1 'org-checkbox prepend)
  5058. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5059. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5060. (0 (org-get-checkbox-statistics-face) prepend)))
  5061. ;; Description list items
  5062. '("\\(?:^[ \t]*[-+]\\|^[ \t]+[*]\\)[ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5063. 1 'org-list-dt prepend)
  5064. ;; Inline export snippets
  5065. '("\\(@@\\)\\([a-z-]+:\\).*?\\(@@\\)"
  5066. (1 'font-lock-comment-face t)
  5067. (2 'org-tag t)
  5068. (3 'font-lock-comment-face t))
  5069. ;; ARCHIVEd headings
  5070. (list (concat
  5071. org-outline-regexp-bol
  5072. "\\(.*:" org-archive-tag ":.*\\)")
  5073. '(1 'org-archived prepend))
  5074. ;; Specials
  5075. '(org-do-latex-and-related)
  5076. '(org-fontify-entities)
  5077. '(org-raise-scripts)
  5078. ;; Code
  5079. '(org-activate-code (1 'org-code t))
  5080. ;; COMMENT
  5081. (list (format
  5082. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5083. org-todo-regexp
  5084. org-comment-string)
  5085. '(9 'org-special-keyword t))
  5086. ;; Blocks and meta lines
  5087. '(org-fontify-meta-lines-and-blocks)
  5088. ;; Citations
  5089. '(org-cite-activate))))
  5090. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5091. (run-hooks 'org-font-lock-set-keywords-hook)
  5092. ;; Now set the full font-lock-keywords
  5093. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5094. (setq-local font-lock-defaults
  5095. '(org-font-lock-keywords t nil nil backward-paragraph))
  5096. (setq-local font-lock-extend-after-change-region-function
  5097. #'org-fontify-extend-region)
  5098. (kill-local-variable 'font-lock-keywords)
  5099. nil))
  5100. (defun org-toggle-pretty-entities ()
  5101. "Toggle the composition display of entities as UTF8 characters."
  5102. (interactive)
  5103. (setq-local org-pretty-entities (not org-pretty-entities))
  5104. (org-restart-font-lock)
  5105. (if org-pretty-entities
  5106. (message "Entities are now displayed as UTF8 characters")
  5107. (save-restriction
  5108. (widen)
  5109. (decompose-region (point-min) (point-max))
  5110. (message "Entities are now displayed as plain text"))))
  5111. (defvar-local org-custom-properties-overlays nil
  5112. "List of overlays used for custom properties.")
  5113. (defun org-toggle-custom-properties-visibility ()
  5114. "Display or hide properties in `org-custom-properties'."
  5115. (interactive)
  5116. (if org-custom-properties-overlays
  5117. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5118. (setq org-custom-properties-overlays nil))
  5119. (when org-custom-properties
  5120. (org-with-wide-buffer
  5121. (goto-char (point-min))
  5122. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5123. (while (re-search-forward regexp nil t)
  5124. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5125. (when (and end (< (point) end))
  5126. ;; Hide first custom property in current drawer.
  5127. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5128. (overlay-put o 'invisible t)
  5129. (overlay-put o 'org-custom-property t)
  5130. (push o org-custom-properties-overlays))
  5131. ;; Hide additional custom properties in the same drawer.
  5132. (while (re-search-forward regexp end t)
  5133. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5134. (overlay-put o 'invisible t)
  5135. (overlay-put o 'org-custom-property t)
  5136. (push o org-custom-properties-overlays)))))
  5137. ;; Each entry is limited to a single property drawer.
  5138. (outline-next-heading)))))))
  5139. (defun org-fontify-entities (limit)
  5140. "Find an entity to fontify."
  5141. (let (ee)
  5142. (when org-pretty-entities
  5143. (catch 'match
  5144. ;; "\_ "-family is left out on purpose. Only the first one,
  5145. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5146. ;; confusing when adding a second white space character.
  5147. (while (re-search-forward
  5148. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5149. limit t)
  5150. (when (and (not (org-at-comment-p))
  5151. (setq ee (org-entity-get (match-string 1)))
  5152. (= (length (nth 6 ee)) 1))
  5153. (let* ((end (if (equal (match-string 2) "{}")
  5154. (match-end 2)
  5155. (match-end 1))))
  5156. (add-text-properties
  5157. (match-beginning 0) end
  5158. (list 'font-lock-fontified t))
  5159. (compose-region (match-beginning 0) end
  5160. (nth 6 ee) nil)
  5161. (backward-char 1)
  5162. (throw 'match t))))
  5163. nil))))
  5164. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5165. "Fontify string S like in Org mode."
  5166. (with-temp-buffer
  5167. (insert s)
  5168. (let ((org-odd-levels-only odd-levels))
  5169. (org-mode)
  5170. (org-font-lock-ensure)
  5171. (buffer-string))))
  5172. (defun org-get-level-face (n)
  5173. "Get the right face for match N in font-lock matching of headlines."
  5174. (let* ((org-l0 (- (match-end 2) (match-beginning 1) 1))
  5175. (org-l (if org-odd-levels-only (1+ (/ org-l0 2)) org-l0))
  5176. (org-f (if org-cycle-level-faces
  5177. (nth (% (1- org-l) org-n-level-faces) org-level-faces)
  5178. (nth (1- (min org-l org-n-level-faces)) org-level-faces))))
  5179. (cond
  5180. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5181. ((eq n 2) org-f)
  5182. (t (unless org-level-color-stars-only org-f)))))
  5183. (defun org-face-from-face-or-color (context inherit face-or-color)
  5184. "Create a face list that inherits INHERIT, but sets the foreground color.
  5185. When FACE-OR-COLOR is not a string, just return it."
  5186. (if (stringp face-or-color)
  5187. (list :inherit inherit
  5188. (cdr (assoc context org-faces-easy-properties))
  5189. face-or-color)
  5190. face-or-color))
  5191. (defun org-get-todo-face (kwd)
  5192. "Get the right face for a TODO keyword KWD.
  5193. If KWD is a number, get the corresponding match group."
  5194. (when (numberp kwd) (setq kwd (match-string kwd)))
  5195. (or (org-face-from-face-or-color
  5196. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5197. (and (member kwd org-done-keywords) 'org-done)
  5198. 'org-todo))
  5199. (defun org-get-priority-face (priority)
  5200. "Get the right face for PRIORITY.
  5201. PRIORITY is a character."
  5202. (or (org-face-from-face-or-color
  5203. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5204. 'org-priority))
  5205. (defun org-get-tag-face (tag)
  5206. "Get the right face for TAG.
  5207. If TAG is a number, get the corresponding match group."
  5208. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5209. (or (org-face-from-face-or-color
  5210. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5211. 'org-tag)))
  5212. (defvar org-priority-regexp) ; defined later in the file
  5213. (defun org-font-lock-add-priority-faces (limit)
  5214. "Add the special priority faces."
  5215. (while (re-search-forward (concat "^\\*+" org-priority-regexp) limit t)
  5216. (let ((beg (match-beginning 1))
  5217. (end (1+ (match-end 2))))
  5218. (add-face-text-property
  5219. beg end
  5220. (org-get-priority-face (string-to-char (match-string 2))))
  5221. (add-text-properties
  5222. beg end
  5223. (list 'font-lock-fontified t)))))
  5224. (defun org-font-lock-add-tag-faces (limit)
  5225. "Add the special tag faces."
  5226. (when (and org-tag-faces org-tags-special-faces-re)
  5227. (while (re-search-forward org-tags-special-faces-re limit t)
  5228. (add-face-text-property
  5229. (match-beginning 1)
  5230. (match-end 1)
  5231. (org-get-tag-face 1))
  5232. (add-text-properties (match-beginning 1) (match-end 1)
  5233. (list 'font-lock-fontified t))
  5234. (backward-char 1))))
  5235. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5236. "Remove fontification and activation overlays from links."
  5237. (font-lock-default-unfontify-region beg end)
  5238. (let* ((buffer-undo-list t)
  5239. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5240. (inhibit-modification-hooks t)
  5241. deactivate-mark buffer-file-name buffer-file-truename)
  5242. (decompose-region beg end)
  5243. (remove-text-properties beg end
  5244. '(mouse-face t keymap t org-linked-text t
  5245. invisible t intangible t
  5246. org-emphasis t))
  5247. (org-remove-font-lock-display-properties beg end)))
  5248. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5249. ((raise 0.3) (height 0.7))
  5250. ((raise -0.5))
  5251. ((raise 0.5)))
  5252. "Display properties for showing superscripts and subscripts.")
  5253. (defun org-remove-font-lock-display-properties (beg end)
  5254. "Remove specific display properties that have been added by font lock.
  5255. The will remove the raise properties that are used to show superscripts
  5256. and subscripts."
  5257. (let (next prop)
  5258. (while (< beg end)
  5259. (setq next (next-single-property-change beg 'display nil end)
  5260. prop (get-text-property beg 'display))
  5261. (when (member prop org-script-display)
  5262. (put-text-property beg next 'display nil))
  5263. (setq beg next))))
  5264. (defun org-raise-scripts (limit)
  5265. "Add raise properties to sub/superscripts."
  5266. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5267. (re-search-forward
  5268. (if (eq org-use-sub-superscripts t)
  5269. org-match-substring-regexp
  5270. org-match-substring-with-braces-regexp)
  5271. limit t))
  5272. (let* ((pos (point)) table-p comment-p
  5273. (mpos (match-beginning 3))
  5274. (emph-p (get-text-property mpos 'org-emphasis))
  5275. (link-p (get-text-property mpos 'mouse-face))
  5276. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5277. (goto-char (point-at-bol))
  5278. (setq table-p (looking-at-p org-table-dataline-regexp)
  5279. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5280. (goto-char pos)
  5281. ;; Handle a_b^c
  5282. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5283. (unless (or comment-p emph-p link-p keyw-p)
  5284. (put-text-property (match-beginning 3) (match-end 0)
  5285. 'display
  5286. (if (equal (char-after (match-beginning 2)) ?^)
  5287. (nth (if table-p 3 1) org-script-display)
  5288. (nth (if table-p 2 0) org-script-display)))
  5289. (add-text-properties (match-beginning 2) (match-end 2)
  5290. (list 'invisible t))
  5291. (when (and (eq (char-after (match-beginning 3)) ?{)
  5292. (eq (char-before (match-end 3)) ?}))
  5293. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5294. (list 'invisible t))
  5295. (add-text-properties (1- (match-end 3)) (match-end 3)
  5296. (list 'invisible t))))
  5297. t)))
  5298. (defun org-remove-empty-overlays-at (pos)
  5299. "Remove outline overlays that do not contain non-white stuff."
  5300. (dolist (o (overlays-at pos))
  5301. (and (eq 'outline (overlay-get o 'invisible))
  5302. (not (string-match-p
  5303. "\\S-" (buffer-substring (overlay-start o)
  5304. (overlay-end o))))
  5305. (delete-overlay o))))
  5306. (defun org-show-empty-lines-in-parent ()
  5307. "Move to the parent and re-show empty lines before visible headlines."
  5308. (save-excursion
  5309. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  5310. (org-cycle-show-empty-lines context))))
  5311. (defun org-files-list ()
  5312. "Return `org-agenda-files' list, plus all open Org files.
  5313. This is useful for operations that need to scan all of a user's
  5314. open and agenda-wise Org files."
  5315. (let ((files (mapcar #'expand-file-name (org-agenda-files))))
  5316. (dolist (buf (buffer-list))
  5317. (with-current-buffer buf
  5318. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  5319. (cl-pushnew (expand-file-name (buffer-file-name)) files
  5320. :test #'equal))))
  5321. files))
  5322. (defsubst org-entry-beginning-position ()
  5323. "Return the beginning position of the current entry."
  5324. (save-excursion (org-back-to-heading t) (point)))
  5325. (defsubst org-entry-end-position ()
  5326. "Return the end position of the current entry."
  5327. (save-excursion (outline-next-heading) (point)))
  5328. (defun org-subtree-end-visible-p ()
  5329. "Is the end of the current subtree visible?"
  5330. (pos-visible-in-window-p
  5331. (save-excursion (org-end-of-subtree t) (point))))
  5332. (defun org-first-headline-recenter ()
  5333. "Move cursor to the first headline and recenter the headline."
  5334. (let ((window (get-buffer-window)))
  5335. (when window
  5336. (goto-char (point-min))
  5337. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  5338. (set-window-start window (line-beginning-position))))))
  5339. ;;; Visibility (headlines, blocks, drawers)
  5340. ;;;; Headlines visibility
  5341. (defun org-show-entry ()
  5342. "Show the body directly following its heading.
  5343. Show the heading too, if it is currently invisible."
  5344. (interactive)
  5345. (save-excursion
  5346. (org-back-to-heading-or-point-min t)
  5347. (org-flag-region
  5348. (line-end-position 0)
  5349. (save-excursion
  5350. (if (re-search-forward
  5351. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  5352. (match-beginning 1)
  5353. (point-max)))
  5354. nil
  5355. 'outline)
  5356. (org-cycle-hide-drawers 'children)))
  5357. (defun org-hide-entry ()
  5358. "Hide the body directly following its heading."
  5359. (interactive)
  5360. (save-excursion
  5361. (org-back-to-heading-or-point-min t)
  5362. (when (org-at-heading-p) (forward-line))
  5363. (org-flag-region
  5364. (line-end-position 0)
  5365. (save-excursion
  5366. (if (re-search-forward
  5367. (concat "[\r\n]" org-outline-regexp) nil t)
  5368. (line-end-position 0)
  5369. (point-max)))
  5370. t
  5371. 'outline)))
  5372. (defun org-show-children (&optional level)
  5373. "Show all direct subheadings of this heading.
  5374. Prefix arg LEVEL is how many levels below the current level
  5375. should be shown. Default is enough to cause the following
  5376. heading to appear."
  5377. (interactive "p")
  5378. (unless (org-before-first-heading-p)
  5379. (save-excursion
  5380. (org-with-limited-levels (org-back-to-heading t))
  5381. (let* ((current-level (funcall outline-level))
  5382. (max-level (org-get-valid-level
  5383. current-level
  5384. (if level (prefix-numeric-value level) 1)))
  5385. (end (save-excursion (org-end-of-subtree t t)))
  5386. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  5387. (past-first-child nil)
  5388. ;; Make sure to skip inlinetasks.
  5389. (re (format regexp-fmt
  5390. current-level
  5391. (cond
  5392. ((not (featurep 'org-inlinetask)) "")
  5393. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  5394. 3))
  5395. (t (1- org-inlinetask-min-level))))))
  5396. ;; Display parent heading.
  5397. (org-flag-heading nil)
  5398. (forward-line)
  5399. ;; Display children. First child may be deeper than expected
  5400. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  5401. ;; MAX-LEVEL accordingly.
  5402. (while (re-search-forward re end t)
  5403. (unless past-first-child
  5404. (setq re (format regexp-fmt
  5405. current-level
  5406. (max (funcall outline-level) max-level)))
  5407. (setq past-first-child t))
  5408. (org-flag-heading nil))))))
  5409. (defun org-show-subtree ()
  5410. "Show everything after this heading at deeper levels."
  5411. (interactive)
  5412. (org-flag-region
  5413. (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
  5414. ;;;; Blocks and drawers visibility
  5415. (defun org--hide-wrapper-toggle (element category force no-error)
  5416. "Toggle visibility for ELEMENT.
  5417. ELEMENT is a block or drawer type parsed element. CATEGORY is
  5418. either `block' or `drawer'. When FORCE is `off', show the block
  5419. or drawer. If it is non-nil, hide it unconditionally. Throw an
  5420. error when not at a block or drawer, unless NO-ERROR is non-nil.
  5421. Return a non-nil value when toggling is successful."
  5422. (let ((type (org-element-type element)))
  5423. (cond
  5424. ((memq type
  5425. (pcase category
  5426. (`drawer '(drawer property-drawer))
  5427. (`block '(center-block
  5428. comment-block dynamic-block example-block export-block
  5429. quote-block special-block src-block verse-block))
  5430. (_ (error "Unknown category: %S" category))))
  5431. (let* ((post (org-element-property :post-affiliated element))
  5432. (start (save-excursion
  5433. (goto-char post)
  5434. (line-end-position)))
  5435. (end (save-excursion
  5436. (goto-char (org-element-property :end element))
  5437. (skip-chars-backward " \t\n")
  5438. (line-end-position))))
  5439. ;; Do nothing when not before or at the block opening line or
  5440. ;; at the block closing line.
  5441. (unless (let ((eol (line-end-position)))
  5442. (and (> eol start) (/= eol end)))
  5443. (let* ((spec (if (eq category 'block) 'org-hide-block 'outline))
  5444. (flag
  5445. (cond ((eq force 'off) nil)
  5446. (force t)
  5447. ((eq spec (get-char-property start 'invisible)) nil)
  5448. (t t))))
  5449. (org-flag-region start end flag spec))
  5450. ;; When the block is hidden away, make sure point is left in
  5451. ;; a visible part of the buffer.
  5452. (when (invisible-p (max (1- (point)) (point-min)))
  5453. (goto-char post))
  5454. ;; Signal success.
  5455. t)))
  5456. (no-error nil)
  5457. (t
  5458. (user-error (if (eq category 'drawer)
  5459. "Not at a drawer"
  5460. "Not at a block"))))))
  5461. (defun org-hide-block-toggle (&optional force no-error element)
  5462. "Toggle the visibility of the current block.
  5463. When optional argument FORCE is `off', make block visible. If it
  5464. is non-nil, hide it unconditionally. Throw an error when not at
  5465. a block, unless NO-ERROR is non-nil. When optional argument
  5466. ELEMENT is provided, consider it instead of the current block.
  5467. Return a non-nil value when toggling is successful."
  5468. (interactive)
  5469. (org--hide-wrapper-toggle
  5470. (or element (org-element-at-point)) 'block force no-error))
  5471. (defun org-hide-drawer-toggle (&optional force no-error element)
  5472. "Toggle the visibility of the current drawer.
  5473. When optional argument FORCE is `off', make drawer visible. If
  5474. it is non-nil, hide it unconditionally. Throw an error when not
  5475. at a drawer, unless NO-ERROR is non-nil. When optional argument
  5476. ELEMENT is provided, consider it instead of the current drawer.
  5477. Return a non-nil value when toggling is successful."
  5478. (interactive)
  5479. (org--hide-wrapper-toggle
  5480. (or element (org-element-at-point)) 'drawer force no-error))
  5481. (defun org-hide-block-all ()
  5482. "Fold all blocks in the current buffer."
  5483. (interactive)
  5484. (org-show-all '(blocks))
  5485. (org-block-map 'org-hide-block-toggle))
  5486. (defun org-hide-drawer-all ()
  5487. "Fold all drawers in the current buffer."
  5488. (let ((begin (point-min))
  5489. (end (point-max)))
  5490. (org--hide-drawers begin end)))
  5491. (defun org-cycle-hide-drawers (state)
  5492. "Re-hide all drawers after a visibility state change.
  5493. STATE should be one of the symbols listed in the docstring of
  5494. `org-cycle-hook'."
  5495. (when (derived-mode-p 'org-mode)
  5496. (cond ((not (memq state '(overview folded contents)))
  5497. (let* ((global? (eq state 'all))
  5498. (beg (if global? (point-min) (line-beginning-position)))
  5499. (end (cond (global? (point-max))
  5500. ((eq state 'children) (org-entry-end-position))
  5501. (t (save-excursion (org-end-of-subtree t t))))))
  5502. (org--hide-drawers beg end)))
  5503. ((memq state '(overview contents))
  5504. ;; Hide drawers before first heading.
  5505. (let ((beg (point-min))
  5506. (end (save-excursion
  5507. (goto-char (point-min))
  5508. (if (org-before-first-heading-p)
  5509. (org-entry-end-position)
  5510. (point-min)))))
  5511. (when (< beg end)
  5512. (org--hide-drawers beg end)))))))
  5513. (defun org--hide-drawers (begin end)
  5514. "Hide all drawers between BEGIN and END."
  5515. (save-excursion
  5516. (goto-char begin)
  5517. (while (re-search-forward org-drawer-regexp end t)
  5518. (let* ((pair (get-char-property-and-overlay (line-beginning-position)
  5519. 'invisible))
  5520. (o (cdr-safe pair)))
  5521. (if (overlayp o) (goto-char (overlay-end o)) ;invisible drawer
  5522. (pcase (get-char-property-and-overlay (point) 'invisible)
  5523. (`(outline . ,o) (goto-char (overlay-end o))) ;already folded
  5524. (_
  5525. (let* ((drawer (org-element-at-point))
  5526. (type (org-element-type drawer)))
  5527. (when (memq type '(drawer property-drawer))
  5528. (org-hide-drawer-toggle t nil drawer)
  5529. ;; Make sure to skip drawer entirely or we might flag it
  5530. ;; another time when matching its ending line with
  5531. ;; `org-drawer-regexp'.
  5532. (goto-char (org-element-property :end drawer)))))))))))
  5533. ;;;; Visibility cycling
  5534. (defvar-local org-cycle-global-status nil)
  5535. (put 'org-cycle-global-status 'org-state t)
  5536. (defvar-local org-cycle-subtree-status nil)
  5537. (put 'org-cycle-subtree-status 'org-state t)
  5538. (defun org-show-all (&optional types)
  5539. "Show all contents in the visible part of the buffer.
  5540. By default, the function expands headings, blocks and drawers.
  5541. When optional argument TYPE is a list of symbols among `blocks',
  5542. `drawers' and `headings', to only expand one specific type."
  5543. (interactive)
  5544. (let ((types (or types '(blocks drawers headings))))
  5545. (when (memq 'blocks types)
  5546. (org-flag-region (point-min) (point-max) nil 'org-hide-block))
  5547. (cond
  5548. ;; Fast path. Since headings and drawers share the same
  5549. ;; invisible spec, clear everything in one go.
  5550. ((and (memq 'headings types)
  5551. (memq 'drawers types))
  5552. (org-flag-region (point-min) (point-max) nil 'outline))
  5553. ((memq 'headings types)
  5554. (org-flag-region (point-min) (point-max) nil 'outline)
  5555. (org-cycle-hide-drawers 'all))
  5556. ((memq 'drawers types)
  5557. (save-excursion
  5558. (goto-char (point-min))
  5559. (while (re-search-forward org-drawer-regexp nil t)
  5560. (let* ((pair (get-char-property-and-overlay (line-beginning-position)
  5561. 'invisible))
  5562. (o (cdr-safe pair)))
  5563. (if (overlayp o) (goto-char (overlay-end o))
  5564. (pcase (get-char-property-and-overlay (point) 'invisible)
  5565. (`(outline . ,o)
  5566. (goto-char (overlay-end o))
  5567. (delete-overlay o))
  5568. (_ nil))))))))))
  5569. ;;;###autoload
  5570. (defun org-cycle (&optional arg)
  5571. "TAB-action and visibility cycling for Org mode.
  5572. This is the command invoked in Org mode by the `TAB' key. Its main
  5573. purpose is outline visibility cycling, but it also invokes other actions
  5574. in special contexts.
  5575. When this function is called with a `\\[universal-argument]' prefix, rotate \
  5576. the entire
  5577. buffer through 3 states (global cycling)
  5578. 1. OVERVIEW: Show only top-level headlines.
  5579. 2. CONTENTS: Show all headlines of all levels, but no body text.
  5580. 3. SHOW ALL: Show everything.
  5581. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  5582. switch to the startup visibility,
  5583. determined by the variable `org-startup-folded', and by any VISIBILITY
  5584. properties in the buffer.
  5585. With a `\\[universal-argument] \\[universal-argument] \
  5586. \\[universal-argument]' prefix argument, show the entire buffer, including
  5587. any drawers.
  5588. When inside a table, re-align the table and move to the next field.
  5589. When point is at the beginning of a headline, rotate the subtree started
  5590. by this line through 3 different states (local cycling)
  5591. 1. FOLDED: Only the main headline is shown.
  5592. 2. CHILDREN: The main headline and the direct children are shown.
  5593. From this state, you can move to one of the children
  5594. and zoom in further.
  5595. 3. SUBTREE: Show the entire subtree, including body text.
  5596. If there is no subtree, switch directly from CHILDREN to FOLDED.
  5597. When point is at the beginning of an empty headline and the variable
  5598. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  5599. of the headline by demoting and promoting it to likely levels. This
  5600. speeds up creation document structure by pressing `TAB' once or several
  5601. times right after creating a new headline.
  5602. When there is a numeric prefix, go up to a heading with level ARG, do
  5603. a `show-subtree' and return to the previous cursor position. If ARG
  5604. is negative, go up that many levels.
  5605. When point is not at the beginning of a headline, execute the global
  5606. binding for `TAB', which is re-indenting the line. See the option
  5607. `org-cycle-emulate-tab' for details.
  5608. As a special case, if point is at the very beginning of the buffer, if
  5609. there is no headline there, and if the variable `org-cycle-global-at-bob'
  5610. is non-nil, this function acts as if called with prefix argument \
  5611. \(`\\[universal-argument] TAB',
  5612. same as `S-TAB') also when called without prefix argument."
  5613. (interactive "P")
  5614. (org-load-modules-maybe)
  5615. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  5616. (and org-cycle-level-after-item/entry-creation
  5617. (or (org-cycle-level)
  5618. (org-cycle-item-indentation))))
  5619. (let* ((limit-level
  5620. (or org-cycle-max-level
  5621. (and (boundp 'org-inlinetask-min-level)
  5622. org-inlinetask-min-level
  5623. (1- org-inlinetask-min-level))))
  5624. (nstars
  5625. (and limit-level
  5626. (if org-odd-levels-only
  5627. (1- (* 2 limit-level))
  5628. limit-level)))
  5629. (org-outline-regexp
  5630. (format "\\*%s " (if nstars (format "\\{1,%d\\}" nstars) "+"))))
  5631. (cond
  5632. ((equal arg '(16))
  5633. (setq last-command 'dummy)
  5634. (org-set-startup-visibility)
  5635. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  5636. ((equal arg '(64))
  5637. (org-show-all)
  5638. (org-unlogged-message "Entire buffer visible, including drawers"))
  5639. ((equal arg '(4)) (org-cycle-internal-global))
  5640. ;; Show-subtree, ARG levels up from here.
  5641. ((integerp arg)
  5642. (save-excursion
  5643. (org-back-to-heading)
  5644. (outline-up-heading (if (< arg 0) (- arg)
  5645. (- (funcall outline-level) arg)))
  5646. (org-show-subtree)))
  5647. ;; Global cycling at BOB: delegate to `org-cycle-internal-global'.
  5648. ((and org-cycle-global-at-bob
  5649. (bobp)
  5650. (not (looking-at org-outline-regexp)))
  5651. (let ((org-cycle-hook
  5652. (remq 'org-optimize-window-after-visibility-change
  5653. org-cycle-hook)))
  5654. (org-cycle-internal-global)))
  5655. ;; Try CDLaTeX TAB completion.
  5656. ((org-try-cdlatex-tab))
  5657. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  5658. ((and (featurep 'org-inlinetask)
  5659. (org-inlinetask-at-task-p)
  5660. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5661. (org-inlinetask-toggle-visibility))
  5662. (t
  5663. (let ((pos (point))
  5664. (element (org-element-at-point)))
  5665. (cond
  5666. ;; Try toggling visibility for block at point.
  5667. ((org-hide-block-toggle nil t element))
  5668. ;; Try toggling visibility for drawer at point.
  5669. ((org-hide-drawer-toggle nil t element))
  5670. ;; Table: enter it or move to the next field.
  5671. ((and (org-match-line "[ \t]*[|+]")
  5672. (org-element-lineage element '(table) t))
  5673. (if (and (eq 'table (org-element-type element))
  5674. (eq 'table.el (org-element-property :type element)))
  5675. (message (substitute-command-keys "\\<org-mode-map>\
  5676. Use `\\[org-edit-special]' to edit table.el tables"))
  5677. (org-table-justify-field-maybe)
  5678. (call-interactively #'org-table-next-field)))
  5679. ((run-hook-with-args-until-success
  5680. 'org-tab-after-check-for-table-hook))
  5681. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  5682. ((and (or (and org-cycle-include-plain-lists
  5683. (let ((item (org-element-lineage element
  5684. '(item plain-list)
  5685. t)))
  5686. (and item
  5687. (= (line-beginning-position)
  5688. (org-element-property :post-affiliated
  5689. item)))))
  5690. (org-match-line org-outline-regexp))
  5691. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5692. (org-cycle-internal-local))
  5693. ;; From there: TAB emulation and template completion.
  5694. (buffer-read-only (org-back-to-heading))
  5695. ((run-hook-with-args-until-success
  5696. 'org-tab-after-check-for-cycling-hook))
  5697. ((run-hook-with-args-until-success
  5698. 'org-tab-before-tab-emulation-hook))
  5699. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  5700. (or (not (bolp))
  5701. (not (looking-at org-outline-regexp))))
  5702. (call-interactively (global-key-binding (kbd "TAB"))))
  5703. ((or (eq org-cycle-emulate-tab t)
  5704. (and (memq org-cycle-emulate-tab '(white whitestart))
  5705. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  5706. (or (and (eq org-cycle-emulate-tab 'white)
  5707. (= (match-end 0) (point-at-eol)))
  5708. (and (eq org-cycle-emulate-tab 'whitestart)
  5709. (>= (match-end 0) pos)))))
  5710. (call-interactively (global-key-binding (kbd "TAB"))))
  5711. (t
  5712. (save-excursion
  5713. (org-back-to-heading)
  5714. (org-cycle))))))))))
  5715. (defun org-cycle-internal-global ()
  5716. "Do the global cycling action."
  5717. ;; Hack to avoid display of messages for .org attachments in Gnus
  5718. (let ((ga (string-match-p "\\*fontification" (buffer-name))))
  5719. (cond
  5720. ((and (eq last-command this-command)
  5721. (eq org-cycle-global-status 'overview))
  5722. ;; We just created the overview - now do table of contents
  5723. ;; This can be slow in very large buffers, so indicate action
  5724. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  5725. (unless ga (org-unlogged-message "CONTENTS..."))
  5726. (org-content)
  5727. (unless ga (org-unlogged-message "CONTENTS...done"))
  5728. (setq org-cycle-global-status 'contents)
  5729. (run-hook-with-args 'org-cycle-hook 'contents))
  5730. ((and (eq last-command this-command)
  5731. (eq org-cycle-global-status 'contents))
  5732. ;; We just showed the table of contents - now show everything
  5733. (run-hook-with-args 'org-pre-cycle-hook 'all)
  5734. (org-show-all '(headings blocks))
  5735. (unless ga (org-unlogged-message "SHOW ALL"))
  5736. (setq org-cycle-global-status 'all)
  5737. (run-hook-with-args 'org-cycle-hook 'all))
  5738. (t
  5739. ;; Default action: go to overview
  5740. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  5741. (org-overview)
  5742. (unless ga (org-unlogged-message "OVERVIEW"))
  5743. (setq org-cycle-global-status 'overview)
  5744. (run-hook-with-args 'org-cycle-hook 'overview)))))
  5745. (defvar org-called-with-limited-levels nil
  5746. "Non-nil when `org-with-limited-levels' is currently active.")
  5747. (defun org-cycle-internal-local ()
  5748. "Do the local cycling action."
  5749. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  5750. ;; First, determine end of headline (EOH), end of subtree or item
  5751. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  5752. (save-excursion
  5753. (if (org-at-item-p)
  5754. (progn
  5755. (beginning-of-line)
  5756. (setq struct (org-list-struct))
  5757. (setq eoh (point-at-eol))
  5758. (setq eos (org-list-get-item-end-before-blank (point) struct))
  5759. (setq has-children (org-list-has-child-p (point) struct)))
  5760. (org-back-to-heading)
  5761. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  5762. (setq eos (save-excursion
  5763. (org-end-of-subtree t t)
  5764. (unless (eobp) (forward-char -1))
  5765. (point)))
  5766. (setq has-children
  5767. (or
  5768. (save-excursion
  5769. (let ((level (funcall outline-level)))
  5770. (outline-next-heading)
  5771. (and (org-at-heading-p t)
  5772. (> (funcall outline-level) level))))
  5773. (and (eq org-cycle-include-plain-lists 'integrate)
  5774. (save-excursion
  5775. (org-list-search-forward (org-item-beginning-re) eos t))))))
  5776. ;; Determine end invisible part of buffer (EOL)
  5777. (beginning-of-line 2)
  5778. (while (and (not (eobp)) ;this is like `next-line'
  5779. (get-char-property (1- (point)) 'invisible))
  5780. (goto-char (next-single-char-property-change (point) 'invisible))
  5781. (and (eolp) (beginning-of-line 2)))
  5782. (setq eol (point)))
  5783. ;; Find out what to do next and set `this-command'
  5784. (cond
  5785. ((= eos eoh)
  5786. ;; Nothing is hidden behind this heading
  5787. (unless (org-before-first-heading-p)
  5788. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  5789. (org-unlogged-message "EMPTY ENTRY")
  5790. (setq org-cycle-subtree-status nil)
  5791. (save-excursion
  5792. (goto-char eos)
  5793. (outline-next-heading)
  5794. (when (org-invisible-p) (org-flag-heading nil))))
  5795. ((and (or (>= eol eos)
  5796. (not (string-match "\\S-" (buffer-substring eol eos))))
  5797. (or has-children
  5798. (not (setq children-skipped
  5799. org-cycle-skip-children-state-if-no-children))))
  5800. ;; Entire subtree is hidden in one line: children view
  5801. (unless (org-before-first-heading-p)
  5802. (run-hook-with-args 'org-pre-cycle-hook 'children))
  5803. (if (org-at-item-p)
  5804. (org-list-set-item-visibility (point-at-bol) struct 'children)
  5805. (org-show-entry)
  5806. (org-with-limited-levels (org-show-children))
  5807. (org-show-set-visibility 'tree)
  5808. ;; Fold every list in subtree to top-level items.
  5809. (when (eq org-cycle-include-plain-lists 'integrate)
  5810. (save-excursion
  5811. (org-back-to-heading)
  5812. (while (org-list-search-forward (org-item-beginning-re) eos t)
  5813. (beginning-of-line 1)
  5814. (let* ((struct (org-list-struct))
  5815. (prevs (org-list-prevs-alist struct))
  5816. (end (org-list-get-bottom-point struct)))
  5817. (dolist (e (org-list-get-all-items (point) struct prevs))
  5818. (org-list-set-item-visibility e struct 'folded))
  5819. (goto-char (if (< end eos) end eos)))))))
  5820. (org-unlogged-message "CHILDREN")
  5821. (save-excursion
  5822. (goto-char eos)
  5823. (outline-next-heading)
  5824. (when (org-invisible-p) (org-flag-heading nil)))
  5825. (setq org-cycle-subtree-status 'children)
  5826. (unless (org-before-first-heading-p)
  5827. (run-hook-with-args 'org-cycle-hook 'children)))
  5828. ((or children-skipped
  5829. (and (eq last-command this-command)
  5830. (eq org-cycle-subtree-status 'children)))
  5831. ;; We just showed the children, or no children are there,
  5832. ;; now show everything.
  5833. (unless (org-before-first-heading-p)
  5834. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  5835. (org-flag-region eoh eos nil 'outline)
  5836. (org-unlogged-message
  5837. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  5838. (setq org-cycle-subtree-status 'subtree)
  5839. (unless (org-before-first-heading-p)
  5840. (run-hook-with-args 'org-cycle-hook 'subtree)))
  5841. (t
  5842. ;; Default action: hide the subtree.
  5843. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  5844. (org-flag-region eoh eos t 'outline)
  5845. (org-unlogged-message "FOLDED")
  5846. (setq org-cycle-subtree-status 'folded)
  5847. (unless (org-before-first-heading-p)
  5848. (run-hook-with-args 'org-cycle-hook 'folded))))))
  5849. ;;;###autoload
  5850. (defun org-global-cycle (&optional arg)
  5851. "Cycle the global visibility. For details see `org-cycle'.
  5852. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  5853. With a numeric prefix, show all headlines up to that level."
  5854. (interactive "P")
  5855. (cond
  5856. ((integerp arg)
  5857. (org-content arg)
  5858. (setq org-cycle-global-status 'contents))
  5859. ((equal arg '(4))
  5860. (org-set-startup-visibility)
  5861. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  5862. (t
  5863. (org-cycle '(4)))))
  5864. (defun org-set-startup-visibility ()
  5865. "Set the visibility required by startup options and properties."
  5866. (cond
  5867. ((eq org-startup-folded t)
  5868. (org-overview))
  5869. ((eq org-startup-folded 'content)
  5870. (org-content))
  5871. ((eq org-startup-folded 'show2levels)
  5872. (org-content 2))
  5873. ((eq org-startup-folded 'show3levels)
  5874. (org-content 3))
  5875. ((eq org-startup-folded 'show4levels)
  5876. (org-content 4))
  5877. ((eq org-startup-folded 'show5levels)
  5878. (org-content 5))
  5879. ((or (eq org-startup-folded 'showeverything)
  5880. (eq org-startup-folded nil))
  5881. (org-show-all)))
  5882. (unless (eq org-startup-folded 'showeverything)
  5883. (when org-hide-block-startup (org-hide-block-all))
  5884. (org-set-visibility-according-to-property)
  5885. (org-cycle-hide-archived-subtrees 'all)
  5886. (org-cycle-hide-drawers 'all)
  5887. (org-cycle-show-empty-lines t)))
  5888. (defun org-set-visibility-according-to-property ()
  5889. "Switch subtree visibility according to VISIBILITY property."
  5890. (interactive)
  5891. (let ((regexp (org-re-property "VISIBILITY")))
  5892. (org-with-point-at 1
  5893. (while (re-search-forward regexp nil t)
  5894. (let ((state (match-string 3)))
  5895. (if (not (org-at-property-p)) (outline-next-heading)
  5896. (save-excursion
  5897. (org-back-to-heading t)
  5898. (org-flag-subtree t)
  5899. (org-reveal)
  5900. (pcase state
  5901. ("folded"
  5902. (org-flag-subtree t))
  5903. ("children"
  5904. (org-show-hidden-entry)
  5905. (org-show-children))
  5906. ("content"
  5907. (save-excursion
  5908. (save-restriction
  5909. (org-narrow-to-subtree)
  5910. (org-content))))
  5911. ((or "all" "showall")
  5912. (outline-show-subtree))
  5913. (_ nil)))
  5914. (org-end-of-subtree)))))))
  5915. (defun org-overview ()
  5916. "Switch to overview mode, showing only top-level headlines."
  5917. (interactive)
  5918. (org-show-all '(headings drawers))
  5919. (save-excursion
  5920. (goto-char (point-min))
  5921. (when (re-search-forward org-outline-regexp-bol nil t)
  5922. (let* ((last (line-end-position))
  5923. (level (- (match-end 0) (match-beginning 0) 1))
  5924. (regexp (format "^\\*\\{1,%d\\} " level)))
  5925. (while (re-search-forward regexp nil :move)
  5926. (org-flag-region last (line-end-position 0) t 'outline)
  5927. (setq last (line-end-position))
  5928. (setq level (- (match-end 0) (match-beginning 0) 1))
  5929. (setq regexp (format "^\\*\\{1,%d\\} " level)))
  5930. (org-flag-region last (point) t 'outline)))))
  5931. (defun org-content (&optional arg)
  5932. "Show all headlines in the buffer, like a table of contents.
  5933. With numerical argument N, show content up to level N."
  5934. (interactive "p")
  5935. (org-show-all '(headings drawers))
  5936. (save-excursion
  5937. (goto-char (point-max))
  5938. (let ((regexp (if (and (wholenump arg) (> arg 0))
  5939. (format "^\\*\\{1,%d\\} " arg)
  5940. "^\\*+ "))
  5941. (last (point)))
  5942. (while (re-search-backward regexp nil t)
  5943. (org-flag-region (line-end-position) last t 'outline)
  5944. (setq last (line-end-position 0))))))
  5945. (defvar org-scroll-position-to-restore nil
  5946. "Temporarily store scroll position to restore.")
  5947. (defun org-optimize-window-after-visibility-change (state)
  5948. "Adjust the window after a change in outline visibility.
  5949. This function is the default value of the hook `org-cycle-hook'."
  5950. (when (get-buffer-window (current-buffer))
  5951. (let ((repeat (eq last-command this-command)))
  5952. (unless repeat
  5953. (setq org-scroll-position-to-restore nil))
  5954. (cond
  5955. ((eq state 'content) nil)
  5956. ((eq state 'all) nil)
  5957. ((and org-scroll-position-to-restore repeat
  5958. (eq state 'folded))
  5959. (set-window-start nil org-scroll-position-to-restore))
  5960. ((eq state 'folded) nil)
  5961. ((eq state 'children)
  5962. (setq org-scroll-position-to-restore (window-start))
  5963. (or (org-subtree-end-visible-p) (recenter 1)))
  5964. ((eq state 'subtree)
  5965. (unless repeat
  5966. (setq org-scroll-position-to-restore (window-start)))
  5967. (or (org-subtree-end-visible-p) (recenter 1)))))))
  5968. (defun org-clean-visibility-after-subtree-move ()
  5969. "Fix visibility issues after moving a subtree."
  5970. ;; First, find a reasonable region to look at:
  5971. ;; Start two siblings above, end three below
  5972. (let* ((beg (save-excursion
  5973. (and (org-get-previous-sibling)
  5974. (org-get-previous-sibling))
  5975. (point)))
  5976. (end (save-excursion
  5977. (and (org-get-next-sibling)
  5978. (org-get-next-sibling)
  5979. (org-get-next-sibling))
  5980. (if (org-at-heading-p)
  5981. (point-at-eol)
  5982. (point))))
  5983. (level (looking-at "\\*+"))
  5984. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  5985. (save-excursion
  5986. (save-restriction
  5987. (narrow-to-region beg end)
  5988. (when re
  5989. ;; Properly fold already folded siblings
  5990. (goto-char (point-min))
  5991. (while (re-search-forward re nil t)
  5992. (when (and (not (org-invisible-p))
  5993. (org-invisible-p (line-end-position)))
  5994. (outline-hide-entry))))
  5995. (org-cycle-hide-drawers 'all)
  5996. (org-cycle-show-empty-lines 'overview)))))
  5997. (defun org-cycle-show-empty-lines (state)
  5998. "Show empty lines above all visible headlines.
  5999. The region to be covered depends on STATE when called through
  6000. `org-cycle-hook'. Lisp program can use t for STATE to get the
  6001. entire buffer covered. Note that an empty line is only shown if there
  6002. are at least `org-cycle-separator-lines' empty lines before the headline."
  6003. (when (/= org-cycle-separator-lines 0)
  6004. (save-excursion
  6005. (let* ((n (abs org-cycle-separator-lines))
  6006. (re (cond
  6007. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  6008. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  6009. (t (let ((ns (number-to-string (- n 2))))
  6010. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  6011. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  6012. beg end)
  6013. (cond
  6014. ((memq state '(overview contents t))
  6015. (setq beg (point-min) end (point-max)))
  6016. ((memq state '(children folded))
  6017. (setq beg (point)
  6018. end (progn (org-end-of-subtree t t)
  6019. (line-beginning-position 2)))))
  6020. (when beg
  6021. (goto-char beg)
  6022. (while (re-search-forward re end t)
  6023. (unless (get-char-property (match-end 1) 'invisible)
  6024. (let ((e (match-end 1))
  6025. (b (if (>= org-cycle-separator-lines 0)
  6026. (match-beginning 1)
  6027. (save-excursion
  6028. (goto-char (match-beginning 0))
  6029. (skip-chars-backward " \t\n")
  6030. (line-end-position)))))
  6031. (org-flag-region b e nil 'outline))))))))
  6032. ;; Never hide empty lines at the end of the file.
  6033. (save-excursion
  6034. (goto-char (point-max))
  6035. (outline-previous-heading)
  6036. (outline-end-of-heading)
  6037. (when (and (looking-at "[ \t\n]+")
  6038. (= (match-end 0) (point-max)))
  6039. (org-flag-region (point) (match-end 0) nil 'outline))))
  6040. ;;;; Reveal point location
  6041. (defun org-show-context (&optional key)
  6042. "Make sure point and context are visible.
  6043. Optional argument KEY, when non-nil, is a symbol. See
  6044. `org-show-context-detail' for allowed values and how much is to
  6045. be shown."
  6046. (org-show-set-visibility
  6047. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  6048. ((cdr (assq key org-show-context-detail)))
  6049. (t (cdr (assq 'default org-show-context-detail))))))
  6050. (defun org-show-set-visibility (detail)
  6051. "Set visibility around point according to DETAIL.
  6052. DETAIL is either nil, `minimal', `local', `ancestors',
  6053. `ancestors-full', `lineage', `tree', `canonical' or t. See
  6054. `org-show-context-detail' for more information."
  6055. ;; Show current heading and possibly its entry, following headline
  6056. ;; or all children.
  6057. (if (and (org-at-heading-p) (not (eq detail 'local)))
  6058. (org-flag-heading nil)
  6059. (org-show-entry)
  6060. ;; If point is hidden within a drawer or a block, make sure to
  6061. ;; expose it.
  6062. (dolist (o (overlays-at (point)))
  6063. (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
  6064. (delete-overlay o)))
  6065. (unless (org-before-first-heading-p)
  6066. (org-with-limited-levels
  6067. (cl-case detail
  6068. ((tree canonical t) (org-show-children))
  6069. ((nil minimal ancestors ancestors-full))
  6070. (t (save-excursion
  6071. (outline-next-heading)
  6072. (org-flag-heading nil)))))))
  6073. ;; Show whole subtree.
  6074. (when (eq detail 'ancestors-full) (org-show-subtree))
  6075. ;; Show all siblings.
  6076. (when (eq detail 'lineage) (org-show-siblings))
  6077. ;; Show ancestors, possibly with their children.
  6078. (when (memq detail '(ancestors ancestors-full lineage tree canonical t))
  6079. (save-excursion
  6080. (while (org-up-heading-safe)
  6081. (org-flag-heading nil)
  6082. (when (memq detail '(canonical t)) (org-show-entry))
  6083. (when (memq detail '(tree canonical t)) (org-show-children))))))
  6084. (defvar org-reveal-start-hook nil
  6085. "Hook run before revealing a location.")
  6086. (defun org-reveal (&optional siblings)
  6087. "Show current entry, hierarchy above it, and the following headline.
  6088. This can be used to show a consistent set of context around
  6089. locations exposed with `org-show-context'.
  6090. With optional argument SIBLINGS, on each level of the hierarchy all
  6091. siblings are shown. This repairs the tree structure to what it would
  6092. look like when opened with hierarchical calls to `org-cycle'.
  6093. With a \\[universal-argument] \\[universal-argument] prefix, \
  6094. go to the parent and show the entire tree."
  6095. (interactive "P")
  6096. (run-hooks 'org-reveal-start-hook)
  6097. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  6098. ((equal siblings '(16))
  6099. (save-excursion
  6100. (when (org-up-heading-safe)
  6101. (org-show-subtree)
  6102. (run-hook-with-args 'org-cycle-hook 'subtree))))
  6103. (t (org-show-set-visibility 'lineage))))
  6104. ;;; Indirect buffer display of subtrees
  6105. (defvar org-indirect-dedicated-frame nil
  6106. "This is the frame being used for indirect tree display.")
  6107. (defvar org-last-indirect-buffer nil)
  6108. (defun org-tree-to-indirect-buffer (&optional arg)
  6109. "Create indirect buffer and narrow it to current subtree.
  6110. With a numerical prefix ARG, go up to this level and then take that tree.
  6111. If ARG is negative, go up that many levels.
  6112. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6113. indirect buffer previously made with this command, to avoid proliferation of
  6114. indirect buffers. However, when you call the command with a \
  6115. `\\[universal-argument]' prefix, or
  6116. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  6117. so that you can work with several indirect buffers at the same time. If
  6118. `org-indirect-buffer-display' is `dedicated-frame', the \
  6119. `\\[universal-argument]' prefix also
  6120. requests that a new frame be made for the new buffer, so that the dedicated
  6121. frame is not changed."
  6122. (interactive "P")
  6123. (let ((cbuf (current-buffer))
  6124. (cwin (selected-window))
  6125. (pos (point))
  6126. beg end level heading ibuf)
  6127. (save-excursion
  6128. (org-back-to-heading t)
  6129. (when (numberp arg)
  6130. (setq level (org-outline-level))
  6131. (when (< arg 0) (setq arg (+ level arg)))
  6132. (while (> (setq level (org-outline-level)) arg)
  6133. (org-up-heading-safe)))
  6134. (setq beg (point)
  6135. heading (org-get-heading 'no-tags))
  6136. (org-end-of-subtree t t)
  6137. (when (org-at-heading-p) (backward-char 1))
  6138. (setq end (point)))
  6139. (when (and (buffer-live-p org-last-indirect-buffer)
  6140. (not (eq org-indirect-buffer-display 'new-frame))
  6141. (not arg))
  6142. (kill-buffer org-last-indirect-buffer))
  6143. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6144. org-last-indirect-buffer ibuf)
  6145. (cond
  6146. ((or (eq org-indirect-buffer-display 'new-frame)
  6147. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6148. (select-frame (make-frame))
  6149. (delete-other-windows)
  6150. (pop-to-buffer-same-window ibuf)
  6151. (org-set-frame-title heading))
  6152. ((eq org-indirect-buffer-display 'dedicated-frame)
  6153. (raise-frame
  6154. (select-frame (or (and org-indirect-dedicated-frame
  6155. (frame-live-p org-indirect-dedicated-frame)
  6156. org-indirect-dedicated-frame)
  6157. (setq org-indirect-dedicated-frame (make-frame)))))
  6158. (delete-other-windows)
  6159. (pop-to-buffer-same-window ibuf)
  6160. (org-set-frame-title (concat "Indirect: " heading)))
  6161. ((eq org-indirect-buffer-display 'current-window)
  6162. (pop-to-buffer-same-window ibuf))
  6163. ((eq org-indirect-buffer-display 'other-window)
  6164. (pop-to-buffer ibuf))
  6165. (t (error "Invalid value")))
  6166. (narrow-to-region beg end)
  6167. (org-show-all '(headings drawers blocks))
  6168. (goto-char pos)
  6169. (run-hook-with-args 'org-cycle-hook 'all)
  6170. (and (window-live-p cwin) (select-window cwin))))
  6171. (defun org-get-indirect-buffer (&optional buffer heading)
  6172. (setq buffer (or buffer (current-buffer)))
  6173. (let ((n 1) (base (buffer-name buffer)) bname)
  6174. (while (buffer-live-p
  6175. (get-buffer
  6176. (setq bname
  6177. (concat base "-"
  6178. (if heading (concat heading "-" (number-to-string n))
  6179. (number-to-string n))))))
  6180. (setq n (1+ n)))
  6181. (condition-case nil
  6182. (make-indirect-buffer buffer bname 'clone)
  6183. (error (make-indirect-buffer buffer bname)))))
  6184. (defun org-set-frame-title (title)
  6185. "Set the title of the current frame to the string TITLE."
  6186. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6187. ;;;; Structure editing
  6188. ;;; Inserting headlines
  6189. (defun org--blank-before-heading-p (&optional parent)
  6190. "Non-nil when an empty line should precede a new heading here.
  6191. When optional argument PARENT is non-nil, consider parent
  6192. headline instead of current one."
  6193. (pcase (assq 'heading org-blank-before-new-entry)
  6194. (`(heading . auto)
  6195. (save-excursion
  6196. (org-with-limited-levels
  6197. (unless (and (org-before-first-heading-p)
  6198. (not (outline-next-heading)))
  6199. (org-back-to-heading t)
  6200. (when parent (org-up-heading-safe))
  6201. (cond ((not (bobp))
  6202. (org-previous-line-empty-p))
  6203. ((outline-next-heading)
  6204. (org-previous-line-empty-p))
  6205. ;; Ignore trailing spaces on last buffer line.
  6206. ((progn (skip-chars-backward " \t") (bolp))
  6207. (org-previous-line-empty-p))
  6208. (t nil))))))
  6209. (`(heading . ,value) value)
  6210. (_ nil)))
  6211. (defun org-insert-heading (&optional arg invisible-ok top)
  6212. "Insert a new heading or an item with the same depth at point.
  6213. If point is at the beginning of a heading, insert a new heading
  6214. or a new headline above the current one. When at the beginning
  6215. of a regular line of text, turn it into a heading.
  6216. If point is in the middle of a line, split it and create a new
  6217. headline with the text in the current line after point (see
  6218. `org-M-RET-may-split-line' on how to modify this behavior). As
  6219. a special case, on a headline, splitting can only happen on the
  6220. title itself. E.g., this excludes breaking stars or tags.
  6221. With a `\\[universal-argument]' prefix, set \
  6222. `org-insert-heading-respect-content' to
  6223. a non-nil value for the duration of the command. This forces the
  6224. insertion of a heading after the current subtree, independently
  6225. on the location of point.
  6226. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6227. insert the heading at the end of the tree
  6228. above the current heading. For example, if point is within a
  6229. 2nd-level heading, then it will insert a 2nd-level heading at
  6230. the end of the 1st-level parent subtree.
  6231. When INVISIBLE-OK is set, stop at invisible headlines when going
  6232. back. This is important for non-interactive uses of the
  6233. command.
  6234. When optional argument TOP is non-nil, insert a level 1 heading,
  6235. unconditionally."
  6236. (interactive "P")
  6237. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6238. (level (org-current-level))
  6239. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6240. (cond
  6241. ((or org-insert-heading-respect-content
  6242. (member arg '((4) (16)))
  6243. (and (not invisible-ok)
  6244. (invisible-p (max (1- (point)) (point-min)))))
  6245. ;; Position point at the location of insertion. Make sure we
  6246. ;; end up on a visible headline if INVISIBLE-OK is nil.
  6247. (org-with-limited-levels
  6248. (if (not level) (outline-next-heading) ;before first headline
  6249. (org-back-to-heading invisible-ok)
  6250. (when (equal arg '(16)) (org-up-heading-safe))
  6251. (org-end-of-subtree)))
  6252. (unless (bolp) (insert "\n"))
  6253. (when (and blank? (save-excursion
  6254. (backward-char)
  6255. (org-before-first-heading-p)))
  6256. (insert "\n")
  6257. (backward-char))
  6258. (when (and (not level) (not (eobp)) (not (bobp)))
  6259. (when (org-at-heading-p) (insert "\n"))
  6260. (backward-char))
  6261. (unless (and blank? (org-previous-line-empty-p))
  6262. (org-N-empty-lines-before-current (if blank? 1 0)))
  6263. (insert stars " ")
  6264. ;; When INVISIBLE-OK is non-nil, ensure newly created headline
  6265. ;; is visible.
  6266. (unless invisible-ok
  6267. (pcase (get-char-property-and-overlay (point) 'invisible)
  6268. (`(outline . ,o)
  6269. (move-overlay o (overlay-start o) (line-end-position 0)))
  6270. (_ nil))))
  6271. ;; At a headline...
  6272. ((org-at-heading-p)
  6273. (cond ((bolp)
  6274. (when blank? (save-excursion (insert "\n")))
  6275. (save-excursion (insert stars " \n"))
  6276. (unless (and blank? (org-previous-line-empty-p))
  6277. (org-N-empty-lines-before-current (if blank? 1 0)))
  6278. (end-of-line))
  6279. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6280. (org-match-line org-complex-heading-regexp)
  6281. (org-pos-in-match-range (point) 4))
  6282. ;; Grab the text that should moved to the new headline.
  6283. ;; Preserve tags.
  6284. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6285. (if (looking-at "[ \t]*$") (replace-match "")
  6286. (org-align-tags))
  6287. (end-of-line)
  6288. (when blank? (insert "\n"))
  6289. (insert "\n" stars " ")
  6290. (when (org-string-nw-p split) (insert split))))
  6291. (t
  6292. (end-of-line)
  6293. (when blank? (insert "\n"))
  6294. (insert "\n" stars " "))))
  6295. ;; On regular text, turn line into a headline or split, if
  6296. ;; appropriate.
  6297. ((bolp)
  6298. (insert stars " ")
  6299. (unless (and blank? (org-previous-line-empty-p))
  6300. (org-N-empty-lines-before-current (if blank? 1 0))))
  6301. (t
  6302. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6303. (end-of-line))
  6304. (insert "\n" stars " ")
  6305. (unless (and blank? (org-previous-line-empty-p))
  6306. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6307. (run-hooks 'org-insert-heading-hook))
  6308. (defun org-N-empty-lines-before-current (n)
  6309. "Make the number of empty lines before current exactly N.
  6310. So this will delete or add empty lines."
  6311. (let ((column (current-column)))
  6312. (beginning-of-line)
  6313. (unless (bobp)
  6314. (let ((start (save-excursion
  6315. (skip-chars-backward " \r\t\n")
  6316. (line-end-position))))
  6317. (delete-region start (line-end-position 0))))
  6318. (insert (make-string n ?\n))
  6319. (move-to-column column)))
  6320. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6321. "Return the heading of the current entry, without the stars.
  6322. When NO-TAGS is non-nil, don't include tags.
  6323. When NO-TODO is non-nil, don't include TODO keywords.
  6324. When NO-PRIORITY is non-nil, don't include priority cookie.
  6325. When NO-COMMENT is non-nil, don't include COMMENT string.
  6326. Return nil before first heading."
  6327. (unless (org-before-first-heading-p)
  6328. (save-excursion
  6329. (org-back-to-heading t)
  6330. (let ((case-fold-search nil))
  6331. (looking-at org-complex-heading-regexp)
  6332. (let ((todo (and (not no-todo) (match-string 2)))
  6333. (priority (and (not no-priority) (match-string 3)))
  6334. (headline (pcase (match-string 4)
  6335. (`nil "")
  6336. ((and (guard no-comment) h)
  6337. (replace-regexp-in-string
  6338. (eval-when-compile
  6339. (format "\\`%s[ \t]+" org-comment-string))
  6340. "" h))
  6341. (h h)))
  6342. (tags (and (not no-tags) (match-string 5))))
  6343. (mapconcat #'identity
  6344. (delq nil (list todo priority headline tags))
  6345. " "))))))
  6346. (defun org-heading-components ()
  6347. "Return the components of the current heading.
  6348. This is a list with the following elements:
  6349. - the level as an integer
  6350. - the reduced level, different if `org-odd-levels-only' is set.
  6351. - the TODO keyword, or nil
  6352. - the priority character, like ?A, or nil if no priority is given
  6353. - the headline text itself, or the tags string if no headline text
  6354. - the tags string, or nil."
  6355. (save-excursion
  6356. (org-back-to-heading t)
  6357. (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
  6358. (list (length (match-string 1))
  6359. (org-reduced-level (length (match-string 1)))
  6360. (match-string-no-properties 2)
  6361. (and (match-end 3) (aref (match-string 3) 2))
  6362. (match-string-no-properties 4)
  6363. (match-string-no-properties 5)))))
  6364. (defun org-get-entry ()
  6365. "Get the entry text, after heading, entire subtree."
  6366. (save-excursion
  6367. (org-back-to-heading t)
  6368. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  6369. (defun org-edit-headline (&optional heading)
  6370. "Edit the current headline.
  6371. Set it to HEADING when provided."
  6372. (interactive)
  6373. (org-with-wide-buffer
  6374. (org-back-to-heading t)
  6375. (let ((case-fold-search nil))
  6376. (when (looking-at org-complex-heading-regexp)
  6377. (let* ((old (match-string-no-properties 4))
  6378. (new (save-match-data
  6379. (org-trim (or heading (read-string "Edit: " old))))))
  6380. (unless (equal old new)
  6381. (if old (replace-match new t t nil 4)
  6382. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  6383. (insert " " new))
  6384. (org-align-tags)
  6385. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  6386. (defun org-insert-heading-after-current ()
  6387. "Insert a new heading with same level as current, after current subtree."
  6388. (interactive)
  6389. (org-back-to-heading)
  6390. (org-insert-heading)
  6391. (org-move-subtree-down)
  6392. (end-of-line 1))
  6393. (defun org-insert-heading-respect-content (&optional invisible-ok)
  6394. "Insert heading with `org-insert-heading-respect-content' set to t."
  6395. (interactive)
  6396. (org-insert-heading '(4) invisible-ok))
  6397. (defun org-insert-todo-heading-respect-content (&optional force-state)
  6398. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  6399. (interactive)
  6400. (org-insert-todo-heading force-state '(4)))
  6401. (defun org-insert-todo-heading (arg &optional force-heading)
  6402. "Insert a new heading with the same level and TODO state as current heading.
  6403. If the heading has no TODO state, or if the state is DONE, use
  6404. the first state (TODO by default). Also with one prefix arg,
  6405. force first state. With two prefix args, force inserting at the
  6406. end of the parent subtree.
  6407. When called at a plain list item, insert a new item with an
  6408. unchecked check box."
  6409. (interactive "P")
  6410. (when (or force-heading (not (org-insert-item 'checkbox)))
  6411. (org-insert-heading (or (and (equal arg '(16)) '(16))
  6412. force-heading))
  6413. (save-excursion
  6414. (org-forward-heading-same-level -1)
  6415. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  6416. (let* ((new-mark-x
  6417. (if (or (equal arg '(4))
  6418. (not (match-beginning 2))
  6419. (member (match-string 2) org-done-keywords))
  6420. (car org-todo-keywords-1)
  6421. (match-string 2)))
  6422. (new-mark
  6423. (or
  6424. (run-hook-with-args-until-success
  6425. 'org-todo-get-default-hook new-mark-x nil)
  6426. new-mark-x)))
  6427. (beginning-of-line 1)
  6428. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  6429. (if org-treat-insert-todo-heading-as-state-change
  6430. (org-todo new-mark)
  6431. (insert new-mark " "))))
  6432. (when org-provide-todo-statistics
  6433. (org-update-parent-todo-statistics))))
  6434. (defun org-insert-subheading (arg)
  6435. "Insert a new subheading and demote it.
  6436. Works for outline headings and for plain lists alike."
  6437. (interactive "P")
  6438. (org-insert-heading arg)
  6439. (cond
  6440. ((org-at-heading-p) (org-do-demote))
  6441. ((org-at-item-p) (org-indent-item))))
  6442. (defun org-insert-todo-subheading (arg)
  6443. "Insert a new subheading with TODO keyword or checkbox and demote it.
  6444. Works for outline headings and for plain lists alike."
  6445. (interactive "P")
  6446. (org-insert-todo-heading arg)
  6447. (cond
  6448. ((org-at-heading-p) (org-do-demote))
  6449. ((org-at-item-p) (org-indent-item))))
  6450. ;;; Promotion and Demotion
  6451. (defvar org-after-demote-entry-hook nil
  6452. "Hook run after an entry has been demoted.
  6453. The cursor will be at the beginning of the entry.
  6454. When a subtree is being demoted, the hook will be called for each node.")
  6455. (defvar org-after-promote-entry-hook nil
  6456. "Hook run after an entry has been promoted.
  6457. The cursor will be at the beginning of the entry.
  6458. When a subtree is being promoted, the hook will be called for each node.")
  6459. (defun org-promote-subtree ()
  6460. "Promote the entire subtree.
  6461. See also `org-promote'."
  6462. (interactive)
  6463. (save-excursion
  6464. (org-back-to-heading t)
  6465. (combine-change-calls (point) (save-excursion (org-end-of-subtree t))
  6466. (org-with-limited-levels (org-map-tree 'org-promote))))
  6467. (org-fix-position-after-promote))
  6468. (defun org-demote-subtree ()
  6469. "Demote the entire subtree.
  6470. See `org-demote' and `org-promote'."
  6471. (interactive)
  6472. (save-excursion
  6473. (org-back-to-heading t)
  6474. (combine-change-calls (point) (save-excursion (org-end-of-subtree t))
  6475. (org-with-limited-levels (org-map-tree 'org-demote))))
  6476. (org-fix-position-after-promote))
  6477. (defun org-do-promote ()
  6478. "Promote the current heading higher up the tree.
  6479. If the region is active in `transient-mark-mode', promote all
  6480. headings in the region."
  6481. (interactive)
  6482. (save-excursion
  6483. (if (org-region-active-p)
  6484. (org-map-region 'org-promote (region-beginning) (region-end))
  6485. (org-promote)))
  6486. (org-fix-position-after-promote))
  6487. (defun org-do-demote ()
  6488. "Demote the current heading lower down the tree.
  6489. If the region is active in `transient-mark-mode', demote all
  6490. headings in the region."
  6491. (interactive)
  6492. (save-excursion
  6493. (if (org-region-active-p)
  6494. (org-map-region 'org-demote (region-beginning) (region-end))
  6495. (org-demote)))
  6496. (org-fix-position-after-promote))
  6497. (defun org-fix-position-after-promote ()
  6498. "Fix cursor position and indentation after demoting/promoting."
  6499. (let ((pos (point)))
  6500. (when (save-excursion
  6501. (beginning-of-line)
  6502. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  6503. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  6504. (cond ((eobp) (insert " "))
  6505. ((eolp) (insert " "))
  6506. ((equal (char-after) ?\s) (forward-char 1))))))
  6507. (defun org-current-level ()
  6508. "Return the level of the current entry, or nil if before the first headline.
  6509. The level is the number of stars at the beginning of the
  6510. headline. Use `org-reduced-level' to remove the effect of
  6511. `org-odd-levels'. Unlike to `org-outline-level', this function
  6512. ignores inlinetasks."
  6513. (let ((level (org-with-limited-levels (org-outline-level))))
  6514. (and (> level 0) level)))
  6515. (defun org-get-previous-line-level ()
  6516. "Return the outline depth of the last headline before the current line.
  6517. Returns 0 for the first headline in the buffer, and nil if before the
  6518. first headline."
  6519. (and (org-current-level)
  6520. (or (and (/= (line-beginning-position) (point-min))
  6521. (save-excursion (beginning-of-line 0) (org-current-level)))
  6522. 0)))
  6523. (defun org-reduced-level (l)
  6524. "Compute the effective level of a heading.
  6525. This takes into account the setting of `org-odd-levels-only'."
  6526. (cond
  6527. ((zerop l) 0)
  6528. (org-odd-levels-only (1+ (floor (/ l 2))))
  6529. (t l)))
  6530. (defun org-level-increment ()
  6531. "Return the number of stars that will be added or removed at a
  6532. time to headlines when structure editing, based on the value of
  6533. `org-odd-levels-only'."
  6534. (if org-odd-levels-only 2 1))
  6535. (defun org-get-valid-level (level &optional change)
  6536. "Rectify a level change under the influence of `org-odd-levels-only'.
  6537. LEVEL is a current level, CHANGE is by how much the level should
  6538. be modified. Even if CHANGE is nil, LEVEL may be returned
  6539. modified because even level numbers will become the next higher
  6540. odd number. Returns values greater than 0."
  6541. (if org-odd-levels-only
  6542. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  6543. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  6544. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  6545. (max 1 (+ level (or change 0)))))
  6546. (defun org-promote ()
  6547. "Promote the current heading higher up the tree."
  6548. (org-with-wide-buffer
  6549. (org-back-to-heading t)
  6550. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6551. after-change-functions))
  6552. (level (save-match-data (funcall outline-level)))
  6553. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  6554. (diff (abs (- level (length up-head) -1))))
  6555. (cond
  6556. ((and (= level 1) org-allow-promoting-top-level-subtree)
  6557. (replace-match "# " nil t))
  6558. ((= level 1)
  6559. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  6560. (t (replace-match up-head nil t)))
  6561. (unless (= level 1)
  6562. (when org-auto-align-tags (org-align-tags))
  6563. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  6564. (run-hooks 'org-after-promote-entry-hook))))
  6565. (defun org-demote ()
  6566. "Demote the current heading lower down the tree."
  6567. (org-with-wide-buffer
  6568. (org-back-to-heading t)
  6569. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6570. after-change-functions))
  6571. (level (save-match-data (funcall outline-level)))
  6572. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  6573. (diff (abs (- level (length down-head) -1))))
  6574. (replace-match down-head nil t)
  6575. (when org-auto-align-tags (org-align-tags))
  6576. (when org-adapt-indentation (org-fixup-indentation diff))
  6577. (run-hooks 'org-after-demote-entry-hook))))
  6578. (defun org-cycle-level ()
  6579. "Cycle the level of an empty headline through possible states.
  6580. This goes first to child, then to parent, level, then up the hierarchy.
  6581. After top level, it switches back to sibling level."
  6582. (interactive)
  6583. (let ((org-adapt-indentation nil))
  6584. (when (org-point-at-end-of-empty-headline)
  6585. (setq this-command 'org-cycle-level) ; Only needed for caching
  6586. (let ((cur-level (org-current-level))
  6587. (prev-level (org-get-previous-line-level)))
  6588. (cond
  6589. ;; If first headline in file, promote to top-level.
  6590. ((= prev-level 0)
  6591. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6592. do (org-do-promote)))
  6593. ;; If same level as prev, demote one.
  6594. ((= prev-level cur-level)
  6595. (org-do-demote))
  6596. ;; If parent is top-level, promote to top level if not already.
  6597. ((= prev-level 1)
  6598. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6599. do (org-do-promote)))
  6600. ;; If top-level, return to prev-level.
  6601. ((= cur-level 1)
  6602. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  6603. do (org-do-demote)))
  6604. ;; If less than prev-level, promote one.
  6605. ((< cur-level prev-level)
  6606. (org-do-promote))
  6607. ;; If deeper than prev-level, promote until higher than
  6608. ;; prev-level.
  6609. ((> cur-level prev-level)
  6610. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  6611. do (org-do-promote))))
  6612. t))))
  6613. (defun org-map-tree (fun)
  6614. "Call FUN for every heading underneath the current one."
  6615. (org-back-to-heading t)
  6616. (let ((level (funcall outline-level)))
  6617. (save-excursion
  6618. (funcall fun)
  6619. (while (and (progn
  6620. (outline-next-heading)
  6621. (> (funcall outline-level) level))
  6622. (not (eobp)))
  6623. (funcall fun)))))
  6624. (defun org-map-region (fun beg end)
  6625. "Call FUN for every heading between BEG and END."
  6626. (let ((org-ignore-region t))
  6627. (save-excursion
  6628. (setq end (copy-marker end))
  6629. (goto-char beg)
  6630. (when (and (re-search-forward org-outline-regexp-bol nil t)
  6631. (< (point) end))
  6632. (funcall fun))
  6633. (while (and (progn
  6634. (outline-next-heading)
  6635. (< (point) end))
  6636. (not (eobp)))
  6637. (funcall fun)))))
  6638. (defun org-fixup-indentation (diff)
  6639. "Change the indentation in the current entry by DIFF.
  6640. DIFF is an integer. Indentation is done according to the
  6641. following rules:
  6642. - Planning information and property drawers are always indented
  6643. according to the new level of the headline;
  6644. - Footnote definitions and their contents are ignored;
  6645. - Inlinetasks' boundaries are not shifted;
  6646. - Empty lines are ignored;
  6647. - Other lines' indentation are shifted by DIFF columns, unless
  6648. it would introduce a structural change in the document, in
  6649. which case no shifting is done at all.
  6650. Assume point is at a heading or an inlinetask beginning."
  6651. (org-with-wide-buffer
  6652. (narrow-to-region (line-beginning-position)
  6653. (save-excursion
  6654. (if (org-with-limited-levels (org-at-heading-p))
  6655. (org-with-limited-levels (outline-next-heading))
  6656. (org-inlinetask-goto-end))
  6657. (point)))
  6658. (forward-line)
  6659. ;; Indent properly planning info and property drawer.
  6660. (when (looking-at-p org-planning-line-re)
  6661. (org-indent-line)
  6662. (forward-line))
  6663. (when (looking-at org-property-drawer-re)
  6664. (goto-char (match-end 0))
  6665. (forward-line)
  6666. (org-indent-region (match-beginning 0) (match-end 0)))
  6667. (when (looking-at org-logbook-drawer-re)
  6668. (let ((end-marker (move-marker (make-marker) (match-end 0)))
  6669. (col (+ (current-indentation) diff)))
  6670. (when (wholenump col)
  6671. (while (< (point) end-marker)
  6672. (if (natnump diff)
  6673. (insert (make-string diff 32))
  6674. (delete-char (abs diff)))
  6675. (forward-line)))))
  6676. (catch 'no-shift
  6677. (when (or (zerop diff) (not (eq org-adapt-indentation t)))
  6678. (throw 'no-shift nil))
  6679. ;; If DIFF is negative, first check if a shift is possible at all
  6680. ;; (e.g., it doesn't break structure). This can only happen if
  6681. ;; some contents are not properly indented.
  6682. (let ((case-fold-search t))
  6683. (when (< diff 0)
  6684. (let ((diff (- diff))
  6685. (forbidden-re (concat org-outline-regexp
  6686. "\\|"
  6687. (substring org-footnote-definition-re 1))))
  6688. (save-excursion
  6689. (while (not (eobp))
  6690. (cond
  6691. ((looking-at-p "[ \t]*$") (forward-line))
  6692. ((and (looking-at-p org-footnote-definition-re)
  6693. (let ((e (org-element-at-point)))
  6694. (and (eq (org-element-type e) 'footnote-definition)
  6695. (goto-char (org-element-property :end e))))))
  6696. ((looking-at-p org-outline-regexp) (forward-line))
  6697. ;; Give up if shifting would move before column 0 or
  6698. ;; if it would introduce a headline or a footnote
  6699. ;; definition.
  6700. (t
  6701. (skip-chars-forward " \t")
  6702. (let ((ind (current-column)))
  6703. (when (or (< ind diff)
  6704. (and (= ind diff) (looking-at-p forbidden-re)))
  6705. (throw 'no-shift nil)))
  6706. ;; Ignore contents of example blocks and source
  6707. ;; blocks if their indentation is meant to be
  6708. ;; preserved. Jump to block's closing line.
  6709. (beginning-of-line)
  6710. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6711. (let ((e (org-element-at-point)))
  6712. (and (memq (org-element-type e)
  6713. '(example-block src-block))
  6714. (or org-src-preserve-indentation
  6715. (org-element-property :preserve-indent e))
  6716. (goto-char (org-element-property :end e))
  6717. (progn (skip-chars-backward " \r\t\n")
  6718. (beginning-of-line)
  6719. t))))
  6720. (forward-line))))))))
  6721. ;; Shift lines but footnote definitions, inlinetasks boundaries
  6722. ;; by DIFF. Also skip contents of source or example blocks
  6723. ;; when indentation is meant to be preserved.
  6724. (while (not (eobp))
  6725. (cond
  6726. ((and (looking-at-p org-footnote-definition-re)
  6727. (let ((e (org-element-at-point)))
  6728. (and (eq (org-element-type e) 'footnote-definition)
  6729. (goto-char (org-element-property :end e))))))
  6730. ((looking-at-p org-outline-regexp) (forward-line))
  6731. ((looking-at-p "[ \t]*$") (forward-line))
  6732. (t
  6733. (indent-line-to (+ (current-indentation) diff))
  6734. (beginning-of-line)
  6735. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6736. (let ((e (org-element-at-point)))
  6737. (and (memq (org-element-type e)
  6738. '(example-block src-block))
  6739. (or org-src-preserve-indentation
  6740. (org-element-property :preserve-indent e))
  6741. (goto-char (org-element-property :end e))
  6742. (progn (skip-chars-backward " \r\t\n")
  6743. (beginning-of-line)
  6744. t))))
  6745. (forward-line)))))))))
  6746. (defun org-convert-to-odd-levels ()
  6747. "Convert an Org file with all levels allowed to one with odd levels.
  6748. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  6749. level 5 etc."
  6750. (interactive)
  6751. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  6752. (let ((outline-level 'org-outline-level)
  6753. (org-odd-levels-only nil) n)
  6754. (save-excursion
  6755. (goto-char (point-min))
  6756. (while (re-search-forward "^\\*\\*+ " nil t)
  6757. (setq n (- (length (match-string 0)) 2))
  6758. (while (>= (setq n (1- n)) 0)
  6759. (org-demote))
  6760. (end-of-line 1))))))
  6761. (defun org-convert-to-oddeven-levels ()
  6762. "Convert an Org file with only odd levels to one with odd/even levels.
  6763. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  6764. file contains a section with an even level, conversion would
  6765. destroy the structure of the file. An error is signaled in this
  6766. case."
  6767. (interactive)
  6768. (goto-char (point-min))
  6769. ;; First check if there are no even levels
  6770. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  6771. (org-show-set-visibility 'canonical)
  6772. (error "Not all levels are odd in this file. Conversion not possible"))
  6773. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  6774. (let ((outline-regexp org-outline-regexp)
  6775. (outline-level 'org-outline-level)
  6776. (org-odd-levels-only nil) n)
  6777. (save-excursion
  6778. (goto-char (point-min))
  6779. (while (re-search-forward "^\\*\\*+ " nil t)
  6780. (setq n (/ (1- (length (match-string 0))) 2))
  6781. (while (>= (setq n (1- n)) 0)
  6782. (org-promote))
  6783. (end-of-line 1))))))
  6784. (defun org-tr-level (n)
  6785. "Make N odd if required."
  6786. (if org-odd-levels-only (1+ (/ n 2)) n))
  6787. ;;; Vertical tree motion, cutting and pasting of subtrees
  6788. (defun org-move-subtree-up (&optional arg)
  6789. "Move the current subtree up past ARG headlines of the same level."
  6790. (interactive "p")
  6791. (org-move-subtree-down (- (prefix-numeric-value arg))))
  6792. (defun org-move-subtree-down (&optional arg)
  6793. "Move the current subtree down past ARG headlines of the same level."
  6794. (interactive "p")
  6795. (setq arg (prefix-numeric-value arg))
  6796. (org-preserve-local-variables
  6797. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  6798. 'org-get-previous-sibling))
  6799. (ins-point (make-marker))
  6800. (cnt (abs arg))
  6801. (col (current-column))
  6802. beg end txt folded)
  6803. ;; Select the tree
  6804. (org-back-to-heading)
  6805. (setq beg (point))
  6806. (save-match-data
  6807. (save-excursion (outline-end-of-heading)
  6808. (setq folded (org-invisible-p)))
  6809. (progn (org-end-of-subtree nil t)
  6810. (unless (eobp) (backward-char))))
  6811. (outline-next-heading)
  6812. (setq end (point))
  6813. (goto-char beg)
  6814. ;; Find insertion point, with error handling
  6815. (while (> cnt 0)
  6816. (unless (and (funcall movfunc) (looking-at org-outline-regexp))
  6817. (goto-char beg)
  6818. (user-error "Cannot move past superior level or buffer limit"))
  6819. (setq cnt (1- cnt)))
  6820. (when (> arg 0)
  6821. ;; Moving forward - still need to move over subtree
  6822. (org-end-of-subtree t t)
  6823. (save-excursion
  6824. (org-back-over-empty-lines)
  6825. (or (bolp) (newline))))
  6826. (move-marker ins-point (point))
  6827. (setq txt (buffer-substring beg end))
  6828. (org-save-markers-in-region beg end)
  6829. (delete-region beg end)
  6830. (org-remove-empty-overlays-at beg)
  6831. (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
  6832. (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
  6833. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  6834. (let ((bbb (point)))
  6835. (insert-before-markers txt)
  6836. (org-reinstall-markers-in-region bbb)
  6837. (move-marker ins-point bbb))
  6838. (or (bolp) (insert "\n"))
  6839. (goto-char ins-point)
  6840. (org-skip-whitespace)
  6841. (move-marker ins-point nil)
  6842. (if folded
  6843. (org-flag-subtree t)
  6844. (org-show-entry)
  6845. (org-show-children))
  6846. (org-clean-visibility-after-subtree-move)
  6847. ;; move back to the initial column we were at
  6848. (move-to-column col))))
  6849. (defvar org-subtree-clip ""
  6850. "Clipboard for cut and paste of subtrees.
  6851. This is actually only a copy of the kill, because we use the normal kill
  6852. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  6853. (defvar org-subtree-clip-folded nil
  6854. "Was the last copied subtree folded?
  6855. This is used to fold the tree back after pasting.")
  6856. (defun org-cut-subtree (&optional n)
  6857. "Cut the current subtree into the clipboard.
  6858. With prefix arg N, cut this many sequential subtrees.
  6859. This is a short-hand for marking the subtree and then cutting it."
  6860. (interactive "p")
  6861. (org-copy-subtree n 'cut))
  6862. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  6863. "Copy the current subtree into the clipboard.
  6864. With prefix arg N, copy this many sequential subtrees.
  6865. This is a short-hand for marking the subtree and then copying it.
  6866. If CUT is non-nil, actually cut the subtree.
  6867. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  6868. of some markers in the region, even if CUT is non-nil. This is
  6869. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  6870. (interactive "p")
  6871. (org-preserve-local-variables
  6872. (let (beg end folded (beg0 (point)))
  6873. (if (called-interactively-p 'any)
  6874. (org-back-to-heading nil) ; take what looks like a subtree
  6875. (org-back-to-heading t)) ; take what is really there
  6876. (setq beg (point))
  6877. (skip-chars-forward " \t\r\n")
  6878. (save-match-data
  6879. (if nosubtrees
  6880. (outline-next-heading)
  6881. (save-excursion (outline-end-of-heading)
  6882. (setq folded (org-invisible-p)))
  6883. (ignore-errors (org-forward-heading-same-level (1- n) t))
  6884. (org-end-of-subtree t t)))
  6885. ;; Include the end of an inlinetask
  6886. (when (and (featurep 'org-inlinetask)
  6887. (looking-at-p (concat (org-inlinetask-outline-regexp)
  6888. "END[ \t]*$")))
  6889. (end-of-line))
  6890. (setq end (point))
  6891. (goto-char beg0)
  6892. (when (> end beg)
  6893. (setq org-subtree-clip-folded folded)
  6894. (when (or cut force-store-markers)
  6895. (org-save-markers-in-region beg end))
  6896. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  6897. (setq org-subtree-clip (current-kill 0))
  6898. (message "%s: Subtree(s) with %d characters"
  6899. (if cut "Cut" "Copied")
  6900. (length org-subtree-clip))))))
  6901. (defun org-paste-subtree (&optional level tree for-yank remove)
  6902. "Paste the clipboard as a subtree, with modification of headline level.
  6903. The entire subtree is promoted or demoted in order to match a new headline
  6904. level.
  6905. If the cursor is at the beginning of a headline, the same level as
  6906. that headline is used to paste the tree.
  6907. If not, the new level is derived from the *visible* headings
  6908. before and after the insertion point, and taken to be the inferior headline
  6909. level of the two. So if the previous visible heading is level 3 and the
  6910. next is level 4 (or vice versa), level 4 will be used for insertion.
  6911. This makes sure that the subtree remains an independent subtree and does
  6912. not swallow low level entries.
  6913. You can also force a different level, either by using a numeric prefix
  6914. argument, or by inserting the heading marker by hand. For example, if the
  6915. cursor is after \"*****\", then the tree will be shifted to level 5.
  6916. If optional TREE is given, use this text instead of the kill ring.
  6917. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  6918. move back over whitespace before inserting, and move point to the end of
  6919. the inserted text when done.
  6920. When REMOVE is non-nil, remove the subtree from the clipboard."
  6921. (interactive "P")
  6922. (setq tree (or tree (and kill-ring (current-kill 0))))
  6923. (unless (org-kill-is-subtree-p tree)
  6924. (user-error
  6925. (substitute-command-keys
  6926. "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
  6927. (org-with-limited-levels
  6928. (let* ((visp (not (org-invisible-p)))
  6929. (txt tree)
  6930. (old-level (if (string-match org-outline-regexp-bol txt)
  6931. (- (match-end 0) (match-beginning 0) 1)
  6932. -1))
  6933. (force-level
  6934. (cond
  6935. (level (prefix-numeric-value level))
  6936. ;; When point is after the stars in an otherwise empty
  6937. ;; headline, use the number of stars as the forced level.
  6938. ((and (org-match-line "^\\*+[ \t]*$")
  6939. (not (eq ?* (char-after))))
  6940. (org-outline-level))
  6941. ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
  6942. (previous-level
  6943. (save-excursion
  6944. (org-previous-visible-heading 1)
  6945. (if (org-at-heading-p) (org-outline-level) 1)))
  6946. (next-level
  6947. (save-excursion
  6948. (if (org-at-heading-p) (org-outline-level)
  6949. (org-next-visible-heading 1)
  6950. (if (org-at-heading-p) (org-outline-level) 1))))
  6951. (new-level (or force-level (max previous-level next-level)))
  6952. (shift (if (or (= old-level -1)
  6953. (= new-level -1)
  6954. (= old-level new-level))
  6955. 0
  6956. (- new-level old-level)))
  6957. (delta (if (> shift 0) -1 1))
  6958. (func (if (> shift 0) #'org-demote #'org-promote))
  6959. (org-odd-levels-only nil)
  6960. beg end newend)
  6961. ;; Remove the forced level indicator.
  6962. (when (and force-level (not level))
  6963. (delete-region (line-beginning-position) (point)))
  6964. ;; Paste before the next visible heading or at end of buffer,
  6965. ;; unless point is at the beginning of a headline.
  6966. (unless (and (bolp) (org-at-heading-p))
  6967. (org-next-visible-heading 1)
  6968. (unless (bolp) (insert "\n")))
  6969. (setq beg (point))
  6970. ;; Avoid re-parsing cache elements when i.e. level 1 heading
  6971. ;; is inserted and then promoted.
  6972. (combine-change-calls beg beg
  6973. (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  6974. (insert-before-markers txt)
  6975. (unless (string-suffix-p "\n" txt) (insert "\n"))
  6976. (setq newend (point))
  6977. (org-reinstall-markers-in-region beg)
  6978. (setq end (point))
  6979. (goto-char beg)
  6980. (skip-chars-forward " \t\n\r")
  6981. (setq beg (point))
  6982. (when (and (org-invisible-p) visp)
  6983. (save-excursion (outline-show-heading)))
  6984. ;; Shift if necessary.
  6985. (unless (= shift 0)
  6986. (save-restriction
  6987. (narrow-to-region beg end)
  6988. (while (not (= shift 0))
  6989. (org-map-region func (point-min) (point-max))
  6990. (setq shift (+ delta shift)))
  6991. (goto-char (point-min))
  6992. (setq newend (point-max)))))
  6993. (when (or for-yank (called-interactively-p 'interactive))
  6994. (message "Clipboard pasted as level %d subtree" new-level))
  6995. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  6996. kill-ring
  6997. (equal org-subtree-clip (current-kill 0))
  6998. org-subtree-clip-folded)
  6999. ;; The tree was folded before it was killed/copied
  7000. (org-flag-subtree t))
  7001. (when for-yank (goto-char newend))
  7002. (when remove (pop kill-ring)))))
  7003. (defun org-kill-is-subtree-p (&optional txt)
  7004. "Check if the current kill is an outline subtree, or a set of trees.
  7005. Returns nil if kill does not start with a headline, or if the first
  7006. headline level is not the largest headline level in the tree.
  7007. So this will actually accept several entries of equal levels as well,
  7008. which is OK for `org-paste-subtree'.
  7009. If optional TXT is given, check this string instead of the current kill."
  7010. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  7011. (re (org-get-limited-outline-regexp))
  7012. (^re (concat "^" re))
  7013. (start-level (and kill
  7014. (string-match
  7015. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  7016. kill)
  7017. (- (match-end 2) (match-beginning 2) 1)))
  7018. (start (1+ (or (match-beginning 2) -1))))
  7019. (if (not start-level)
  7020. (progn
  7021. nil) ;; does not even start with a heading
  7022. (catch 'exit
  7023. (while (setq start (string-match ^re kill (1+ start)))
  7024. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  7025. (throw 'exit nil)))
  7026. t))))
  7027. (defvar org-markers-to-move nil
  7028. "Markers that should be moved with a cut-and-paste operation.
  7029. Those markers are stored together with their positions relative to
  7030. the start of the region.")
  7031. (defun org-save-markers-in-region (beg end)
  7032. "Check markers in region.
  7033. If these markers are between BEG and END, record their position relative
  7034. to BEG, so that after moving the block of text, we can put the markers back
  7035. into place.
  7036. This function gets called just before an entry or tree gets cut from the
  7037. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  7038. called immediately, to move the markers with the entries."
  7039. (setq org-markers-to-move nil)
  7040. (when (featurep 'org-clock)
  7041. (org-clock-save-markers-for-cut-and-paste beg end))
  7042. (when (featurep 'org-agenda)
  7043. (org-agenda-save-markers-for-cut-and-paste beg end)))
  7044. (defun org-check-and-save-marker (marker beg end)
  7045. "Check if MARKER is between BEG and END.
  7046. If yes, remember the marker and the distance to BEG."
  7047. (when (and (marker-buffer marker)
  7048. (or (equal (marker-buffer marker) (current-buffer))
  7049. (equal (marker-buffer marker) (buffer-base-buffer (current-buffer))))
  7050. (>= marker beg) (< marker end))
  7051. (push (cons marker (- marker beg)) org-markers-to-move)))
  7052. (defun org-reinstall-markers-in-region (beg)
  7053. "Move all remembered markers to their position relative to BEG."
  7054. (dolist (x org-markers-to-move)
  7055. (move-marker (car x) (+ beg (cdr x))))
  7056. (setq org-markers-to-move nil))
  7057. (defun org-narrow-to-subtree (&optional element)
  7058. "Narrow buffer to the current subtree."
  7059. (interactive)
  7060. (if (org-element--cache-active-p)
  7061. (if-let* ((heading (org-element-lineage
  7062. (or element (org-element-at-point))
  7063. '(headline) t))
  7064. (end (org-element-property :end heading)))
  7065. (narrow-to-region (org-element-property :begin heading)
  7066. (if (= end (point-max))
  7067. end (1- end)))
  7068. (signal 'outline-before-first-heading nil))
  7069. (save-excursion
  7070. (save-match-data
  7071. (org-with-limited-levels
  7072. (narrow-to-region
  7073. (progn (org-back-to-heading t) (point))
  7074. (progn (org-end-of-subtree t t)
  7075. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  7076. (point))))))))
  7077. (defun org-toggle-narrow-to-subtree ()
  7078. "Narrow to the subtree at point or widen a narrowed buffer."
  7079. (interactive)
  7080. (if (buffer-narrowed-p)
  7081. (progn (widen) (message "Buffer widen"))
  7082. (org-narrow-to-subtree)
  7083. (message "Buffer narrowed to current subtree")))
  7084. (defun org-narrow-to-block ()
  7085. "Narrow buffer to the current block."
  7086. (interactive)
  7087. (let* ((case-fold-search t)
  7088. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7089. "^[ \t]*#\\+end_.*")))
  7090. (if blockp
  7091. (narrow-to-region (car blockp) (cdr blockp))
  7092. (user-error "Not in a block"))))
  7093. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7094. "Clone the task (subtree) at point N times.
  7095. The clones will be inserted as siblings.
  7096. In interactive use, the user will be prompted for the number of
  7097. clones to be produced. If the entry has a timestamp, the user
  7098. will also be prompted for a time shift, which may be a repeater
  7099. as used in time stamps, for example `+3d'. To disable this,
  7100. you can call the function with a universal prefix argument.
  7101. When a valid repeater is given and the entry contains any time
  7102. stamps, the clones will become a sequence in time, with time
  7103. stamps in the subtree shifted for each clone produced. If SHIFT
  7104. is nil or the empty string, time stamps will be left alone. The
  7105. ID property of the original subtree is removed.
  7106. In each clone, all the CLOCK entries will be removed. This
  7107. prevents Org from considering that the clocked times overlap.
  7108. If the original subtree did contain time stamps with a repeater,
  7109. the following will happen:
  7110. - the repeater will be removed in each clone
  7111. - an additional clone will be produced, with the current, unshifted
  7112. date(s) in the entry.
  7113. - the original entry will be placed *after* all the clones, with
  7114. repeater intact.
  7115. - the start days in the repeater in the original entry will be shifted
  7116. to past the last clone.
  7117. In this way you can spell out a number of instances of a repeating task,
  7118. and still retain the repeater to cover future instances of the task.
  7119. As described above, N+1 clones are produced when the original
  7120. subtree has a repeater. Setting N to 0, then, can be used to
  7121. remove the repeater from a subtree and create a shifted clone
  7122. with the original repeater."
  7123. (interactive "nNumber of clones to produce: ")
  7124. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  7125. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  7126. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  7127. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  7128. (shift
  7129. (or shift
  7130. (if (and (not (equal current-prefix-arg '(4)))
  7131. (save-excursion
  7132. (goto-char beg)
  7133. (re-search-forward org-ts-regexp-both end-of-tree t)))
  7134. (read-from-minibuffer
  7135. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7136. ""))) ;No time shift
  7137. (doshift
  7138. (and (org-string-nw-p shift)
  7139. (or (string-match "\\`[ \t]*\\([+-]?[0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
  7140. shift)
  7141. (user-error "Invalid shift specification %s" shift)))))
  7142. (goto-char end-of-tree)
  7143. (unless (bolp) (insert "\n"))
  7144. (let* ((end (point))
  7145. (template (buffer-substring beg end))
  7146. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  7147. (shift-what (pcase (and doshift (match-string 2 shift))
  7148. (`nil nil)
  7149. ("h" 'hour)
  7150. ("d" 'day)
  7151. ("w" (setq shift-n (* 7 shift-n)) 'day)
  7152. ("m" 'month)
  7153. ("y" 'year)
  7154. (_ (error "Unsupported time unit"))))
  7155. (nmin 1)
  7156. (nmax n)
  7157. (n-no-remove -1)
  7158. (org-id-overriding-file-name (buffer-file-name (buffer-base-buffer)))
  7159. (idprop (org-entry-get beg "ID")))
  7160. (when (and doshift
  7161. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  7162. template))
  7163. (delete-region beg end)
  7164. (setq end beg)
  7165. (setq nmin 0)
  7166. (setq nmax (1+ nmax))
  7167. (setq n-no-remove nmax))
  7168. (goto-char end)
  7169. (cl-loop for n from nmin to nmax do
  7170. (insert
  7171. ;; Prepare clone.
  7172. (with-temp-buffer
  7173. (insert template)
  7174. (org-mode)
  7175. (goto-char (point-min))
  7176. (org-show-subtree)
  7177. (and idprop (if org-clone-delete-id
  7178. (org-entry-delete nil "ID")
  7179. (org-id-get-create t)))
  7180. (unless (= n 0)
  7181. (while (re-search-forward org-clock-line-re nil t)
  7182. (delete-region (line-beginning-position)
  7183. (line-beginning-position 2)))
  7184. (goto-char (point-min))
  7185. (while (re-search-forward org-drawer-regexp nil t)
  7186. (org-remove-empty-drawer-at (point))))
  7187. (goto-char (point-min))
  7188. (when doshift
  7189. (while (re-search-forward org-ts-regexp-both nil t)
  7190. (org-timestamp-change (* n shift-n) shift-what))
  7191. (unless (= n n-no-remove)
  7192. (goto-char (point-min))
  7193. (while (re-search-forward org-ts-regexp nil t)
  7194. (save-excursion
  7195. (goto-char (match-beginning 0))
  7196. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7197. (delete-region (match-beginning 1) (match-end 1)))))))
  7198. (buffer-string)))))
  7199. (goto-char beg)))
  7200. ;;; Outline path
  7201. (defvar org-outline-path-cache nil
  7202. "Alist between buffer positions and outline paths.
  7203. It value is an alist (POSITION . PATH) where POSITION is the
  7204. buffer position at the beginning of an entry and PATH is a list
  7205. of strings describing the outline path for that entry, in reverse
  7206. order.")
  7207. (defun org--get-outline-path-1 (&optional use-cache)
  7208. "Return outline path to current headline.
  7209. Outline path is a list of strings, in reverse order. When
  7210. optional argument USE-CACHE is non-nil, make use of a cache. See
  7211. `org-get-outline-path' for details.
  7212. Assume buffer is widened and point is on a headline."
  7213. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  7214. (let ((p (point))
  7215. (heading (let ((case-fold-search nil))
  7216. (looking-at org-complex-heading-regexp)
  7217. (if (not (match-end 4)) ""
  7218. ;; Remove statistics cookies.
  7219. (org-trim
  7220. (org-link-display-format
  7221. (replace-regexp-in-string
  7222. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  7223. (match-string-no-properties 4))))))))
  7224. (if (org-up-heading-safe)
  7225. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  7226. (when use-cache
  7227. (push (cons p path) org-outline-path-cache))
  7228. path)
  7229. ;; This is a new root node. Since we assume we are moving
  7230. ;; forward, we can drop previous cache so as to limit number
  7231. ;; of associations there.
  7232. (let ((path (list heading)))
  7233. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  7234. path)))))
  7235. (defun org-get-outline-path (&optional with-self use-cache)
  7236. "Return the outline path to the current entry.
  7237. An outline path is a list of ancestors for current headline, as
  7238. a list of strings. Statistics cookies are removed and links are
  7239. replaced with their description, if any, or their path otherwise.
  7240. When optional argument WITH-SELF is non-nil, the path also
  7241. includes the current headline.
  7242. When optional argument USE-CACHE is non-nil, cache outline paths
  7243. between calls to this function so as to avoid backtracking. This
  7244. argument is useful when planning to find more than one outline
  7245. path in the same document. In that case, there are two
  7246. conditions to satisfy:
  7247. - `org-outline-path-cache' is set to nil before starting the
  7248. process;
  7249. - outline paths are computed by increasing buffer positions."
  7250. (org-with-wide-buffer
  7251. (and (or (and with-self (org-back-to-heading t))
  7252. (org-up-heading-safe))
  7253. (reverse (org--get-outline-path-1 use-cache)))))
  7254. (defun org-format-outline-path (path &optional width prefix separator)
  7255. "Format the outline path PATH for display.
  7256. WIDTH is the maximum number of characters that is available.
  7257. PREFIX is a prefix to be included in the returned string,
  7258. such as the file name.
  7259. SEPARATOR is inserted between the different parts of the path,
  7260. the default is \"/\"."
  7261. (setq width (or width 79))
  7262. (setq path (delq nil path))
  7263. (unless (> width 0)
  7264. (user-error "Argument `width' must be positive"))
  7265. (setq separator (or separator "/"))
  7266. (let* ((org-odd-levels-only nil)
  7267. (fpath (concat
  7268. prefix (and prefix path separator)
  7269. (mapconcat
  7270. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  7271. (cl-loop for head in path
  7272. for n from 0
  7273. collect (org-add-props
  7274. head nil 'face
  7275. (nth (% n org-n-level-faces) org-level-faces)))
  7276. separator))))
  7277. (when (> (length fpath) width)
  7278. (if (< width 7)
  7279. ;; It's unlikely that `width' will be this small, but don't
  7280. ;; waste characters by adding ".." if it is.
  7281. (setq fpath (substring fpath 0 width))
  7282. (setf (substring fpath (- width 2)) "..")))
  7283. fpath))
  7284. (defun org-display-outline-path (&optional file current separator just-return-string)
  7285. "Display the current outline path in the echo area.
  7286. If FILE is non-nil, prepend the output with the file name.
  7287. If CURRENT is non-nil, append the current heading to the output.
  7288. SEPARATOR is passed through to `org-format-outline-path'. It separates
  7289. the different parts of the path and defaults to \"/\".
  7290. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  7291. (interactive "P")
  7292. (let* (case-fold-search
  7293. (bfn (buffer-file-name (buffer-base-buffer)))
  7294. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  7295. res)
  7296. (when current (setq path (append path
  7297. (save-excursion
  7298. (org-back-to-heading t)
  7299. (when (looking-at org-complex-heading-regexp)
  7300. (list (match-string 4)))))))
  7301. (setq res
  7302. (org-format-outline-path
  7303. path
  7304. (1- (frame-width))
  7305. (and file bfn (concat (file-name-nondirectory bfn) separator))
  7306. separator))
  7307. (add-face-text-property 0 (length res)
  7308. `(:height ,(face-attribute 'default :height))
  7309. nil res)
  7310. (if just-return-string
  7311. res
  7312. (org-unlogged-message "%s" res))))
  7313. ;;; Outline Sorting
  7314. (defun org-sort (&optional with-case)
  7315. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7316. Optional argument WITH-CASE means sort case-sensitively."
  7317. (interactive "P")
  7318. (org-call-with-arg
  7319. (cond ((org-at-table-p) #'org-table-sort-lines)
  7320. ((org-at-item-p) #'org-sort-list)
  7321. (t #'org-sort-entries))
  7322. with-case))
  7323. (defun org-sort-remove-invisible (s)
  7324. "Remove emphasis markers and any invisible property from string S.
  7325. Assume S may contain only objects."
  7326. ;; org-element-interpret-data clears any text property, including
  7327. ;; invisible part.
  7328. (org-element-interpret-data
  7329. (let ((tree (org-element-parse-secondary-string
  7330. s (org-element-restriction 'paragraph))))
  7331. (org-element-map tree '(bold code italic link strike-through underline verbatim)
  7332. (lambda (o)
  7333. (pcase (org-element-type o)
  7334. ;; Terminal object. Replace it with its value.
  7335. ((or `code `verbatim)
  7336. (let ((new (org-element-property :value o)))
  7337. (org-element-insert-before new o)
  7338. (org-element-put-property
  7339. new :post-blank (org-element-property :post-blank o))))
  7340. ;; Non-terminal objects. Splice contents.
  7341. (type
  7342. (let ((contents
  7343. (or (org-element-contents o)
  7344. (and (eq type 'link)
  7345. (list (org-element-property :raw-link o)))))
  7346. (c nil))
  7347. (while contents
  7348. (setq c (pop contents))
  7349. (org-element-insert-before c o))
  7350. (org-element-put-property
  7351. c :post-blank (org-element-property :post-blank o)))))
  7352. (org-element-extract-element o)))
  7353. ;; Return modified tree.
  7354. tree)))
  7355. (defvar org-after-sorting-entries-or-items-hook nil
  7356. "Hook that is run after a bunch of entries or items have been sorted.
  7357. When children are sorted, the cursor is in the parent line when this
  7358. hook gets called. When a region or a plain list is sorted, the cursor
  7359. will be in the first entry of the sorted region/list.")
  7360. (defun org-sort-entries
  7361. (&optional with-case sorting-type getkey-func compare-func property
  7362. interactive?)
  7363. "Sort entries on a certain level of an outline tree.
  7364. If there is an active region, the entries in the region are sorted.
  7365. Else, if the cursor is before the first entry, sort the top-level items.
  7366. Else, the children of the entry at point are sorted.
  7367. Sorting can be alphabetically, numerically, by date/time as given by
  7368. a time stamp, by a property, by priority order, or by a custom function.
  7369. The command prompts for the sorting type unless it has been given to the
  7370. function through the SORTING-TYPE argument, which needs to be a character,
  7371. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7372. the precise meaning of each character:
  7373. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7374. c By creation time, which is assumed to be the first inactive time stamp
  7375. at the beginning of a line.
  7376. d By deadline date/time.
  7377. k By clocking time.
  7378. n Numerically, by converting the beginning of the entry/item to a number.
  7379. o By order of TODO keywords.
  7380. p By priority according to the cookie.
  7381. r By the value of a property.
  7382. s By scheduled date/time.
  7383. t By date/time, either the first active time stamp in the entry, or, if
  7384. none exist, by the first inactive one.
  7385. Capital letters will reverse the sort order.
  7386. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7387. called with point at the beginning of the record. It must return a
  7388. value that is compatible with COMPARE-FUNC, the function used to
  7389. compare entries.
  7390. Comparing entries ignores case by default. However, with an optional argument
  7391. WITH-CASE, the sorting considers case as well.
  7392. Sorting is done against the visible part of the headlines, it ignores hidden
  7393. links.
  7394. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  7395. A non-nil value for INTERACTIVE? is used to signal that this
  7396. function is being called interactively."
  7397. (interactive (list current-prefix-arg nil nil nil nil t))
  7398. (let ((case-func (if with-case 'identity 'downcase))
  7399. start beg end stars re re2
  7400. txt what tmp)
  7401. ;; Find beginning and end of region to sort
  7402. (cond
  7403. ((org-region-active-p)
  7404. ;; we will sort the region
  7405. (setq end (region-end)
  7406. what "region")
  7407. (goto-char (region-beginning))
  7408. (unless (org-at-heading-p) (outline-next-heading))
  7409. (setq start (point)))
  7410. ((or (org-at-heading-p)
  7411. (ignore-errors (progn (org-back-to-heading) t)))
  7412. ;; we will sort the children of the current headline
  7413. (org-back-to-heading)
  7414. (setq start (point)
  7415. end (progn (org-end-of-subtree t t)
  7416. (or (bolp) (insert "\n"))
  7417. (when (>= (org-back-over-empty-lines) 1)
  7418. (forward-line 1))
  7419. (point))
  7420. what "children")
  7421. (goto-char start)
  7422. (outline-show-subtree)
  7423. (outline-next-heading))
  7424. (t
  7425. ;; we will sort the top-level entries in this file
  7426. (goto-char (point-min))
  7427. (or (org-at-heading-p) (outline-next-heading))
  7428. (setq start (point))
  7429. (goto-char (point-max))
  7430. (beginning-of-line 1)
  7431. (when (looking-at ".*?\\S-")
  7432. ;; File ends in a non-white line
  7433. (end-of-line 1)
  7434. (insert "\n"))
  7435. (setq end (point-max))
  7436. (setq what "top-level")
  7437. (goto-char start)
  7438. (org-show-all '(headings drawers blocks))))
  7439. (setq beg (point))
  7440. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7441. (looking-at "\\(\\*+\\)")
  7442. (setq stars (match-string 1)
  7443. re (concat "^" (regexp-quote stars) " +")
  7444. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7445. txt (buffer-substring beg end))
  7446. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7447. (when (and (not (equal stars "*")) (string-match re2 txt))
  7448. (user-error "Region to sort contains a level above the first entry"))
  7449. (unless sorting-type
  7450. (message
  7451. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7452. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7453. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7454. what)
  7455. (setq sorting-type (read-char-exclusive)))
  7456. (unless getkey-func
  7457. (and (= (downcase sorting-type) ?f)
  7458. (setq getkey-func
  7459. (or (and interactive?
  7460. (org-read-function
  7461. "Function for extracting keys: "))
  7462. (error "Missing key extractor")))))
  7463. (and (= (downcase sorting-type) ?r)
  7464. (not property)
  7465. (setq property
  7466. (completing-read "Property: "
  7467. (mapcar #'list (org-buffer-property-keys t))
  7468. nil t)))
  7469. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  7470. (message "Sorting entries...")
  7471. (save-restriction
  7472. (narrow-to-region start end)
  7473. (let ((restore-clock?
  7474. ;; The clock marker is lost when using `sort-subr'; mark
  7475. ;; the clock with temporary `:org-clock-marker-backup'
  7476. ;; text property.
  7477. (when (and (eq (org-clocking-buffer) (current-buffer))
  7478. (<= start (marker-position org-clock-marker))
  7479. (>= end (marker-position org-clock-marker)))
  7480. (with-silent-modifications
  7481. (put-text-property (1- org-clock-marker) org-clock-marker
  7482. :org-clock-marker-backup t))
  7483. t))
  7484. (dcst (downcase sorting-type))
  7485. (case-fold-search nil)
  7486. (now (current-time)))
  7487. (org-preserve-local-variables
  7488. (sort-subr
  7489. (/= dcst sorting-type)
  7490. ;; This function moves to the beginning character of the
  7491. ;; "record" to be sorted.
  7492. (lambda nil
  7493. (if (re-search-forward re nil t)
  7494. (goto-char (match-beginning 0))
  7495. (goto-char (point-max))))
  7496. ;; This function moves to the last character of the "record" being
  7497. ;; sorted.
  7498. (lambda nil
  7499. (save-match-data
  7500. (condition-case nil
  7501. (outline-forward-same-level 1)
  7502. (error
  7503. (goto-char (point-max))))))
  7504. ;; This function returns the value that gets sorted against.
  7505. (lambda ()
  7506. (cond
  7507. ((= dcst ?n)
  7508. (string-to-number
  7509. (org-sort-remove-invisible (org-get-heading t t t t))))
  7510. ((= dcst ?a)
  7511. (funcall case-func
  7512. (org-sort-remove-invisible (org-get-heading t t t t))))
  7513. ((= dcst ?k)
  7514. (or (get-text-property (point) :org-clock-minutes) 0))
  7515. ((= dcst ?t)
  7516. (let ((end (save-excursion (outline-next-heading) (point))))
  7517. (if (or (re-search-forward org-ts-regexp end t)
  7518. (re-search-forward org-ts-regexp-both end t))
  7519. (org-time-string-to-seconds (match-string 0))
  7520. (float-time now))))
  7521. ((= dcst ?c)
  7522. (let ((end (save-excursion (outline-next-heading) (point))))
  7523. (if (re-search-forward
  7524. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  7525. end t)
  7526. (org-time-string-to-seconds (match-string 0))
  7527. (float-time now))))
  7528. ((= dcst ?s)
  7529. (let ((end (save-excursion (outline-next-heading) (point))))
  7530. (if (re-search-forward org-scheduled-time-regexp end t)
  7531. (org-time-string-to-seconds (match-string 1))
  7532. (float-time now))))
  7533. ((= dcst ?d)
  7534. (let ((end (save-excursion (outline-next-heading) (point))))
  7535. (if (re-search-forward org-deadline-time-regexp end t)
  7536. (org-time-string-to-seconds (match-string 1))
  7537. (float-time now))))
  7538. ((= dcst ?p)
  7539. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  7540. (string-to-char (match-string 2))
  7541. org-priority-default))
  7542. ((= dcst ?r)
  7543. (or (org-entry-get nil property) ""))
  7544. ((= dcst ?o)
  7545. (when (looking-at org-complex-heading-regexp)
  7546. (let* ((m (match-string 2))
  7547. (s (if (member m org-done-keywords) '- '+)))
  7548. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  7549. ((= dcst ?f)
  7550. (if getkey-func
  7551. (progn
  7552. (setq tmp (funcall getkey-func))
  7553. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  7554. tmp)
  7555. (error "Invalid key function `%s'" getkey-func)))
  7556. (t (error "Invalid sorting type `%c'" sorting-type))))
  7557. nil
  7558. (cond
  7559. ((= dcst ?a) 'string-collate-lessp)
  7560. ((= dcst ?f)
  7561. (or compare-func
  7562. (and interactive?
  7563. (org-read-function
  7564. (concat "Function for comparing keys "
  7565. "(empty for default `sort-subr' predicate): ")
  7566. 'allow-empty))))
  7567. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
  7568. (org-cycle-hide-drawers 'all)
  7569. (when restore-clock?
  7570. (move-marker org-clock-marker
  7571. (1+ (next-single-property-change
  7572. start :org-clock-marker-backup)))
  7573. (remove-text-properties (1- org-clock-marker) org-clock-marker
  7574. '(:org-clock-marker-backup t)))))
  7575. (run-hooks 'org-after-sorting-entries-or-items-hook)
  7576. (message "Sorting entries...done")))
  7577. (defun org-contextualize-keys (alist contexts)
  7578. "Return valid elements in ALIST depending on CONTEXTS.
  7579. `org-agenda-custom-commands' or `org-capture-templates' are the
  7580. values used for ALIST, and `org-agenda-custom-commands-contexts'
  7581. or `org-capture-templates-contexts' are the associated contexts
  7582. definitions."
  7583. (let ((contexts
  7584. ;; normalize contexts
  7585. (mapcar
  7586. (lambda(c) (cond ((listp (cadr c))
  7587. (list (car c) (car c) (nth 1 c)))
  7588. ((string= "" (cadr c))
  7589. (list (car c) (car c) (nth 2 c)))
  7590. (t c)))
  7591. contexts))
  7592. (a alist) r s)
  7593. ;; loop over all commands or templates
  7594. (dolist (c a)
  7595. (let (vrules repl)
  7596. (cond
  7597. ((not (assoc (car c) contexts))
  7598. (push c r))
  7599. ((and (assoc (car c) contexts)
  7600. (setq vrules (org-contextualize-validate-key
  7601. (car c) contexts)))
  7602. (mapc (lambda (vr)
  7603. (unless (equal (car vr) (cadr vr))
  7604. (setq repl vr)))
  7605. vrules)
  7606. (if (not repl) (push c r)
  7607. (push (cadr repl) s)
  7608. (push
  7609. (cons (car c)
  7610. (cdr (or (assoc (cadr repl) alist)
  7611. (error "Undefined key `%s' as contextual replacement for `%s'"
  7612. (cadr repl) (car c)))))
  7613. r))))))
  7614. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  7615. (delq
  7616. nil
  7617. (delete-dups
  7618. (mapcar (lambda (x)
  7619. (let ((tpl (car x)))
  7620. (unless (delq
  7621. nil
  7622. (mapcar (lambda (y)
  7623. (equal y tpl))
  7624. s))
  7625. x)))
  7626. (reverse r))))))
  7627. (defun org-contextualize-validate-key (key contexts)
  7628. "Check CONTEXTS for agenda or capture KEY."
  7629. (let (res)
  7630. (dolist (r contexts)
  7631. (dolist (rr (car (last r)))
  7632. (when
  7633. (and (equal key (car r))
  7634. (if (functionp rr) (funcall rr)
  7635. (or (and (eq (car rr) 'in-file)
  7636. (buffer-file-name)
  7637. (string-match (cdr rr) (buffer-file-name)))
  7638. (and (eq (car rr) 'in-mode)
  7639. (string-match (cdr rr) (symbol-name major-mode)))
  7640. (and (eq (car rr) 'in-buffer)
  7641. (string-match (cdr rr) (buffer-name)))
  7642. (when (and (eq (car rr) 'not-in-file)
  7643. (buffer-file-name))
  7644. (not (string-match (cdr rr) (buffer-file-name))))
  7645. (when (eq (car rr) 'not-in-mode)
  7646. (not (string-match (cdr rr) (symbol-name major-mode))))
  7647. (when (eq (car rr) 'not-in-buffer)
  7648. (not (string-match (cdr rr) (buffer-name)))))))
  7649. (push r res))))
  7650. (delete-dups (delq nil res))))
  7651. ;; Defined to provide a value for defcustom, since there is no
  7652. ;; string-collate-greaterp in Emacs.
  7653. (defun org-string-collate-greaterp (s1 s2)
  7654. "Return non-nil if S1 is greater than S2 in collation order."
  7655. (not (string-collate-lessp s1 s2)))
  7656. ;;;###autoload
  7657. (defun org-run-like-in-org-mode (cmd)
  7658. "Run a command, pretending that the current buffer is in Org mode.
  7659. This will temporarily bind local variables that are typically bound in
  7660. Org mode to the values they have in Org mode, and then interactively
  7661. call CMD."
  7662. (org-load-modules-maybe)
  7663. (let (binds)
  7664. (dolist (var (org-get-local-variables))
  7665. (when (or (not (boundp (car var)))
  7666. (eq (symbol-value (car var))
  7667. (default-value (car var))))
  7668. (push (list (car var) `(quote ,(cadr var))) binds)))
  7669. (eval `(let ,binds
  7670. (call-interactively (quote ,cmd))))))
  7671. (defun org-get-category (&optional pos force-refresh)
  7672. "Get the category applying to position POS."
  7673. (save-match-data
  7674. (when force-refresh (org-refresh-category-properties))
  7675. (let ((pos (or pos (point))))
  7676. (if (org-element--cache-active-p)
  7677. ;; Sync cache.
  7678. (org-with-point-at (org-element-property :begin (org-element-at-point pos))
  7679. (or (org-entry-get-with-inheritance "CATEGORY")
  7680. "???"))
  7681. (or (get-text-property pos 'org-category)
  7682. (progn
  7683. (org-refresh-category-properties)
  7684. (get-text-property pos 'org-category)))))))
  7685. ;;; Refresh properties
  7686. (defun org-refresh-properties (dprop tprop)
  7687. "Refresh buffer text properties.
  7688. DPROP is the drawer property and TPROP is either the
  7689. corresponding text property to set, or an alist with each element
  7690. being a text property (as a symbol) and a function to apply to
  7691. the value of the drawer property."
  7692. (let* ((case-fold-search t)
  7693. (inhibit-read-only t)
  7694. (inherit? (org-property-inherit-p dprop))
  7695. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  7696. (global-or-keyword (and inherit?
  7697. (org--property-global-or-keyword-value dprop nil))))
  7698. (with-silent-modifications
  7699. (org-with-point-at 1
  7700. ;; Set global and keyword based values to the whole buffer.
  7701. (when global-or-keyword
  7702. (put-text-property (point-min) (point-max) tprop global-or-keyword))
  7703. ;; Set values based on property-drawers throughout the document.
  7704. (while (re-search-forward property-re nil t)
  7705. (when (org-at-property-p)
  7706. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  7707. (outline-next-heading))))))
  7708. (defun org-refresh-property (tprop p &optional inherit)
  7709. "Refresh the buffer text property TPROP from the drawer property P.
  7710. The refresh happens only for the current entry, or the whole
  7711. sub-tree if optional argument INHERIT is non-nil.
  7712. If point is before first headline, the function applies to the
  7713. part before the first headline. In that particular case, when
  7714. optional argument INHERIT is non-nil, it refreshes properties for
  7715. the whole buffer."
  7716. (save-excursion
  7717. (org-back-to-heading-or-point-min t)
  7718. (let ((start (point))
  7719. (end (save-excursion
  7720. (cond ((and inherit (org-before-first-heading-p))
  7721. (point-max))
  7722. (inherit
  7723. (org-end-of-subtree t t))
  7724. ((outline-next-heading))
  7725. ((point-max))))))
  7726. (with-silent-modifications
  7727. (if (symbolp tprop)
  7728. ;; TPROP is a text property symbol.
  7729. (put-text-property start end tprop p)
  7730. ;; TPROP is an alist with (property . function) elements.
  7731. (pcase-dolist (`(,prop . ,f) tprop)
  7732. (put-text-property start end prop (funcall f p))))))))
  7733. (defun org-refresh-category-properties ()
  7734. "Refresh category text properties in the buffer."
  7735. (unless (org-element--cache-active-p)
  7736. (let ((case-fold-search t)
  7737. (inhibit-read-only t)
  7738. (default-category
  7739. (cond ((null org-category)
  7740. (if buffer-file-name
  7741. (file-name-sans-extension
  7742. (file-name-nondirectory buffer-file-name))
  7743. "???"))
  7744. ((symbolp org-category) (symbol-name org-category))
  7745. (t org-category))))
  7746. (let ((category (catch 'buffer-category
  7747. (org-with-wide-buffer
  7748. (goto-char (point-max))
  7749. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  7750. (let ((element (org-element-at-point-no-context)))
  7751. (when (eq (org-element-type element) 'keyword)
  7752. (throw 'buffer-category
  7753. (org-element-property :value element))))))
  7754. default-category)))
  7755. (with-silent-modifications
  7756. (org-with-wide-buffer
  7757. ;; Set buffer-wide property from keyword. Search last #+CATEGORY
  7758. ;; keyword. If none is found, fall-back to `org-category' or
  7759. ;; buffer file name, or set it by the document property drawer.
  7760. (put-text-property (point-min) (point-max)
  7761. 'org-category category)
  7762. ;; Set categories from the document property drawer or
  7763. ;; property drawers in the outline. If category is found in
  7764. ;; the property drawer for the whole buffer that value
  7765. ;; overrides the keyword-based value set above.
  7766. (goto-char (point-min))
  7767. (let ((regexp (org-re-property "CATEGORY")))
  7768. (while (re-search-forward regexp nil t)
  7769. (let ((value (match-string-no-properties 3)))
  7770. (when (org-at-property-p)
  7771. (put-text-property
  7772. (save-excursion (org-back-to-heading-or-point-min t))
  7773. (save-excursion (if (org-before-first-heading-p)
  7774. (point-max)
  7775. (org-end-of-subtree t t)))
  7776. 'org-category
  7777. value)))))))))))
  7778. (defun org-refresh-stats-properties ()
  7779. "Refresh stats text properties in the buffer."
  7780. (with-silent-modifications
  7781. (org-with-point-at 1
  7782. (let ((regexp (concat org-outline-regexp-bol
  7783. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  7784. (while (re-search-forward regexp nil t)
  7785. (let* ((numerator (string-to-number (match-string 1)))
  7786. (denominator (and (match-end 2)
  7787. (string-to-number (match-string 2))))
  7788. (stats (cond ((not denominator) numerator) ;percent
  7789. ((= denominator 0) 0)
  7790. (t (/ (* numerator 100) denominator)))))
  7791. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  7792. 'org-stats stats)))))))
  7793. (defun org-refresh-effort-properties ()
  7794. "Refresh effort properties."
  7795. (org-refresh-properties
  7796. org-effort-property
  7797. '((effort . identity)
  7798. (effort-minutes . org-duration-to-minutes))))
  7799. (defun org-find-file-at-mouse (ev)
  7800. "Open file link or URL at mouse."
  7801. (interactive "e")
  7802. (mouse-set-point ev)
  7803. (org-open-at-point 'in-emacs))
  7804. (defun org-open-at-mouse (ev)
  7805. "Open file link or URL at mouse.
  7806. See the docstring of `org-open-file' for details."
  7807. (interactive "e")
  7808. (mouse-set-point ev)
  7809. (when (eq major-mode 'org-agenda-mode)
  7810. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  7811. (org-open-at-point))
  7812. (defvar org-window-config-before-follow-link nil
  7813. "The window configuration before following a link.
  7814. This is saved in case the need arises to restore it.")
  7815. (defun org--file-default-apps ()
  7816. "Return the default applications for this operating system."
  7817. (pcase system-type
  7818. (`darwin org-file-apps-macos)
  7819. (`windows-nt org-file-apps-windowsnt)
  7820. (_ org-file-apps-gnu)))
  7821. (defun org--file-apps-entry-dlink-p (entry)
  7822. "Non-nil if ENTRY should be matched against the link by `org-open-file'.
  7823. It assumes that is the case when the entry uses a regular
  7824. expression which has at least one grouping construct and the
  7825. action is either a Lisp form or a command string containing
  7826. \"%1\", i.e., using at least one subexpression match as
  7827. a parameter."
  7828. (pcase entry
  7829. (`(,selector . ,action)
  7830. (and (stringp selector)
  7831. (> (regexp-opt-depth selector) 0)
  7832. (or (and (stringp action)
  7833. (string-match "%[0-9]" action))
  7834. (consp action))))
  7835. (_ nil)))
  7836. (defun org--file-apps-regexp-alist (list &optional add-auto-mode)
  7837. "Convert extensions to regular expressions in the cars of LIST.
  7838. Also, weed out any non-string entries, because the return value
  7839. is used only for regexp matching.
  7840. When ADD-AUTO-MODE is non-nil, make all matches in `auto-mode-alist'
  7841. point to the symbol `emacs', indicating that the file should be
  7842. opened in Emacs."
  7843. (append
  7844. (delq nil
  7845. (mapcar (lambda (x)
  7846. (unless (not (stringp (car x)))
  7847. (if (string-match "\\W" (car x))
  7848. x
  7849. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  7850. list))
  7851. (when add-auto-mode
  7852. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  7853. ;;;###autoload
  7854. (defun org-open-file (path &optional in-emacs line search)
  7855. "Open the file at PATH.
  7856. First, this expands any special file name abbreviations. Then the
  7857. configuration variable `org-file-apps' is checked if it contains an
  7858. entry for this file type, and if yes, the corresponding command is launched.
  7859. If no application is found, Emacs simply visits the file.
  7860. With optional prefix argument IN-EMACS, Emacs will visit the file.
  7861. With a double \\[universal-argument] \\[universal-argument] \
  7862. prefix arg, Org tries to avoid opening in Emacs
  7863. and to use an external application to visit the file.
  7864. Optional LINE specifies a line to go to, optional SEARCH a string
  7865. to search for. If LINE or SEARCH is given, the file will be
  7866. opened in Emacs, unless an entry from `org-file-apps' that makes
  7867. use of groups in a regexp matches.
  7868. If you want to change the way frames are used when following a
  7869. link, please customize `org-link-frame-setup'.
  7870. If the file does not exist, throw an error."
  7871. (let* ((file (if (equal path "") buffer-file-name
  7872. (substitute-in-file-name (expand-file-name path))))
  7873. (file-apps (append org-file-apps (org--file-default-apps)))
  7874. (apps (cl-remove-if #'org--file-apps-entry-dlink-p file-apps))
  7875. (apps-dlink (cl-remove-if-not #'org--file-apps-entry-dlink-p
  7876. file-apps))
  7877. (remp (and (assq 'remote apps) (file-remote-p file)))
  7878. (dirp (unless remp (file-directory-p file)))
  7879. (file (if (and dirp org-open-directory-means-index-dot-org)
  7880. (concat (file-name-as-directory file) "index.org")
  7881. file))
  7882. (a-m-a-p (assq 'auto-mode apps))
  7883. (dfile (downcase file))
  7884. ;; Reconstruct the original link from the PATH, LINE and
  7885. ;; SEARCH args.
  7886. (link (cond (line (concat file "::" (number-to-string line)))
  7887. (search (concat file "::" search))
  7888. (t file)))
  7889. (dlink (downcase link))
  7890. (ext
  7891. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  7892. (match-string 1 dfile)))
  7893. (save-position-maybe
  7894. (let ((old-buffer (current-buffer))
  7895. (old-pos (point))
  7896. (old-mode major-mode))
  7897. (lambda ()
  7898. (and (derived-mode-p 'org-mode)
  7899. (eq old-mode 'org-mode)
  7900. (or (not (eq old-buffer (current-buffer)))
  7901. (not (eq old-pos (point))))
  7902. (org-mark-ring-push old-pos old-buffer)))))
  7903. cmd link-match-data)
  7904. (cond
  7905. ((member in-emacs '((16) system))
  7906. (setq cmd (cdr (assq 'system apps))))
  7907. (in-emacs (setq cmd 'emacs))
  7908. (t
  7909. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  7910. (and dirp (cdr (assq 'directory apps)))
  7911. ;; First, try matching against apps-dlink if we
  7912. ;; get a match here, store the match data for
  7913. ;; later.
  7914. (let ((match (assoc-default dlink apps-dlink
  7915. 'string-match)))
  7916. (if match
  7917. (progn (setq link-match-data (match-data))
  7918. match)
  7919. (progn (setq in-emacs (or in-emacs line search))
  7920. nil))) ; if we have no match in apps-dlink,
  7921. ; always open the file in emacs if line or search
  7922. ; is given (for backwards compatibility)
  7923. (assoc-default dfile
  7924. (org--file-apps-regexp-alist apps a-m-a-p)
  7925. 'string-match)
  7926. (cdr (assoc ext apps))
  7927. (cdr (assq t apps))))))
  7928. (when (eq cmd 'system)
  7929. (setq cmd (cdr (assq 'system apps))))
  7930. (when (eq cmd 'default)
  7931. (setq cmd (cdr (assoc t apps))))
  7932. (when (eq cmd 'mailcap)
  7933. (require 'mailcap)
  7934. (mailcap-parse-mailcaps)
  7935. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  7936. (command (mailcap-mime-info mime-type)))
  7937. (if (stringp command)
  7938. (setq cmd command)
  7939. (setq cmd 'emacs))))
  7940. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  7941. (not (file-exists-p file))
  7942. (not org-open-non-existing-files))
  7943. (user-error "No such file: %s" file))
  7944. (cond
  7945. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  7946. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  7947. (while (string-match "['\"]%s['\"]" cmd)
  7948. (setq cmd (replace-match "%s" t t cmd)))
  7949. (setq cmd (replace-regexp-in-string
  7950. "%s"
  7951. (shell-quote-argument (convert-standard-filename file))
  7952. cmd
  7953. nil t))
  7954. ;; Replace "%1", "%2" etc. in command with group matches from regex
  7955. (save-match-data
  7956. (let ((match-index 1)
  7957. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  7958. (set-match-data link-match-data)
  7959. (while (<= match-index number-of-groups)
  7960. (let ((regex (concat "%" (number-to-string match-index)))
  7961. (replace-with (match-string match-index dlink)))
  7962. (while (string-match regex cmd)
  7963. (setq cmd (replace-match replace-with t t cmd))))
  7964. (setq match-index (+ match-index 1)))))
  7965. (save-window-excursion
  7966. (message "Running %s...done" cmd)
  7967. ;; Handlers such as "gio open" and kde-open5 start viewer in background
  7968. ;; and exit immediately. Use pipe connection type instead of pty to
  7969. ;; avoid killing children processes with SIGHUP when temporary terminal
  7970. ;; session is finished.
  7971. ;;
  7972. ;; TODO: Once minimum Emacs version is 25.1 or above, consider using
  7973. ;; the `make-process' invocation from 5db61eb0f929 to get more helpful
  7974. ;; error messages.
  7975. (let ((process-connection-type nil))
  7976. (start-process-shell-command cmd nil cmd))
  7977. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  7978. ((or (stringp cmd)
  7979. (eq cmd 'emacs))
  7980. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  7981. (widen)
  7982. (cond (line (org-goto-line line)
  7983. (when (derived-mode-p 'org-mode) (org-reveal)))
  7984. (search (condition-case err
  7985. (org-link-search search)
  7986. ;; Save position before error-ing out so user
  7987. ;; can easily move back to the original buffer.
  7988. (error (funcall save-position-maybe)
  7989. (error (nth 1 err)))))))
  7990. ((functionp cmd)
  7991. (save-match-data
  7992. (set-match-data link-match-data)
  7993. (condition-case nil
  7994. (funcall cmd file link)
  7995. ;; FIXME: Remove this check when most default installations
  7996. ;; of Emacs have at least Org 9.0.
  7997. ((debug wrong-number-of-arguments wrong-type-argument
  7998. invalid-function)
  7999. (user-error "Please see Org News for version 9.0 about \
  8000. `org-file-apps'--Lisp error: %S" cmd)))))
  8001. ((consp cmd)
  8002. ;; FIXME: Remove this check when most default installations of
  8003. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  8004. ;; fall back to `org-link-frame-setup' for an old usage of
  8005. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  8006. (user-error "Please see Org News for version 9.0 about \
  8007. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  8008. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  8009. (funcall save-position-maybe)))
  8010. ;;;###autoload
  8011. (defun org-open-at-point-global ()
  8012. "Follow a link or a time-stamp like Org mode does.
  8013. Also follow links and emails as seen by `thing-at-point'.
  8014. This command can be called in any mode to follow an external
  8015. link or a time-stamp that has Org mode syntax. Its behavior
  8016. is undefined when called on internal links like fuzzy links.
  8017. Raise a user error when there is nothing to follow."
  8018. (interactive)
  8019. (let ((tap-url (thing-at-point 'url))
  8020. (tap-email (thing-at-point 'email)))
  8021. (cond ((org-in-regexp org-link-any-re)
  8022. (org-link-open-from-string (match-string-no-properties 0)))
  8023. ((or (org-in-regexp org-ts-regexp-both nil t)
  8024. (org-in-regexp org-tsr-regexp-both nil t))
  8025. (org-follow-timestamp-link))
  8026. (tap-url (org-link-open-from-string tap-url))
  8027. (tap-email (org-link-open-from-string
  8028. (concat "mailto:" tap-email)))
  8029. (t (user-error "No link found")))))
  8030. (defvar org-open-at-point-functions nil
  8031. "Hook that is run when following a link at point.
  8032. Functions in this hook must return t if they identify and follow
  8033. a link at point. If they don't find anything interesting at point,
  8034. they must return nil.")
  8035. (defun org-open-at-point (&optional arg)
  8036. "Open link, timestamp, footnote or tags at point.
  8037. When point is on a link, follow it. Normally, files will be
  8038. opened by an appropriate application. If the optional prefix
  8039. argument ARG is non-nil, Emacs will visit the file. With
  8040. a double prefix argument, try to open outside of Emacs, in the
  8041. application the system uses for this file type.
  8042. When point is on a timestamp, open the agenda at the day
  8043. specified.
  8044. When point is a footnote definition, move to the first reference
  8045. found. If it is on a reference, move to the associated
  8046. definition.
  8047. When point is on a headline, display a list of every link in the
  8048. entry, so it is possible to pick one, or all, of them. If point
  8049. is on a tag, call `org-tags-view' instead.
  8050. On top of syntactically correct links, this function also tries
  8051. to open links and time-stamps in comments, node properties, and
  8052. keywords if point is on something looking like a timestamp or
  8053. a link."
  8054. (interactive "P")
  8055. (org-load-modules-maybe)
  8056. (setq org-window-config-before-follow-link (current-window-configuration))
  8057. (org-remove-occur-highlights nil nil t)
  8058. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  8059. (let* ((context
  8060. ;; Only consider supported types, even if they are not the
  8061. ;; closest one.
  8062. (org-element-lineage
  8063. (org-element-context)
  8064. '(citation citation-reference clock comment comment-block
  8065. footnote-definition footnote-reference headline
  8066. inline-src-block inlinetask keyword link node-property
  8067. planning src-block timestamp)
  8068. t))
  8069. (type (org-element-type context))
  8070. (value (org-element-property :value context)))
  8071. (cond
  8072. ((not type) (user-error "No link found"))
  8073. ;; No valid link at point. For convenience, look if something
  8074. ;; looks like a link under point in some specific places.
  8075. ((memq type '(comment comment-block node-property keyword))
  8076. (call-interactively #'org-open-at-point-global))
  8077. ;; On a headline or an inlinetask, but not on a timestamp,
  8078. ;; a link, a footnote reference or a citation.
  8079. ((memq type '(headline inlinetask))
  8080. (org-match-line org-complex-heading-regexp)
  8081. (let ((tags-beg (match-beginning 5))
  8082. (tags-end (match-end 5)))
  8083. (if (and tags-beg (>= (point) tags-beg) (< (point) tags-end))
  8084. ;; On tags.
  8085. (org-tags-view
  8086. arg
  8087. (save-excursion
  8088. (let* ((beg-tag (or (search-backward ":" tags-beg 'at-limit) (point)))
  8089. (end-tag (search-forward ":" tags-end nil 2)))
  8090. (buffer-substring (1+ beg-tag) (1- end-tag)))))
  8091. ;; Not on tags.
  8092. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  8093. (`(nil . ,_)
  8094. (require 'org-attach)
  8095. (when (org-attach-dir)
  8096. (message "Opening attachment")
  8097. (if (equal arg '(4))
  8098. (org-attach-reveal-in-emacs)
  8099. (org-attach-reveal))))
  8100. (`(,links . ,links-end)
  8101. (dolist (link (if (stringp links) (list links) links))
  8102. (search-forward link nil links-end)
  8103. (goto-char (match-beginning 0))
  8104. (org-open-at-point arg)))))))
  8105. ;; On a footnote reference or at definition's label.
  8106. ((or (eq type 'footnote-reference)
  8107. (and (eq type 'footnote-definition)
  8108. (save-excursion
  8109. ;; Do not validate action when point is on the
  8110. ;; spaces right after the footnote label, in order
  8111. ;; to be on par with behavior on links.
  8112. (skip-chars-forward " \t")
  8113. (let ((begin
  8114. (org-element-property :contents-begin context)))
  8115. (if begin (< (point) begin)
  8116. (= (org-element-property :post-affiliated context)
  8117. (line-beginning-position)))))))
  8118. (org-footnote-action))
  8119. ;; On a planning line. Check if we are really on a timestamp.
  8120. ((and (eq type 'planning)
  8121. (org-in-regexp org-ts-regexp-both nil t))
  8122. (org-follow-timestamp-link))
  8123. ;; On a clock line, make sure point is on the timestamp
  8124. ;; before opening it.
  8125. ((and (eq type 'clock)
  8126. value
  8127. (>= (point) (org-element-property :begin value))
  8128. (<= (point) (org-element-property :end value)))
  8129. (org-follow-timestamp-link))
  8130. ((eq type 'src-block) (org-babel-open-src-block-result))
  8131. ;; Do nothing on white spaces after an object.
  8132. ((>= (point)
  8133. (save-excursion
  8134. (goto-char (org-element-property :end context))
  8135. (skip-chars-backward " \t")
  8136. (point)))
  8137. (user-error "No link found"))
  8138. ((eq type 'inline-src-block) (org-babel-open-src-block-result))
  8139. ((eq type 'timestamp) (org-follow-timestamp-link))
  8140. ((eq type 'link) (org-link-open context arg))
  8141. ((memq type '(citation citation-reference)) (org-cite-follow context arg))
  8142. (t (user-error "No link found")))))
  8143. (run-hook-with-args 'org-follow-link-hook))
  8144. ;;;###autoload
  8145. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  8146. "Offer links in the current entry and return the selected link.
  8147. If there is only one link, return it.
  8148. If NTH is an integer, return the NTH link found.
  8149. If ZERO is a string, check also this string for a link, and if
  8150. there is one, return it."
  8151. (with-current-buffer buffer
  8152. (org-with-wide-buffer
  8153. (goto-char marker)
  8154. (let ((cnt ?0)
  8155. have-zero end links link c)
  8156. (when (and (stringp zero) (string-match org-link-bracket-re zero))
  8157. (push (match-string 0 zero) links)
  8158. (setq cnt (1- cnt) have-zero t))
  8159. (save-excursion
  8160. (org-back-to-heading t)
  8161. (setq end (save-excursion (outline-next-heading) (point)))
  8162. (while (re-search-forward org-link-any-re end t)
  8163. (push (match-string 0) links))
  8164. (setq links (org-uniquify (reverse links))))
  8165. (cond
  8166. ((null links)
  8167. (message "No links"))
  8168. ((equal (length links) 1)
  8169. (setq link (car links)))
  8170. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  8171. (setq link (nth (if have-zero nth (1- nth)) links)))
  8172. (t ; we have to select a link
  8173. (save-excursion
  8174. (save-window-excursion
  8175. (delete-other-windows)
  8176. (with-output-to-temp-buffer "*Select Link*"
  8177. (dolist (l links)
  8178. (cond
  8179. ((not (string-match org-link-bracket-re l))
  8180. (princ (format "[%c] %s\n" (cl-incf cnt)
  8181. (org-unbracket-string "<" ">" l))))
  8182. ((match-end 2)
  8183. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  8184. (match-string 2 l) (match-string 1 l))))
  8185. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  8186. (match-string 1 l)))))))
  8187. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  8188. (message "Select link to open, RET to open all:")
  8189. (setq c (read-char-exclusive))
  8190. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  8191. (when (equal c ?q) (user-error "Abort"))
  8192. (if (equal c ?\C-m)
  8193. (setq link links)
  8194. (setq nth (- c ?0))
  8195. (when have-zero (setq nth (1+ nth)))
  8196. (unless (and (integerp nth) (>= (length links) nth))
  8197. (user-error "Invalid link selection"))
  8198. (setq link (nth (1- nth) links)))))
  8199. (cons link end)))))
  8200. ;;; File search
  8201. (defun org-do-occur (regexp &optional cleanup)
  8202. "Call the Emacs command `occur'.
  8203. If CLEANUP is non-nil, remove the printout of the regular expression
  8204. in the *Occur* buffer. This is useful if the regex is long and not useful
  8205. to read."
  8206. (occur regexp)
  8207. (when cleanup
  8208. (let ((cwin (selected-window)) win beg end)
  8209. (when (setq win (get-buffer-window "*Occur*"))
  8210. (select-window win))
  8211. (goto-char (point-min))
  8212. (when (re-search-forward "match[a-z]+" nil t)
  8213. (setq beg (match-end 0))
  8214. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  8215. (setq end (1- (match-beginning 0)))))
  8216. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  8217. (goto-char (point-min))
  8218. (select-window cwin))))
  8219. ;;; The Mark Ring
  8220. (defvar org-mark-ring nil
  8221. "Mark ring for positions before jumps in Org mode.")
  8222. (defvar org-mark-ring-last-goto nil
  8223. "Last position in the mark ring used to go back.")
  8224. ;; Fill and close the ring
  8225. (setq org-mark-ring nil)
  8226. (setq org-mark-ring-last-goto nil) ;in case file is reloaded
  8227. (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
  8228. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  8229. org-mark-ring)
  8230. (defun org-mark-ring-push (&optional pos buffer)
  8231. "Put the current position into the mark ring and rotate it.
  8232. Also push position into the Emacs mark ring. If optional
  8233. argument POS and BUFFER are not nil, mark this location instead."
  8234. (interactive)
  8235. (let ((pos (or pos (point)))
  8236. (buffer (or buffer (current-buffer))))
  8237. (with-current-buffer buffer
  8238. (org-with-point-at pos (push-mark nil t)))
  8239. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  8240. (move-marker (car org-mark-ring) pos buffer))
  8241. (message
  8242. (substitute-command-keys
  8243. "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
  8244. (defun org-mark-ring-goto (&optional n)
  8245. "Jump to the previous position in the mark ring.
  8246. With prefix arg N, jump back that many stored positions. When
  8247. called several times in succession, walk through the entire ring.
  8248. Org mode commands jumping to a different position in the current file,
  8249. or to another Org file, automatically push the old position onto the ring."
  8250. (interactive "p")
  8251. (let (p m)
  8252. (if (eq last-command this-command)
  8253. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  8254. (setq p org-mark-ring))
  8255. (setq org-mark-ring-last-goto p)
  8256. (setq m (car p))
  8257. (pop-to-buffer-same-window (marker-buffer m))
  8258. (goto-char m)
  8259. (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  8260. ;;; Following specific links
  8261. (defvar org-agenda-buffer-tmp-name)
  8262. (defvar org-agenda-start-on-weekday)
  8263. (defvar org-agenda-buffer-name)
  8264. (defun org-follow-timestamp-link ()
  8265. "Open an agenda view for the time-stamp date/range at point."
  8266. ;; Avoid changing the global value.
  8267. (let ((org-agenda-buffer-name org-agenda-buffer-name))
  8268. (cond
  8269. ((org-at-date-range-p t)
  8270. (let ((org-agenda-start-on-weekday)
  8271. (t1 (match-string 1))
  8272. (t2 (match-string 2)) tt1 tt2)
  8273. (setq tt1 (time-to-days (org-time-string-to-time t1))
  8274. tt2 (time-to-days (org-time-string-to-time t2)))
  8275. (let ((org-agenda-buffer-tmp-name
  8276. (format "*Org Agenda(a:%s)"
  8277. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  8278. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  8279. ((org-at-timestamp-p 'lax)
  8280. (let ((org-agenda-buffer-tmp-name
  8281. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  8282. (org-agenda-list nil (time-to-days (org-time-string-to-time
  8283. (substring (match-string 1) 0 10)))
  8284. 1)))
  8285. (t (error "This should not happen")))))
  8286. ;;; Following file links
  8287. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  8288. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  8289. (declare-function mailcap-mime-info
  8290. "mailcap" (string &optional request no-decode))
  8291. (defvar org-wait nil)
  8292. ;;;; Refiling
  8293. (defun org-get-org-file ()
  8294. "Read a filename, with default directory `org-directory'."
  8295. (let ((default (or org-default-notes-file remember-data-file)))
  8296. (read-file-name (format "File name [%s]: " default)
  8297. (file-name-as-directory org-directory)
  8298. default)))
  8299. (defun org-notes-order-reversed-p ()
  8300. "Check if the current file should receive notes in reversed order."
  8301. (cond
  8302. ((not org-reverse-note-order) nil)
  8303. ((eq t org-reverse-note-order) t)
  8304. ((not (listp org-reverse-note-order)) nil)
  8305. (t (catch 'exit
  8306. (dolist (entry org-reverse-note-order)
  8307. (when (string-match (car entry) buffer-file-name)
  8308. (throw 'exit (cdr entry))))))))
  8309. (defvar org-agenda-new-buffers nil
  8310. "Buffers created to visit agenda files.")
  8311. (declare-function org-string-nw-p "org-macs" (s))
  8312. ;;;; Dynamic blocks
  8313. (defun org-find-dblock (name)
  8314. "Find the first dynamic block with name NAME in the buffer.
  8315. If not found, stay at current position and return nil."
  8316. (let ((case-fold-search t) pos)
  8317. (save-excursion
  8318. (goto-char (point-min))
  8319. (setq pos (and (re-search-forward
  8320. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  8321. (match-beginning 0))))
  8322. (when pos (goto-char pos))
  8323. pos))
  8324. (defun org-create-dblock (plist)
  8325. "Create a dynamic block section, with parameters taken from PLIST.
  8326. PLIST must contain a :name entry which is used as the name of the block."
  8327. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  8328. (end-of-line 1)
  8329. (newline))
  8330. (let ((col (current-column))
  8331. (name (plist-get plist :name)))
  8332. (insert "#+BEGIN: " name)
  8333. (while plist
  8334. (if (eq (car plist) :name)
  8335. (setq plist (cddr plist))
  8336. (insert " " (prin1-to-string (pop plist)))))
  8337. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  8338. (beginning-of-line -2)))
  8339. (defun org-prepare-dblock ()
  8340. "Prepare dynamic block for refresh.
  8341. This empties the block, puts the cursor at the insert position and returns
  8342. the property list including an extra property :name with the block name."
  8343. (unless (looking-at org-dblock-start-re)
  8344. (user-error "Not at a dynamic block"))
  8345. (let* ((begdel (1+ (match-end 0)))
  8346. (name (org-no-properties (match-string 1)))
  8347. (params (append (list :name name)
  8348. (read (concat "(" (match-string 3) ")")))))
  8349. (save-excursion
  8350. (beginning-of-line 1)
  8351. (skip-chars-forward " \t")
  8352. (setq params (plist-put params :indentation-column (current-column))))
  8353. (unless (re-search-forward org-dblock-end-re nil t)
  8354. (error "Dynamic block not terminated"))
  8355. (setq params
  8356. (append params
  8357. (list :content (buffer-substring
  8358. begdel (match-beginning 0)))))
  8359. (delete-region begdel (match-beginning 0))
  8360. (goto-char begdel)
  8361. (open-line 1)
  8362. params))
  8363. (defun org-map-dblocks (&optional command)
  8364. "Apply COMMAND to all dynamic blocks in the current buffer.
  8365. If COMMAND is not given, use `org-update-dblock'."
  8366. (let ((cmd (or command 'org-update-dblock)))
  8367. (save-excursion
  8368. (goto-char (point-min))
  8369. (while (re-search-forward org-dblock-start-re nil t)
  8370. (goto-char (match-beginning 0))
  8371. (save-excursion
  8372. (condition-case nil
  8373. (funcall cmd)
  8374. (error (message "Error during update of dynamic block"))))
  8375. (unless (re-search-forward org-dblock-end-re nil t)
  8376. (error "Dynamic block not terminated"))))))
  8377. (defvar org-dynamic-block-alist nil
  8378. "Alist defining all the Org dynamic blocks.
  8379. The key is the dynamic block type name, as a string. The value
  8380. is the function used to insert the dynamic block.
  8381. Use `org-dynamic-block-define' to populate it.")
  8382. (defun org-dynamic-block-function (type)
  8383. "Return function associated to a given dynamic block type.
  8384. TYPE is the dynamic block type, as a string."
  8385. (cdr (assoc type org-dynamic-block-alist)))
  8386. (defun org-dynamic-block-types ()
  8387. "List all defined dynamic block types."
  8388. (mapcar #'car org-dynamic-block-alist))
  8389. (defun org-dynamic-block-define (type func)
  8390. "Define dynamic block TYPE with FUNC.
  8391. TYPE is a string. FUNC is the function creating the dynamic
  8392. block of such type."
  8393. (pcase (assoc type org-dynamic-block-alist)
  8394. (`nil (push (cons type func) org-dynamic-block-alist))
  8395. (def (setcdr def func))))
  8396. (defun org-dynamic-block-insert-dblock (type &optional interactive-p)
  8397. "Insert a dynamic block of type TYPE.
  8398. When used interactively, select the dynamic block types among
  8399. defined types, per `org-dynamic-block-define'. If INTERACTIVE-P
  8400. is non-nil, call the dynamic block function interactively."
  8401. (interactive (list (completing-read "Dynamic block: "
  8402. (org-dynamic-block-types))
  8403. t))
  8404. (pcase (org-dynamic-block-function type)
  8405. (`nil (error "No such dynamic block: %S" type))
  8406. ((and f (pred functionp))
  8407. (if interactive-p (call-interactively f) (funcall f)))
  8408. (_ (error "Invalid function for dynamic block %S" type))))
  8409. (defun org-dblock-update (&optional arg)
  8410. "User command for updating dynamic blocks.
  8411. Update the dynamic block at point. With prefix ARG, update all dynamic
  8412. blocks in the buffer."
  8413. (interactive "P")
  8414. (if arg
  8415. (org-update-all-dblocks)
  8416. (or (looking-at org-dblock-start-re)
  8417. (org-beginning-of-dblock))
  8418. (org-update-dblock)))
  8419. (defun org-update-dblock ()
  8420. "Update the dynamic block at point.
  8421. This means to empty the block, parse for parameters and then call
  8422. the correct writing function."
  8423. (interactive)
  8424. (save-excursion
  8425. (let* ((win (selected-window))
  8426. (pos (point))
  8427. (line (org-current-line))
  8428. (params (org-prepare-dblock))
  8429. (name (plist-get params :name))
  8430. (indent (plist-get params :indentation-column))
  8431. (cmd (intern (concat "org-dblock-write:" name))))
  8432. (message "Updating dynamic block `%s' at line %d..." name line)
  8433. (funcall cmd params)
  8434. (message "Updating dynamic block `%s' at line %d...done" name line)
  8435. (goto-char pos)
  8436. (when (and indent (> indent 0))
  8437. (setq indent (make-string indent ?\ ))
  8438. (save-excursion
  8439. (select-window win)
  8440. (org-beginning-of-dblock)
  8441. (forward-line 1)
  8442. (while (not (looking-at org-dblock-end-re))
  8443. (insert indent)
  8444. (beginning-of-line 2))
  8445. (when (looking-at org-dblock-end-re)
  8446. (and (looking-at "[ \t]+")
  8447. (replace-match ""))
  8448. (insert indent)))))))
  8449. (defun org-beginning-of-dblock ()
  8450. "Find the beginning of the dynamic block at point.
  8451. Error if there is no such block at point."
  8452. (let ((pos (point))
  8453. beg)
  8454. (end-of-line 1)
  8455. (if (and (re-search-backward org-dblock-start-re nil t)
  8456. (setq beg (match-beginning 0))
  8457. (re-search-forward org-dblock-end-re nil t)
  8458. (> (match-end 0) pos))
  8459. (goto-char beg)
  8460. (goto-char pos)
  8461. (error "Not in a dynamic block"))))
  8462. (defun org-update-all-dblocks ()
  8463. "Update all dynamic blocks in the buffer.
  8464. This function can be used in a hook."
  8465. (interactive)
  8466. (when (derived-mode-p 'org-mode)
  8467. (org-map-dblocks 'org-update-dblock)))
  8468. ;;;; Completion
  8469. (declare-function org-export-backend-options "ox" (cl-x) t)
  8470. (defun org-get-export-keywords ()
  8471. "Return a list of all currently understood export keywords.
  8472. Export keywords include options, block names, attributes and
  8473. keywords relative to each registered export back-end."
  8474. (let (keywords)
  8475. (dolist (backend
  8476. (bound-and-true-p org-export-registered-backends)
  8477. (delq nil keywords))
  8478. ;; Back-end name (for keywords, like #+LATEX:)
  8479. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  8480. (dolist (option-entry (org-export-backend-options backend))
  8481. ;; Back-end options.
  8482. (push (nth 1 option-entry) keywords)))))
  8483. (defconst org-options-keywords
  8484. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  8485. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  8486. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  8487. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  8488. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  8489. (defcustom org-structure-template-alist
  8490. '(("a" . "export ascii")
  8491. ("c" . "center")
  8492. ("C" . "comment")
  8493. ("e" . "example")
  8494. ("E" . "export")
  8495. ("h" . "export html")
  8496. ("l" . "export latex")
  8497. ("q" . "quote")
  8498. ("s" . "src")
  8499. ("v" . "verse"))
  8500. "An alist of keys and block types.
  8501. `org-insert-structure-template' will display a menu with this
  8502. list of templates to choose from. The block type is inserted,
  8503. with \"#+BEGIN_\" and \"#+END_\" added automatically.
  8504. The menu keys are defined by the car of each entry in this alist.
  8505. If two entries have the keys \"a\" and \"aa\" respectively, the
  8506. former will be inserted by typing \"a TAB/RET/SPC\" and the
  8507. latter will be inserted by typing \"aa\". If an entry with the
  8508. key \"aab\" is later added, it can be inserted by typing \"ab\".
  8509. If loaded, Org Tempo also uses `org-structure-template-alist'. A
  8510. block can be inserted by pressing TAB after the string \"<KEY\"."
  8511. :group 'org-edit-structure
  8512. :type '(repeat
  8513. (cons (string :tag "Key")
  8514. (string :tag "Template")))
  8515. :package-version '(Org . "9.2"))
  8516. (defun org--check-org-structure-template-alist (&optional checklist)
  8517. "Check whether `org-structure-template-alist' is set up correctly.
  8518. In particular, check if the Org 9.2 format is used as opposed to
  8519. previous format."
  8520. (let ((elm (cl-remove-if-not (lambda (x) (listp (cdr x)))
  8521. (or (eval checklist)
  8522. org-structure-template-alist))))
  8523. (when elm
  8524. (org-display-warning
  8525. (format "
  8526. Please update the entries of `%s'.
  8527. In Org 9.2 the format was changed from something like
  8528. (\"s\" \"#+BEGIN_SRC ?\\n#+END_SRC\")
  8529. to something like
  8530. (\"s\" . \"src\")
  8531. Please refer to the documentation of `org-structure-template-alist'.
  8532. The following entries must be updated:
  8533. %s"
  8534. (or checklist 'org-structure-template-alist)
  8535. (pp-to-string elm))))))
  8536. (defun org--insert-structure-template-mks ()
  8537. "Present `org-structure-template-alist' with `org-mks'.
  8538. Menus are added if keys require more than one keystroke. Tabs
  8539. are added to single key entries when more than one stroke is
  8540. needed. Keys longer than two characters are reduced to two
  8541. characters."
  8542. (org--check-org-structure-template-alist)
  8543. (let* (case-fold-search
  8544. (templates (append org-structure-template-alist
  8545. '(("\t" . "Press TAB, RET or SPC to write block name"))))
  8546. (keys (mapcar #'car templates))
  8547. (start-letters
  8548. (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
  8549. ;; Sort each element of `org-structure-template-alist' into
  8550. ;; sublists according to the first letter.
  8551. (superlist
  8552. (mapcar (lambda (letter)
  8553. (list letter
  8554. (cl-remove-if-not
  8555. (apply-partially #'string-match-p (concat "^" letter))
  8556. templates :key #'car)))
  8557. start-letters)))
  8558. (org-mks
  8559. (apply #'append
  8560. ;; Make an `org-mks' table. If only one element is
  8561. ;; present in a sublist, make it part of the top-menu,
  8562. ;; otherwise make a submenu according to the starting
  8563. ;; letter and populate it.
  8564. (mapcar (lambda (sublist)
  8565. (if (eq 1 (length (cadr sublist)))
  8566. (mapcar (lambda (elm)
  8567. (list (substring (car elm) 0 1)
  8568. (cdr elm) ""))
  8569. (cadr sublist))
  8570. ;; Create submenu.
  8571. (let* ((topkey (car sublist))
  8572. (elms (cadr sublist))
  8573. (keys (mapcar #'car elms))
  8574. (long (> (length elms) 3)))
  8575. (append
  8576. (list
  8577. ;; Make a description of the submenu.
  8578. (list topkey
  8579. (concat
  8580. (mapconcat #'cdr
  8581. (cl-subseq elms 0 (if long 3 (length elms)))
  8582. ", ")
  8583. (when long ", ..."))))
  8584. ;; List of entries in submenu.
  8585. (cl-mapcar #'list
  8586. (org--insert-structure-template-unique-keys keys)
  8587. (mapcar #'cdr elms)
  8588. (make-list (length elms) ""))))))
  8589. superlist))
  8590. "Select a key\n============"
  8591. "Key: ")))
  8592. (defun org--insert-structure-template-unique-keys (keys)
  8593. "Make a list of unique, two characters long elements from KEYS.
  8594. Elements of length one have a tab appended. Elements of length
  8595. two are kept as is. Longer elements are truncated to length two.
  8596. If an element cannot be made unique, an error is raised."
  8597. (let ((ordered-keys (cl-sort (copy-sequence keys) #'< :key #'length))
  8598. menu-keys)
  8599. (dolist (key ordered-keys)
  8600. (let ((potential-key
  8601. (cl-case (length key)
  8602. (1 (concat key "\t"))
  8603. (2 key)
  8604. (otherwise
  8605. (cl-find-if-not (lambda (k) (assoc k menu-keys))
  8606. (mapcar (apply-partially #'concat (substring key 0 1))
  8607. (split-string (substring key 1) "" t)))))))
  8608. (if (or (not potential-key) (assoc potential-key menu-keys))
  8609. (user-error "Could not make unique key for `%s'" key)
  8610. (push (cons potential-key key) menu-keys))))
  8611. (mapcar #'car
  8612. (cl-sort menu-keys #'<
  8613. :key (lambda (elm) (cl-position (cdr elm) keys))))))
  8614. (defun org-insert-structure-template (type)
  8615. "Insert a block structure of the type #+begin_foo/#+end_foo.
  8616. Select a block from `org-structure-template-alist' then type
  8617. either RET, TAB or SPC to write the block type. With an active
  8618. region, wrap the region in the block. Otherwise, insert an empty
  8619. block."
  8620. (interactive
  8621. (list (pcase (org--insert-structure-template-mks)
  8622. (`("\t" . ,_) (read-string "Structure type: "))
  8623. (`(,_ ,choice . ,_) choice))))
  8624. (let* ((region? (use-region-p))
  8625. (region-start (and region? (region-beginning)))
  8626. (region-end (and region? (copy-marker (region-end))))
  8627. (extended? (string-match-p "\\`\\(src\\|export\\)\\'" type))
  8628. (verbatim? (string-match-p
  8629. (concat "\\`" (regexp-opt '("example" "export" "src")))
  8630. type)))
  8631. (when region? (goto-char region-start))
  8632. (let ((column (current-indentation)))
  8633. (if (save-excursion (skip-chars-backward " \t") (bolp))
  8634. (beginning-of-line)
  8635. (insert "\n"))
  8636. (save-excursion
  8637. (indent-to column)
  8638. (insert (format "#+begin_%s%s\n" type (if extended? " " "")))
  8639. (when region?
  8640. (when verbatim? (org-escape-code-in-region (point) region-end))
  8641. (goto-char region-end)
  8642. ;; Ignore empty lines at the end of the region.
  8643. (skip-chars-backward " \r\t\n")
  8644. (end-of-line))
  8645. (unless (bolp) (insert "\n"))
  8646. (indent-to column)
  8647. (insert (format "#+end_%s" (car (split-string type))))
  8648. (if (looking-at "[ \t]*$") (replace-match "")
  8649. (insert "\n"))
  8650. (when (and (eobp) (not (bolp))) (insert "\n")))
  8651. (if extended? (end-of-line)
  8652. (forward-line)
  8653. (skip-chars-forward " \t")))))
  8654. ;;;; TODO, DEADLINE, Comments
  8655. (defun org-toggle-comment ()
  8656. "Change the COMMENT state of an entry."
  8657. (interactive)
  8658. (save-excursion
  8659. (org-back-to-heading)
  8660. (let ((case-fold-search nil))
  8661. (looking-at org-complex-heading-regexp))
  8662. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  8663. (skip-chars-forward " \t")
  8664. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  8665. (if (org-in-commented-heading-p t)
  8666. (delete-region (point)
  8667. (progn (search-forward " " (line-end-position) 'move)
  8668. (skip-chars-forward " \t")
  8669. (point)))
  8670. (insert org-comment-string)
  8671. (unless (eolp) (insert " ")))))
  8672. (defvar org-last-todo-state-is-todo nil
  8673. "This is non-nil when the last TODO state change led to a TODO state.
  8674. If the last change removed the TODO tag or switched to DONE, then
  8675. this is nil.")
  8676. (defvar org-todo-setup-filter-hook nil
  8677. "Hook for functions that pre-filter todo specs.
  8678. Each function takes a todo spec and returns either nil or the spec
  8679. transformed into canonical form." )
  8680. (defvar org-todo-get-default-hook nil
  8681. "Hook for functions that get a default item for todo.
  8682. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  8683. nil or a string to be used for the todo mark." )
  8684. (defvar org-agenda-headline-snapshot-before-repeat)
  8685. (defun org-current-effective-time ()
  8686. "Return current time adjusted for `org-extend-today-until' variable."
  8687. (let* ((ct (org-current-time))
  8688. (dct (decode-time ct))
  8689. (ct1
  8690. (cond
  8691. (org-use-last-clock-out-time-as-effective-time
  8692. (or (org-clock-get-last-clock-out-time) ct))
  8693. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  8694. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  8695. (t ct))))
  8696. ct1))
  8697. (defun org-todo-yesterday (&optional arg)
  8698. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  8699. (interactive "P")
  8700. (if (eq major-mode 'org-agenda-mode)
  8701. (apply 'org-agenda-todo-yesterday arg)
  8702. (let* ((org-use-effective-time t)
  8703. (hour (nth 2 (decode-time (org-current-time))))
  8704. (org-extend-today-until (1+ hour)))
  8705. (org-todo arg))))
  8706. (defvar org-block-entry-blocking ""
  8707. "First entry preventing the TODO state change.")
  8708. (defun org-cancel-repeater ()
  8709. "Cancel a repeater by setting its numeric value to zero."
  8710. (interactive)
  8711. (save-excursion
  8712. (org-back-to-heading t)
  8713. (let ((bound1 (point))
  8714. (bound0 (save-excursion (outline-next-heading) (point))))
  8715. (when (and (re-search-forward
  8716. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  8717. org-deadline-time-regexp "\\)\\|\\("
  8718. org-ts-regexp "\\)")
  8719. bound0 t)
  8720. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  8721. bound1 t))
  8722. (replace-match "0" t nil nil 1)))))
  8723. (defvar org-state)
  8724. (defvar org-blocked-by-checkboxes)
  8725. (defun org-todo (&optional arg)
  8726. "Change the TODO state of an item.
  8727. The state of an item is given by a keyword at the start of the heading,
  8728. like
  8729. *** TODO Write paper
  8730. *** DONE Call mom
  8731. The different keywords are specified in the variable `org-todo-keywords'.
  8732. By default the available states are \"TODO\" and \"DONE\". So, for this
  8733. example: when the item starts with TODO, it is changed to DONE.
  8734. When it starts with DONE, the DONE is removed. And when neither TODO nor
  8735. DONE are present, add TODO at the beginning of the heading.
  8736. You can set up single-character keys to fast-select the new state. See the
  8737. `org-todo-keywords' and `org-use-fast-todo-selection' for details.
  8738. With `\\[universal-argument]' prefix ARG, force logging the state change \
  8739. and take a
  8740. logging note.
  8741. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  8742. next set of TODO \
  8743. keywords (nextset).
  8744. Another way to achieve this is `S-C-<right>'.
  8745. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8746. prefix, circumvent any state blocking.
  8747. With numeric prefix arg, switch to the Nth state.
  8748. With a numeric prefix arg of 0, inhibit note taking for the change.
  8749. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  8750. When called through ELisp, arg is also interpreted in the following way:
  8751. `none' -> empty state
  8752. \"\" -> switch to empty state
  8753. `done' -> switch to DONE
  8754. `nextset' -> switch to the next set of keywords
  8755. `previousset' -> switch to the previous set of keywords
  8756. \"WAITING\" -> switch to the specified keyword, but only if it
  8757. really is a member of `org-todo-keywords'."
  8758. (interactive "P")
  8759. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  8760. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  8761. 'region-start-level 'region))
  8762. org-loop-over-headlines-in-active-region)
  8763. (org-map-entries
  8764. (lambda () (org-todo arg))
  8765. nil cl
  8766. (when (org-invisible-p) (org-end-of-subtree nil t))))
  8767. (when (equal arg '(16)) (setq arg 'nextset))
  8768. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  8769. (let ((org-blocker-hook org-blocker-hook)
  8770. commentp
  8771. case-fold-search)
  8772. (when (equal arg '(64))
  8773. (setq arg nil org-blocker-hook nil))
  8774. (when (and org-blocker-hook
  8775. (or org-inhibit-blocking
  8776. (org-entry-get nil "NOBLOCKING")))
  8777. (setq org-blocker-hook nil))
  8778. (save-excursion
  8779. (catch 'exit
  8780. (org-back-to-heading t)
  8781. (when (org-in-commented-heading-p t)
  8782. (org-toggle-comment)
  8783. (setq commentp t))
  8784. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  8785. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  8786. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  8787. (let* ((match-data (match-data))
  8788. (startpos (copy-marker (line-beginning-position)))
  8789. (force-log (and (equal arg '(4)) (prog1 t (setq arg nil))))
  8790. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  8791. (org-log-done org-log-done)
  8792. (org-log-repeat org-log-repeat)
  8793. (org-todo-log-states org-todo-log-states)
  8794. (org-inhibit-logging
  8795. (if (equal arg 0)
  8796. (progn (setq arg nil) 'note) org-inhibit-logging))
  8797. (this (match-string 1))
  8798. (hl-pos (match-beginning 0))
  8799. (head (org-get-todo-sequence-head this))
  8800. (ass (assoc head org-todo-kwd-alist))
  8801. (interpret (nth 1 ass))
  8802. (done-word (nth 3 ass))
  8803. (final-done-word (nth 4 ass))
  8804. (org-last-state (or this ""))
  8805. (completion-ignore-case t)
  8806. (member (member this org-todo-keywords-1))
  8807. (tail (cdr member))
  8808. (org-state (cond
  8809. ((eq arg 'right)
  8810. ;; Next state
  8811. (if this
  8812. (if tail (car tail) nil)
  8813. (car org-todo-keywords-1)))
  8814. ((eq arg 'left)
  8815. ;; Previous state
  8816. (unless (equal member org-todo-keywords-1)
  8817. (if this
  8818. (nth (- (length org-todo-keywords-1)
  8819. (length tail) 2)
  8820. org-todo-keywords-1)
  8821. (org-last org-todo-keywords-1))))
  8822. (arg
  8823. ;; User or caller requests a specific state.
  8824. (cond
  8825. ((equal arg "") nil)
  8826. ((eq arg 'none) nil)
  8827. ((eq arg 'done) (or done-word (car org-done-keywords)))
  8828. ((eq arg 'nextset)
  8829. (or (car (cdr (member head org-todo-heads)))
  8830. (car org-todo-heads)))
  8831. ((eq arg 'previousset)
  8832. (let ((org-todo-heads (reverse org-todo-heads)))
  8833. (or (car (cdr (member head org-todo-heads)))
  8834. (car org-todo-heads))))
  8835. ((car (member arg org-todo-keywords-1)))
  8836. ((stringp arg)
  8837. (user-error "State `%s' not valid in this file" arg))
  8838. ((nth (1- (prefix-numeric-value arg))
  8839. org-todo-keywords-1))))
  8840. ((and org-todo-key-trigger org-use-fast-todo-selection)
  8841. ;; Use fast selection.
  8842. (org-fast-todo-selection this))
  8843. ((null member) (or head (car org-todo-keywords-1)))
  8844. ((equal this final-done-word) nil) ;-> make empty
  8845. ((null tail) nil) ;-> first entry
  8846. ((memq interpret '(type priority))
  8847. (if (eq this-command last-command)
  8848. (car tail)
  8849. (if (> (length tail) 0)
  8850. (or done-word (car org-done-keywords))
  8851. nil)))
  8852. (t
  8853. (car tail))))
  8854. (org-state (or
  8855. (run-hook-with-args-until-success
  8856. 'org-todo-get-default-hook org-state org-last-state)
  8857. org-state))
  8858. (next (if (org-string-nw-p org-state) (concat " " org-state " ") " "))
  8859. (change-plist (list :type 'todo-state-change :from this :to org-state
  8860. :position startpos))
  8861. dolog now-done-p)
  8862. (when org-blocker-hook
  8863. (let (org-blocked-by-checkboxes block-reason)
  8864. (setq org-last-todo-state-is-todo
  8865. (not (member this org-done-keywords)))
  8866. (unless (save-excursion
  8867. (save-match-data
  8868. (org-with-wide-buffer
  8869. (run-hook-with-args-until-failure
  8870. 'org-blocker-hook change-plist))))
  8871. (setq block-reason (if org-blocked-by-checkboxes
  8872. "contained checkboxes"
  8873. (format "\"%s\"" org-block-entry-blocking)))
  8874. (if (called-interactively-p 'interactive)
  8875. (user-error "TODO state change from %s to %s blocked (by %s)"
  8876. this org-state block-reason)
  8877. ;; Fail silently.
  8878. (message "TODO state change from %s to %s blocked (by %s)"
  8879. this org-state block-reason)
  8880. (throw 'exit nil)))))
  8881. (store-match-data match-data)
  8882. (replace-match next t t)
  8883. (cond ((and org-state (equal this org-state))
  8884. (message "TODO state was already %s" (org-trim next)))
  8885. ((not (pos-visible-in-window-p hl-pos))
  8886. (message "TODO state changed to %s" (org-trim next))))
  8887. (unless head
  8888. (setq head (org-get-todo-sequence-head org-state)
  8889. ass (assoc head org-todo-kwd-alist)
  8890. interpret (nth 1 ass)
  8891. done-word (nth 3 ass)
  8892. final-done-word (nth 4 ass)))
  8893. (when (memq arg '(nextset previousset))
  8894. (message "Keyword-Set %d/%d: %s"
  8895. (- (length org-todo-sets) -1
  8896. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  8897. (length org-todo-sets)
  8898. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  8899. (setq org-last-todo-state-is-todo
  8900. (not (member org-state org-done-keywords)))
  8901. (setq now-done-p (and (member org-state org-done-keywords)
  8902. (not (member this org-done-keywords))))
  8903. (and logging (org-local-logging logging))
  8904. (when (or (and (or org-todo-log-states org-log-done)
  8905. (not (eq org-inhibit-logging t))
  8906. (not (memq arg '(nextset previousset))))
  8907. force-log)
  8908. ;; We need to look at recording a time and note.
  8909. (setq dolog (or (if force-log 'note)
  8910. (nth 1 (assoc org-state org-todo-log-states))
  8911. (nth 2 (assoc this org-todo-log-states))))
  8912. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  8913. (setq dolog 'time))
  8914. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  8915. (and org-state
  8916. (member org-state org-not-done-keywords)
  8917. (not (member this org-not-done-keywords))))
  8918. ;; This is now a todo state and was not one before
  8919. ;; If there was a CLOSED time stamp, get rid of it.
  8920. (org-add-planning-info nil nil 'closed))
  8921. (when (and now-done-p org-log-done)
  8922. ;; It is now done, and it was not done before.
  8923. (org-add-planning-info 'closed (org-current-effective-time))
  8924. (when (and (not dolog) (eq 'note org-log-done))
  8925. (org-add-log-setup 'done org-state this 'note)))
  8926. (when (and org-state dolog)
  8927. ;; This is a non-nil state, and we need to log it.
  8928. (org-add-log-setup 'state org-state this dolog)))
  8929. ;; Fixup tag positioning.
  8930. (org-todo-trigger-tag-changes org-state)
  8931. (when org-auto-align-tags (org-align-tags))
  8932. (when org-provide-todo-statistics
  8933. (org-update-parent-todo-statistics))
  8934. (when (bound-and-true-p org-clock-out-when-done)
  8935. (org-clock-out-if-current))
  8936. (run-hooks 'org-after-todo-state-change-hook)
  8937. (when (and arg (not (member org-state org-done-keywords)))
  8938. (setq head (org-get-todo-sequence-head org-state)))
  8939. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  8940. ;; Do we need to trigger a repeat?
  8941. (when now-done-p
  8942. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  8943. ;; This is for the agenda, take a snapshot of the headline.
  8944. (save-match-data
  8945. (setq org-agenda-headline-snapshot-before-repeat
  8946. (org-get-heading))))
  8947. (org-auto-repeat-maybe org-state))
  8948. ;; Fixup cursor location if close to the keyword.
  8949. (when (and (outline-on-heading-p)
  8950. (not (bolp))
  8951. (save-excursion (beginning-of-line 1)
  8952. (looking-at org-todo-line-regexp))
  8953. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  8954. (goto-char (or (match-end 2) (match-end 1)))
  8955. (and (looking-at " ")
  8956. (not (looking-at " *:"))
  8957. (just-one-space)))
  8958. (when org-trigger-hook
  8959. (save-excursion
  8960. (run-hook-with-args 'org-trigger-hook change-plist)))
  8961. (when commentp (org-toggle-comment))))))))
  8962. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  8963. "Block turning an entry into a TODO, using the hierarchy.
  8964. This checks whether the current task should be blocked from state
  8965. changes. Such blocking occurs when:
  8966. 1. The task has children which are not all in a completed state.
  8967. 2. A task has a parent with the property :ORDERED:, and there
  8968. are siblings prior to the current task with incomplete
  8969. status.
  8970. 3. The parent of the task is blocked because it has siblings that should
  8971. be done first, or is child of a block grandparent TODO entry."
  8972. (if (not org-enforce-todo-dependencies)
  8973. t ; if locally turned off don't block
  8974. (catch 'dont-block
  8975. ;; If this is not a todo state change, or if this entry is already DONE,
  8976. ;; do not block
  8977. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  8978. (member (plist-get change-plist :from)
  8979. (cons 'done org-done-keywords))
  8980. (member (plist-get change-plist :to)
  8981. (cons 'todo org-not-done-keywords))
  8982. (not (plist-get change-plist :to)))
  8983. (throw 'dont-block t))
  8984. ;; If this task has children, and any are undone, it's blocked
  8985. (save-excursion
  8986. (org-back-to-heading t)
  8987. (let ((this-level (funcall outline-level)))
  8988. (outline-next-heading)
  8989. (let ((child-level (funcall outline-level)))
  8990. (while (and (not (eobp))
  8991. (> child-level this-level))
  8992. ;; this todo has children, check whether they are all
  8993. ;; completed
  8994. (when (and (not (org-entry-is-done-p))
  8995. (org-entry-is-todo-p))
  8996. (setq org-block-entry-blocking (org-get-heading))
  8997. (throw 'dont-block nil))
  8998. (outline-next-heading)
  8999. (setq child-level (funcall outline-level))))))
  9000. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  9001. ;; any previous siblings are undone, it's blocked
  9002. (save-excursion
  9003. (org-back-to-heading t)
  9004. (let* ((pos (point))
  9005. (parent-pos (and (org-up-heading-safe) (point)))
  9006. (case-fold-search nil))
  9007. (unless parent-pos (throw 'dont-block t)) ; no parent
  9008. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  9009. (forward-line 1)
  9010. (re-search-forward org-not-done-heading-regexp pos t))
  9011. (setq org-block-entry-blocking (match-string 0))
  9012. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  9013. ;; Search further up the hierarchy, to see if an ancestor is blocked
  9014. (while t
  9015. (goto-char parent-pos)
  9016. (unless (looking-at org-not-done-heading-regexp)
  9017. (throw 'dont-block t)) ; do not block, parent is not a TODO
  9018. (setq pos (point))
  9019. (setq parent-pos (and (org-up-heading-safe) (point)))
  9020. (unless parent-pos (throw 'dont-block t)) ; no parent
  9021. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  9022. (forward-line 1)
  9023. (re-search-forward org-not-done-heading-regexp pos t)
  9024. (setq org-block-entry-blocking (org-get-heading)))
  9025. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  9026. (defcustom org-track-ordered-property-with-tag nil
  9027. "Should the ORDERED property also be shown as a tag?
  9028. The ORDERED property decides if an entry should require subtasks to be
  9029. completed in sequence. Since a property is not very visible, setting
  9030. this option means that toggling the ORDERED property with the command
  9031. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  9032. not relevant for the behavior, but it makes things more visible.
  9033. Note that toggling the tag with tags commands will not change the property
  9034. and therefore not influence behavior!
  9035. This can be t, meaning the tag ORDERED should be used. It can also be a
  9036. string to select a different tag for this task."
  9037. :group 'org-todo
  9038. :type '(choice
  9039. (const :tag "No tracking" nil)
  9040. (const :tag "Track with ORDERED tag" t)
  9041. (string :tag "Use other tag")))
  9042. (defun org-toggle-ordered-property ()
  9043. "Toggle the ORDERED property of the current entry.
  9044. For better visibility, you can track the value of this property with a tag.
  9045. See variable `org-track-ordered-property-with-tag'."
  9046. (interactive)
  9047. (let* ((t1 org-track-ordered-property-with-tag)
  9048. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  9049. (save-excursion
  9050. (org-back-to-heading)
  9051. (if (org-entry-get nil "ORDERED")
  9052. (progn
  9053. (org-delete-property "ORDERED")
  9054. (and tag (org-toggle-tag tag 'off))
  9055. (message "Subtasks can be completed in arbitrary order"))
  9056. (org-entry-put nil "ORDERED" "t")
  9057. (and tag (org-toggle-tag tag 'on))
  9058. (message "Subtasks must be completed in sequence")))))
  9059. (defun org-block-todo-from-checkboxes (change-plist)
  9060. "Block turning an entry into a TODO, using checkboxes.
  9061. This checks whether the current task should be blocked from state
  9062. changes because there are unchecked boxes in this entry."
  9063. (if (not org-enforce-todo-checkbox-dependencies)
  9064. t ; if locally turned off don't block
  9065. (catch 'dont-block
  9066. ;; If this is not a todo state change, or if this entry is already DONE,
  9067. ;; do not block
  9068. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  9069. (member (plist-get change-plist :from)
  9070. (cons 'done org-done-keywords))
  9071. (member (plist-get change-plist :to)
  9072. (cons 'todo org-not-done-keywords))
  9073. (not (plist-get change-plist :to)))
  9074. (throw 'dont-block t))
  9075. ;; If this task has checkboxes that are not checked, it's blocked
  9076. (save-excursion
  9077. (org-back-to-heading t)
  9078. (let ((beg (point)) end)
  9079. (outline-next-heading)
  9080. (setq end (point))
  9081. (goto-char beg)
  9082. (when (org-list-search-forward
  9083. (concat (org-item-beginning-re)
  9084. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  9085. "\\[[- ]\\]")
  9086. end t)
  9087. (when (boundp 'org-blocked-by-checkboxes)
  9088. (setq org-blocked-by-checkboxes t))
  9089. (throw 'dont-block nil))))
  9090. t))) ; do not block
  9091. (defun org-entry-blocked-p ()
  9092. "Non-nil if entry at point is blocked."
  9093. (and (not (org-entry-get nil "NOBLOCKING"))
  9094. (member (org-entry-get nil "TODO") org-not-done-keywords)
  9095. (not (run-hook-with-args-until-failure
  9096. 'org-blocker-hook
  9097. (list :type 'todo-state-change
  9098. :position (point)
  9099. :from 'todo
  9100. :to 'done)))))
  9101. (defun org-update-statistics-cookies (all)
  9102. "Update the statistics cookie, either from TODO or from checkboxes.
  9103. This should be called with the cursor in a line with a statistics
  9104. cookie. When called with a \\[universal-argument] prefix, update
  9105. all statistics cookies in the buffer."
  9106. (interactive "P")
  9107. (if all
  9108. (progn
  9109. (org-update-checkbox-count 'all)
  9110. (org-map-region 'org-update-parent-todo-statistics
  9111. (point-min) (point-max)))
  9112. (if (not (org-at-heading-p))
  9113. (org-update-checkbox-count)
  9114. (let ((pos (point-marker))
  9115. end l1 l2)
  9116. (ignore-errors (org-back-to-heading t))
  9117. (if (not (org-at-heading-p))
  9118. (org-update-checkbox-count)
  9119. (setq l1 (org-outline-level))
  9120. (setq end
  9121. (save-excursion
  9122. (outline-next-heading)
  9123. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  9124. (point)))
  9125. (if (and (save-excursion
  9126. (re-search-forward
  9127. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  9128. (not (save-excursion
  9129. (re-search-forward
  9130. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  9131. (org-update-checkbox-count)
  9132. (if (and l2 (> l2 l1))
  9133. (progn
  9134. (goto-char end)
  9135. (org-update-parent-todo-statistics))
  9136. (goto-char pos)
  9137. (beginning-of-line 1)
  9138. (while (re-search-forward
  9139. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  9140. (point-at-eol) t)
  9141. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  9142. (goto-char pos)
  9143. (move-marker pos nil)))))
  9144. (defvar org-entry-property-inherited-from) ;; defined below
  9145. (defun org-update-parent-todo-statistics ()
  9146. "Update any statistics cookie in the parent of the current headline.
  9147. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  9148. the entire subtree and this will travel up the hierarchy and update
  9149. statistics everywhere."
  9150. (let* ((prop (save-excursion
  9151. (org-up-heading-safe)
  9152. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  9153. (recursive (or (not org-hierarchical-todo-statistics)
  9154. (and prop (string-match "\\<recursive\\>" prop))))
  9155. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  9156. 0))
  9157. (first t)
  9158. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  9159. level ltoggle l1 new ndel
  9160. (cnt-all 0) (cnt-done 0) is-percent kwd
  9161. checkbox-beg cookie-present)
  9162. (catch 'exit
  9163. (save-excursion
  9164. (beginning-of-line 1)
  9165. (setq ltoggle (funcall outline-level))
  9166. ;; Three situations are to consider:
  9167. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  9168. ;; to the top-level ancestor on the headline;
  9169. ;; 2. If parent has "recursive" property, repeat up to the
  9170. ;; headline setting that property, taking inheritance into
  9171. ;; account;
  9172. ;; 3. Else, move up to direct parent and proceed only once.
  9173. (while (and (setq level (org-up-heading-safe))
  9174. (or recursive first)
  9175. (>= (point) lim))
  9176. (setq first nil cookie-present nil)
  9177. (unless (and level
  9178. (not (string-match
  9179. "\\<checkbox\\>"
  9180. (downcase (or (org-entry-get nil "COOKIE_DATA")
  9181. "")))))
  9182. (throw 'exit nil))
  9183. (while (re-search-forward box-re (point-at-eol) t)
  9184. (setq cnt-all 0 cnt-done 0 cookie-present t)
  9185. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  9186. (save-match-data
  9187. (unless (outline-next-heading) (throw 'exit nil))
  9188. (while (and (looking-at org-complex-heading-regexp)
  9189. (> (setq l1 (length (match-string 1))) level))
  9190. (setq kwd (and (or recursive (= l1 ltoggle))
  9191. (match-string 2)))
  9192. (if (or (eq org-provide-todo-statistics 'all-headlines)
  9193. (and (eq org-provide-todo-statistics t)
  9194. (or (member kwd org-done-keywords)))
  9195. (and (listp org-provide-todo-statistics)
  9196. (stringp (car org-provide-todo-statistics))
  9197. (or (member kwd org-provide-todo-statistics)
  9198. (member kwd org-done-keywords)))
  9199. (and (listp org-provide-todo-statistics)
  9200. (listp (car org-provide-todo-statistics))
  9201. (or (member kwd (car org-provide-todo-statistics))
  9202. (and (member kwd org-done-keywords)
  9203. (member kwd (cadr org-provide-todo-statistics))))))
  9204. (setq cnt-all (1+ cnt-all))
  9205. (and (eq org-provide-todo-statistics t)
  9206. kwd
  9207. (setq cnt-all (1+ cnt-all))))
  9208. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  9209. (member kwd org-done-keywords))
  9210. (and (listp org-provide-todo-statistics)
  9211. (listp (car org-provide-todo-statistics))
  9212. (member kwd org-done-keywords)
  9213. (member kwd (cadr org-provide-todo-statistics)))
  9214. (and (listp org-provide-todo-statistics)
  9215. (stringp (car org-provide-todo-statistics))
  9216. (member kwd org-done-keywords)))
  9217. (setq cnt-done (1+ cnt-done)))
  9218. (outline-next-heading)))
  9219. (setq new
  9220. (if is-percent
  9221. (format "[%d%%]" (floor (* 100.0 cnt-done)
  9222. (max 1 cnt-all)))
  9223. (format "[%d/%d]" cnt-done cnt-all))
  9224. ndel (- (match-end 0) checkbox-beg))
  9225. (goto-char checkbox-beg)
  9226. (insert new)
  9227. (delete-region (point) (+ (point) ndel))
  9228. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  9229. (when cookie-present
  9230. (run-hook-with-args 'org-after-todo-statistics-hook
  9231. cnt-done (- cnt-all cnt-done))))))
  9232. (run-hooks 'org-todo-statistics-hook)))
  9233. (defvar org-after-todo-statistics-hook nil
  9234. "Hook that is called after a TODO statistics cookie has been updated.
  9235. Each function is called with two arguments: the number of not-done entries
  9236. and the number of done entries.
  9237. For example, the following function, when added to this hook, will switch
  9238. an entry to DONE when all children are done, and back to TODO when new
  9239. entries are set to a TODO status. Note that this hook is only called
  9240. when there is a statistics cookie in the headline!
  9241. (defun org-summary-todo (n-done n-not-done)
  9242. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  9243. (let (org-log-done org-log-states) ; turn off logging
  9244. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))")
  9245. (defvar org-todo-statistics-hook nil
  9246. "Hook that is run whenever Org thinks TODO statistics should be updated.
  9247. This hook runs even if there is no statistics cookie present, in which case
  9248. `org-after-todo-statistics-hook' would not run.")
  9249. (defun org-todo-trigger-tag-changes (state)
  9250. "Apply the changes defined in `org-todo-state-tags-triggers'."
  9251. (let ((l org-todo-state-tags-triggers)
  9252. changes)
  9253. (when (or (not state) (equal state ""))
  9254. (setq changes (append changes (cdr (assoc "" l)))))
  9255. (when (and (stringp state) (> (length state) 0))
  9256. (setq changes (append changes (cdr (assoc state l)))))
  9257. (when (member state org-not-done-keywords)
  9258. (setq changes (append changes (cdr (assq 'todo l)))))
  9259. (when (member state org-done-keywords)
  9260. (setq changes (append changes (cdr (assq 'done l)))))
  9261. (dolist (c changes)
  9262. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  9263. (defun org-local-logging (value)
  9264. "Get logging settings from a property VALUE."
  9265. ;; Directly set the variables, they are already local.
  9266. (setq org-log-done nil
  9267. org-log-repeat nil
  9268. org-todo-log-states nil)
  9269. (dolist (w (split-string value))
  9270. (let (a)
  9271. (cond
  9272. ((setq a (assoc w org-startup-options))
  9273. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  9274. (set (nth 1 a) (nth 2 a))))
  9275. ((setq a (org-extract-log-state-settings w))
  9276. (and (member (car a) org-todo-keywords-1)
  9277. (push a org-todo-log-states)))))))
  9278. (defun org-get-todo-sequence-head (kwd)
  9279. "Return the head of the TODO sequence to which KWD belongs.
  9280. If KWD is not set, check if there is a text property remembering the
  9281. right sequence."
  9282. (let (p)
  9283. (cond
  9284. ((not kwd)
  9285. (or (get-text-property (point-at-bol) 'org-todo-head)
  9286. (progn
  9287. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  9288. nil (point-at-eol)))
  9289. (get-text-property p 'org-todo-head))))
  9290. ((not (member kwd org-todo-keywords-1))
  9291. (car org-todo-keywords-1))
  9292. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  9293. (defun org-fast-todo-selection (&optional current-state)
  9294. "Fast TODO keyword selection with single keys.
  9295. Returns the new TODO keyword, or nil if no state change should occur.
  9296. When CURRENT-STATE is given and selection letters are not unique globally,
  9297. prefer a state in the current sequence over on in another sequence."
  9298. (let* ((fulltable org-todo-key-alist)
  9299. (head (org-get-todo-sequence-head current-state))
  9300. (done-keywords org-done-keywords) ;; needed for the faces.
  9301. (maxlen (apply 'max (mapcar
  9302. (lambda (x)
  9303. (if (stringp (car x)) (string-width (car x)) 0))
  9304. fulltable)))
  9305. (expert (equal org-use-fast-todo-selection 'expert))
  9306. (prompt "")
  9307. (fwidth (+ maxlen 3 1 3))
  9308. (ncol (/ (- (window-width) 4) fwidth))
  9309. tg cnt e c tbl subtable
  9310. groups ingroup in-current-sequence)
  9311. (save-excursion
  9312. (save-window-excursion
  9313. (if expert
  9314. (set-buffer (get-buffer-create " *Org todo*"))
  9315. (delete-other-windows)
  9316. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org todo*"))
  9317. (org-switch-to-buffer-other-window " *Org todo*"))
  9318. (erase-buffer)
  9319. (setq-local org-done-keywords done-keywords)
  9320. (setq tbl fulltable cnt 0)
  9321. (while (setq e (pop tbl))
  9322. (cond
  9323. ((equal e '(:startgroup))
  9324. (push '() groups) (setq ingroup t)
  9325. (unless (= cnt 0)
  9326. (setq cnt 0)
  9327. (insert "\n"))
  9328. (setq prompt (concat prompt "{"))
  9329. (insert "{ "))
  9330. ((equal e '(:endgroup))
  9331. (setq ingroup nil cnt 0 in-current-sequence nil)
  9332. (setq prompt (concat prompt "}"))
  9333. (insert "}\n"))
  9334. ((equal e '(:newline))
  9335. (unless (= cnt 0)
  9336. (setq cnt 0)
  9337. (insert "\n")
  9338. (setq e (car tbl))
  9339. (while (equal (car tbl) '(:newline))
  9340. (insert "\n")
  9341. (setq tbl (cdr tbl)))))
  9342. (t
  9343. (setq tg (car e) c (cdr e))
  9344. (if (equal tg head) (setq in-current-sequence t))
  9345. (when ingroup (push tg (car groups)))
  9346. (when in-current-sequence (push e subtable))
  9347. (setq tg (org-add-props tg nil 'face
  9348. (org-get-todo-face tg)))
  9349. (when (and (= cnt 0) (not ingroup)) (insert " "))
  9350. (setq prompt (concat prompt "[" (char-to-string c) "] " tg " "))
  9351. (insert "[" c "] " tg (make-string
  9352. (- fwidth 4 (length tg)) ?\ ))
  9353. (when (and (= (setq cnt (1+ cnt)) ncol)
  9354. ;; Avoid lines with just a closing delimiter.
  9355. (not (equal (car tbl) '(:endgroup))))
  9356. (insert "\n")
  9357. (when ingroup (insert " "))
  9358. (setq cnt 0)))))
  9359. (insert "\n")
  9360. (goto-char (point-min))
  9361. (unless expert (org-fit-window-to-buffer))
  9362. (message (concat "[a-z..]:Set [SPC]:clear"
  9363. (if expert (concat "\n" prompt) "")))
  9364. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  9365. (setq subtable (nreverse subtable))
  9366. (cond
  9367. ((or (= c ?\C-g)
  9368. (and (= c ?q) (not (rassoc c fulltable))))
  9369. (setq quit-flag t))
  9370. ((= c ?\ ) nil)
  9371. ((setq e (or (rassoc c subtable) (rassoc c fulltable))
  9372. tg (car e))
  9373. tg)
  9374. (t (setq quit-flag t)))))))
  9375. (defun org-entry-is-todo-p ()
  9376. (member (org-get-todo-state) org-not-done-keywords))
  9377. (defun org-entry-is-done-p ()
  9378. (member (org-get-todo-state) org-done-keywords))
  9379. (defun org-get-todo-state ()
  9380. "Return the TODO keyword of the current subtree."
  9381. (save-excursion
  9382. (org-back-to-heading t)
  9383. (and (let ((case-fold-search nil))
  9384. (looking-at org-todo-line-regexp))
  9385. (match-end 2)
  9386. (match-string 2))))
  9387. (defun org-at-date-range-p (&optional inactive-ok)
  9388. "Non-nil if point is inside a date range.
  9389. When optional argument INACTIVE-OK is non-nil, also consider
  9390. inactive time ranges.
  9391. When this function returns a non-nil value, match data is set
  9392. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  9393. on INACTIVE-OK."
  9394. (interactive)
  9395. (save-excursion
  9396. (catch 'exit
  9397. (let ((pos (point)))
  9398. (skip-chars-backward "^[<\r\n")
  9399. (skip-chars-backward "<[")
  9400. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  9401. (>= (match-end 0) pos)
  9402. (throw 'exit t))
  9403. (skip-chars-backward "^<[\r\n")
  9404. (skip-chars-backward "<[")
  9405. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  9406. (>= (match-end 0) pos)
  9407. (throw 'exit t)))
  9408. nil)))
  9409. (defun org-get-repeat (&optional timestamp)
  9410. "Check if there is a time-stamp with repeater in this entry.
  9411. Return the repeater, as a string, or nil. Also return nil when
  9412. this function is called before first heading.
  9413. When optional argument TIMESTAMP is a string, extract the
  9414. repeater from there instead."
  9415. (save-match-data
  9416. (cond
  9417. (timestamp
  9418. (and (string-match org-repeat-re timestamp)
  9419. (match-string-no-properties 1 timestamp)))
  9420. ((org-before-first-heading-p) nil)
  9421. (t
  9422. (save-excursion
  9423. (org-back-to-heading t)
  9424. (let ((end (org-entry-end-position)))
  9425. (catch :repeat
  9426. (while (re-search-forward org-repeat-re end t)
  9427. (when (save-match-data (org-at-timestamp-p 'agenda))
  9428. (throw :repeat (match-string-no-properties 1)))))))))))
  9429. (defvar org-last-changed-timestamp)
  9430. (defvar org-last-inserted-timestamp)
  9431. (defvar org-log-post-message)
  9432. (defvar org-log-note-purpose)
  9433. (defvar org-log-note-how nil)
  9434. (defvar org-log-note-extra)
  9435. (defvar org-log-setup nil)
  9436. (defun org-auto-repeat-maybe (done-word)
  9437. "Check if the current headline contains a repeated time-stamp.
  9438. If yes, set TODO state back to what it was and change the base date
  9439. of repeating deadline/scheduled time stamps to new date.
  9440. This function is run automatically after each state change to a DONE state."
  9441. (let* ((repeat (org-get-repeat))
  9442. (aa (assoc org-last-state org-todo-kwd-alist))
  9443. (interpret (nth 1 aa))
  9444. (head (nth 2 aa))
  9445. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  9446. (msg "Entry repeats: ")
  9447. (org-log-done nil)
  9448. (org-todo-log-states nil)
  9449. (end (copy-marker (org-entry-end-position))))
  9450. (when (and repeat (not (= 0 (string-to-number (substring repeat 1)))))
  9451. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  9452. (let ((to-state
  9453. (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  9454. (and (stringp org-todo-repeat-to-state)
  9455. org-todo-repeat-to-state)
  9456. (and org-todo-repeat-to-state org-last-state))))
  9457. (org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
  9458. to-state)
  9459. ((eq interpret 'type) org-last-state)
  9460. (head)
  9461. (t 'none))))
  9462. (org-back-to-heading t)
  9463. (org-add-planning-info nil nil 'closed)
  9464. ;; When `org-log-repeat' is non-nil or entry contains
  9465. ;; a clock, set LAST_REPEAT property.
  9466. (when (or org-log-repeat
  9467. (catch :clock
  9468. (save-excursion
  9469. (while (re-search-forward org-clock-line-re end t)
  9470. (when (org-at-clock-log-p) (throw :clock t))))))
  9471. (org-entry-put nil "LAST_REPEAT" (format-time-string
  9472. (org-time-stamp-format t t))))
  9473. (when org-log-repeat
  9474. (if org-log-setup
  9475. ;; We are already setup for some record.
  9476. (when (eq org-log-repeat 'note)
  9477. ;; Make sure we take a note, not only a time stamp.
  9478. (setq org-log-note-how 'note))
  9479. ;; Set up for taking a record.
  9480. (org-add-log-setup 'state
  9481. (or done-word (car org-done-keywords))
  9482. org-last-state
  9483. org-log-repeat)))
  9484. ;; Time-stamps without a repeater are usually skipped. However,
  9485. ;; a SCHEDULED time-stamp without one is removed, as they are no
  9486. ;; longer relevant.
  9487. (save-excursion
  9488. (let ((scheduled (org-entry-get (point) "SCHEDULED")))
  9489. (when (and scheduled (not (string-match-p org-repeat-re scheduled)))
  9490. (org-remove-timestamp-with-keyword org-scheduled-string))))
  9491. ;; Update every time-stamp with a repeater in the entry.
  9492. (let ((planning-re (regexp-opt
  9493. (list org-scheduled-string org-deadline-string))))
  9494. (while (re-search-forward org-repeat-re end t)
  9495. (let* ((ts (match-string 0))
  9496. (type (if (not (org-at-planning-p)) "Plain:"
  9497. (save-excursion
  9498. (re-search-backward
  9499. planning-re (line-beginning-position) t)
  9500. (match-string 0)))))
  9501. (when (and (org-at-timestamp-p 'agenda)
  9502. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  9503. (let ((n (string-to-number (match-string 2 ts)))
  9504. (what (match-string 3 ts)))
  9505. (when (equal what "w") (setq n (* n 7) what "d"))
  9506. (when (and (equal what "h")
  9507. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  9508. ts)))
  9509. (user-error
  9510. "Cannot repeat in %d hour(s) because no hour has been set"
  9511. n))
  9512. ;; Preparation, see if we need to modify the start
  9513. ;; date for the change.
  9514. (when (match-end 1)
  9515. (let ((time (save-match-data (org-time-string-to-time ts)))
  9516. (repeater-type (match-string 1 ts)))
  9517. (cond
  9518. ((equal "." repeater-type)
  9519. ;; Shift starting date to today, or now if
  9520. ;; repeater is by hours.
  9521. (if (equal what "h")
  9522. (org-timestamp-change
  9523. (floor (- (org-time-stamp-to-now ts t)) 60) 'minute)
  9524. (org-timestamp-change
  9525. (- (org-today) (time-to-days time)) 'day)))
  9526. ((equal "+" repeater-type)
  9527. (let ((nshiftmax 10)
  9528. (nshift 0))
  9529. (while (or (= nshift 0)
  9530. (not (time-less-p nil time)))
  9531. (when (= nshiftmax (cl-incf nshift))
  9532. (or (y-or-n-p
  9533. (format "%d repeater intervals were not \
  9534. enough to shift date past today. Continue? "
  9535. nshift))
  9536. (user-error "Abort")))
  9537. (org-timestamp-change n (cdr (assoc what whata)))
  9538. (org-in-regexp org-ts-regexp3)
  9539. (setq ts (match-string 1))
  9540. (setq time
  9541. (save-match-data
  9542. (org-time-string-to-time ts)))))
  9543. (org-timestamp-change (- n) (cdr (assoc what whata)))
  9544. ;; Rematch, so that we have everything in place
  9545. ;; for the real shift.
  9546. (org-in-regexp org-ts-regexp3)
  9547. (setq ts (match-string 1))
  9548. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  9549. ts)))))
  9550. (save-excursion
  9551. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  9552. (setq msg
  9553. (concat msg type " " org-last-changed-timestamp " ")))))))
  9554. (run-hooks 'org-todo-repeat-hook)
  9555. (setq org-log-post-message msg)
  9556. (message msg))))
  9557. (defun org-show-todo-tree (arg)
  9558. "Make a compact tree which shows all headlines marked with TODO.
  9559. The tree will show the lines where the regexp matches, and all higher
  9560. headlines above the match.
  9561. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  9562. With a numeric prefix N, construct a sparse tree for the Nth element
  9563. of `org-todo-keywords-1'."
  9564. (interactive "P")
  9565. (let ((case-fold-search nil)
  9566. (kwd-re
  9567. (cond ((null arg) (concat org-not-done-regexp "\\s-"))
  9568. ((equal arg '(4))
  9569. (let ((kwd
  9570. (completing-read "Keyword (or KWD1|KWD2|...): "
  9571. (mapcar #'list org-todo-keywords-1))))
  9572. (concat "\\("
  9573. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  9574. "\\)\\>")))
  9575. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  9576. (regexp-quote (nth (1- (prefix-numeric-value arg))
  9577. org-todo-keywords-1)))
  9578. (t (user-error "Invalid prefix argument: %s" arg)))))
  9579. (message "%d TODO entries found"
  9580. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  9581. (defun org--deadline-or-schedule (arg type time)
  9582. "Insert DEADLINE or SCHEDULE information in current entry.
  9583. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  9584. `org-schedule' for information about ARG and TIME arguments."
  9585. (let* ((deadline? (eq type 'deadline))
  9586. (keyword (if deadline? org-deadline-string org-scheduled-string))
  9587. (log (if deadline? org-log-redeadline org-log-reschedule))
  9588. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  9589. (old-date-time (and old-date (org-time-string-to-time old-date)))
  9590. ;; Save repeater cookie from either TIME or current scheduled
  9591. ;; time stamp. We are going to insert it back at the end of
  9592. ;; the process.
  9593. (repeater (or (and (org-string-nw-p time)
  9594. ;; We use `org-repeat-re' because we need
  9595. ;; to tell the difference between a real
  9596. ;; repeater and a time delta, e.g. "+2d".
  9597. (string-match org-repeat-re time)
  9598. (match-string 1 time))
  9599. (and (org-string-nw-p old-date)
  9600. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  9601. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  9602. old-date)
  9603. (match-string 1 old-date)))))
  9604. (pcase arg
  9605. (`(4)
  9606. (if (not old-date)
  9607. (message (if deadline? "Entry had no deadline to remove"
  9608. "Entry was not scheduled"))
  9609. (when (and old-date log)
  9610. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  9611. nil old-date log))
  9612. (org-remove-timestamp-with-keyword keyword)
  9613. (message (if deadline? "Entry no longer has a deadline."
  9614. "Entry is no longer scheduled."))))
  9615. (`(16)
  9616. (save-excursion
  9617. (org-back-to-heading t)
  9618. (let ((regexp (if deadline? org-deadline-time-regexp
  9619. org-scheduled-time-regexp)))
  9620. (if (not (re-search-forward regexp (line-end-position 2) t))
  9621. (user-error (if deadline? "No deadline information to update"
  9622. "No scheduled information to update"))
  9623. (let* ((rpl0 (match-string 1))
  9624. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  9625. (msg (if deadline? "Warn starting from" "Delay until")))
  9626. (replace-match
  9627. (concat keyword
  9628. " <" rpl
  9629. (format " -%dd"
  9630. (abs (- (time-to-days
  9631. (save-match-data
  9632. (org-read-date
  9633. nil t nil msg old-date-time)))
  9634. (time-to-days old-date-time))))
  9635. ">") t t))))))
  9636. (_
  9637. (org-add-planning-info type time 'closed)
  9638. (when (and old-date
  9639. log
  9640. (not (equal old-date org-last-inserted-timestamp)))
  9641. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  9642. org-last-inserted-timestamp
  9643. old-date
  9644. log))
  9645. (when repeater
  9646. (save-excursion
  9647. (org-back-to-heading t)
  9648. (when (re-search-forward
  9649. (concat keyword " " org-last-inserted-timestamp)
  9650. (line-end-position 2)
  9651. t)
  9652. (goto-char (1- (match-end 0)))
  9653. (insert " " repeater)
  9654. (setq org-last-inserted-timestamp
  9655. (concat (substring org-last-inserted-timestamp 0 -1)
  9656. " " repeater
  9657. (substring org-last-inserted-timestamp -1))))))
  9658. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  9659. org-last-inserted-timestamp)))))
  9660. (defun org-deadline (arg &optional time)
  9661. "Insert a \"DEADLINE:\" string with a timestamp to make a deadline.
  9662. When called interactively, this command pops up the Emacs calendar to let
  9663. the user select a date.
  9664. With one universal prefix argument, remove any deadline from the item.
  9665. With two universal prefix arguments, prompt for a warning delay.
  9666. With argument TIME, set the deadline at the corresponding date. TIME
  9667. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9668. (interactive "P")
  9669. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9670. (org-map-entries
  9671. (lambda () (org--deadline-or-schedule arg 'deadline time))
  9672. nil
  9673. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9674. 'region-start-level
  9675. 'region)
  9676. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9677. (org--deadline-or-schedule arg 'deadline time)))
  9678. (defun org-schedule (arg &optional time)
  9679. "Insert a \"SCHEDULED:\" string with a timestamp to schedule an item.
  9680. When called interactively, this command pops up the Emacs calendar to let
  9681. the user select a date.
  9682. With one universal prefix argument, remove any scheduling date from the item.
  9683. With two universal prefix arguments, prompt for a delay cookie.
  9684. With argument TIME, scheduled at the corresponding date. TIME can
  9685. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9686. (interactive "P")
  9687. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9688. (org-map-entries
  9689. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  9690. nil
  9691. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9692. 'region-start-level
  9693. 'region)
  9694. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9695. (org--deadline-or-schedule arg 'scheduled time)))
  9696. (defun org-get-scheduled-time (pom &optional inherit)
  9697. "Get the scheduled time as a time tuple, of a format suitable
  9698. for calling org-schedule with, or if there is no scheduling,
  9699. returns nil."
  9700. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  9701. (when time
  9702. (org-time-string-to-time time))))
  9703. (defun org-get-deadline-time (pom &optional inherit)
  9704. "Get the deadline as a time tuple, of a format suitable for
  9705. calling org-deadline with, or if there is no scheduling, returns
  9706. nil."
  9707. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  9708. (when time
  9709. (org-time-string-to-time time))))
  9710. (defun org-remove-timestamp-with-keyword (keyword)
  9711. "Remove all time stamps with KEYWORD in the current entry."
  9712. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  9713. beg)
  9714. (save-excursion
  9715. (org-back-to-heading t)
  9716. (setq beg (point))
  9717. (outline-next-heading)
  9718. (while (re-search-backward re beg t)
  9719. (replace-match "")
  9720. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  9721. (equal (char-before) ?\ ))
  9722. (backward-delete-char 1)
  9723. (when (string-match "^[ \t]*$" (buffer-substring
  9724. (point-at-bol) (point-at-eol)))
  9725. (delete-region (point-at-bol)
  9726. (min (point-max) (1+ (point-at-eol))))))))))
  9727. (defvar org-time-was-given) ; dynamically scoped parameter
  9728. (defvar org-end-time-was-given) ; dynamically scoped parameter
  9729. (defun org-at-planning-p ()
  9730. "Non-nil when point is on a planning info line."
  9731. ;; This is as accurate and faster than `org-element-at-point' since
  9732. ;; planning info location is fixed in the section.
  9733. (or (let ((cached (org-element-at-point nil 'cached)))
  9734. (and cached
  9735. (eq 'planning (org-element-type cached))))
  9736. (org-with-wide-buffer
  9737. (beginning-of-line)
  9738. (and (looking-at-p org-planning-line-re)
  9739. (eq (point)
  9740. (ignore-errors
  9741. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  9742. (org-back-to-heading t)
  9743. (org-with-limited-levels (org-back-to-heading t)))
  9744. (line-beginning-position 2)))))))
  9745. (defun org-add-planning-info (what &optional time &rest remove)
  9746. "Insert new timestamp with keyword in the planning line.
  9747. WHAT indicates what kind of time stamp to add. It is a symbol
  9748. among `closed', `deadline', `scheduled' and nil. TIME indicates
  9749. the time to use. If none is given, the user is prompted for
  9750. a date. REMOVE indicates what kind of entries to remove. An old
  9751. WHAT entry will also be removed."
  9752. (let (org-time-was-given org-end-time-was-given default-time default-input)
  9753. (when (and (memq what '(scheduled deadline))
  9754. (or (not time)
  9755. (and (stringp time)
  9756. (string-match "^[-+]+[0-9]" time))))
  9757. ;; Try to get a default date/time from existing timestamp
  9758. (save-excursion
  9759. (org-back-to-heading t)
  9760. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  9761. (when (re-search-forward (if (eq what 'scheduled)
  9762. org-scheduled-time-regexp
  9763. org-deadline-time-regexp)
  9764. end t)
  9765. (setq ts (match-string 1)
  9766. default-time (org-time-string-to-time ts)
  9767. default-input (and ts (org-get-compact-tod ts)))))))
  9768. (when what
  9769. (setq time
  9770. (if (stringp time)
  9771. ;; This is a string (relative or absolute), set
  9772. ;; proper date.
  9773. (apply #'encode-time
  9774. (org-read-date-analyze
  9775. time default-time (decode-time default-time)))
  9776. ;; If necessary, get the time from the user
  9777. (or time (org-read-date nil 'to-time nil
  9778. (cl-case what
  9779. (deadline "DEADLINE")
  9780. (scheduled "SCHEDULED")
  9781. (otherwise nil))
  9782. default-time default-input)))))
  9783. (org-with-wide-buffer
  9784. (org-back-to-heading t)
  9785. (let ((planning? (save-excursion
  9786. (forward-line)
  9787. (looking-at-p org-planning-line-re))))
  9788. (cond
  9789. (planning?
  9790. (forward-line)
  9791. ;; Move to current indentation.
  9792. (skip-chars-forward " \t")
  9793. ;; Check if we have to remove something.
  9794. (dolist (type (if what (cons what remove) remove))
  9795. (save-excursion
  9796. (when (re-search-forward
  9797. (cl-case type
  9798. (closed org-closed-time-regexp)
  9799. (deadline org-deadline-time-regexp)
  9800. (scheduled org-scheduled-time-regexp)
  9801. (otherwise (error "Invalid planning type: %s" type)))
  9802. (line-end-position)
  9803. t)
  9804. ;; Delete until next keyword or end of line.
  9805. (delete-region
  9806. (match-beginning 0)
  9807. (if (re-search-forward org-keyword-time-not-clock-regexp
  9808. (line-end-position)
  9809. t)
  9810. (match-beginning 0)
  9811. (line-end-position))))))
  9812. ;; If there is nothing more to add and no more keyword is
  9813. ;; left, remove the line completely.
  9814. (if (and (looking-at-p "[ \t]*$") (not what))
  9815. (delete-region (line-end-position 0)
  9816. (line-end-position))
  9817. ;; If we removed last keyword, do not leave trailing white
  9818. ;; space at the end of line.
  9819. (let ((p (point)))
  9820. (save-excursion
  9821. (end-of-line)
  9822. (unless (= (skip-chars-backward " \t" p) 0)
  9823. (delete-region (point) (line-end-position)))))))
  9824. (what
  9825. (end-of-line)
  9826. (insert "\n")
  9827. (when org-adapt-indentation
  9828. (indent-to-column (1+ (org-outline-level)))))
  9829. (t nil)))
  9830. (when what
  9831. ;; Insert planning keyword.
  9832. (insert (cl-case what
  9833. (closed org-closed-string)
  9834. (deadline org-deadline-string)
  9835. (scheduled org-scheduled-string)
  9836. (otherwise (error "Invalid planning type: %s" what)))
  9837. " ")
  9838. ;; Insert associated timestamp.
  9839. (let ((ts (org-insert-time-stamp
  9840. time
  9841. (or org-time-was-given
  9842. (and (eq what 'closed) org-log-done-with-time))
  9843. (eq what 'closed)
  9844. nil nil (list org-end-time-was-given))))
  9845. (unless (eolp) (insert " "))
  9846. ts)))))
  9847. (defvar org-log-note-marker (make-marker)
  9848. "Marker pointing at the entry where the note is to be inserted.")
  9849. (defvar org-log-note-purpose nil)
  9850. (defvar org-log-note-state nil)
  9851. (defvar org-log-note-previous-state nil)
  9852. (defvar org-log-note-extra nil)
  9853. (defvar org-log-note-window-configuration nil)
  9854. (defvar org-log-note-return-to (make-marker))
  9855. (defvar org-log-note-effective-time nil
  9856. "Remembered current time.
  9857. So that dynamically scoped `org-extend-today-until' affects
  9858. timestamps in state change log.")
  9859. (defvar org-log-post-message nil
  9860. "Message to be displayed after a log note has been stored.
  9861. The auto-repeater uses this.")
  9862. (defun org-add-note ()
  9863. "Add a note to the current entry.
  9864. This is done in the same way as adding a state change note."
  9865. (interactive)
  9866. (org-add-log-setup 'note))
  9867. (defun org-log-beginning (&optional create)
  9868. "Return expected start of log notes in current entry.
  9869. When optional argument CREATE is non-nil, the function creates
  9870. a drawer to store notes, if necessary. Returned position ignores
  9871. narrowing."
  9872. (org-with-wide-buffer
  9873. (let ((drawer (org-log-into-drawer)))
  9874. (cond
  9875. (drawer
  9876. (org-end-of-meta-data)
  9877. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  9878. (end (if (org-at-heading-p) (point)
  9879. (save-excursion (outline-next-heading) (point))))
  9880. (case-fold-search t))
  9881. (catch 'exit
  9882. ;; Try to find existing drawer.
  9883. (while (re-search-forward regexp end t)
  9884. (let ((element (org-element-at-point)))
  9885. (when (eq (org-element-type element) 'drawer)
  9886. (let ((cend (org-element-property :contents-end element)))
  9887. (when (and (not org-log-states-order-reversed) cend)
  9888. (goto-char cend)))
  9889. (throw 'exit nil))))
  9890. ;; No drawer found. Create one, if permitted.
  9891. (when create
  9892. (unless (bolp) (insert "\n"))
  9893. (let ((beg (point)))
  9894. (insert ":" drawer ":\n:END:\n")
  9895. (org-indent-region beg (point))
  9896. (org-flag-region (line-end-position -1)
  9897. (1- (point)) t 'outline))
  9898. (end-of-line -1)))))
  9899. (t
  9900. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  9901. (skip-chars-forward " \t\n")
  9902. (beginning-of-line)
  9903. (unless org-log-states-order-reversed
  9904. (org-skip-over-state-notes)
  9905. (skip-chars-backward " \t\n")
  9906. (forward-line)))))
  9907. (if (bolp) (point) (line-beginning-position 2))))
  9908. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  9909. "Set up the post command hook to take a note.
  9910. If this is about to TODO state change, the new state is expected in STATE.
  9911. HOW is an indicator what kind of note should be created.
  9912. EXTRA is additional text that will be inserted into the notes buffer."
  9913. (move-marker org-log-note-marker (point))
  9914. (setq org-log-note-purpose purpose
  9915. org-log-note-state state
  9916. org-log-note-previous-state prev-state
  9917. org-log-note-how how
  9918. org-log-note-extra extra
  9919. org-log-note-effective-time (org-current-effective-time)
  9920. org-log-setup t)
  9921. (add-hook 'post-command-hook 'org-add-log-note 'append))
  9922. (defun org-skip-over-state-notes ()
  9923. "Skip past the list of State notes in an entry."
  9924. (when (ignore-errors (goto-char (org-in-item-p)))
  9925. (let* ((struct (org-list-struct))
  9926. (prevs (org-list-prevs-alist struct))
  9927. (regexp
  9928. (concat "[ \t]*- +"
  9929. (replace-regexp-in-string
  9930. " +" " +"
  9931. (org-replace-escapes
  9932. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  9933. `(("%d" . ,org-ts-regexp-inactive)
  9934. ("%D" . ,org-ts-regexp)
  9935. ("%s" . "\\(?:\"\\S-+\"\\)?")
  9936. ("%S" . "\\(?:\"\\S-+\"\\)?")
  9937. ("%t" . ,org-ts-regexp-inactive)
  9938. ("%T" . ,org-ts-regexp)
  9939. ("%u" . ".*?")
  9940. ("%U" . ".*?")))))))
  9941. (while (looking-at-p regexp)
  9942. (goto-char (or (org-list-get-next-item (point) struct prevs)
  9943. (org-list-get-item-end (point) struct)))))))
  9944. (defun org-add-log-note (&optional _purpose)
  9945. "Pop up a window for taking a note, and add this note later."
  9946. (remove-hook 'post-command-hook 'org-add-log-note)
  9947. (setq org-log-setup nil)
  9948. (setq org-log-note-window-configuration (current-window-configuration))
  9949. (delete-other-windows)
  9950. (move-marker org-log-note-return-to (point))
  9951. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  9952. (goto-char org-log-note-marker)
  9953. (org-switch-to-buffer-other-window "*Org Note*")
  9954. (erase-buffer)
  9955. (if (memq org-log-note-how '(time state))
  9956. (org-store-log-note)
  9957. (let ((org-inhibit-startup t)) (org-mode))
  9958. (insert (format "# Insert note for %s.
  9959. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  9960. (cl-case org-log-note-purpose
  9961. (clock-out "stopped clock")
  9962. (done "closed todo item")
  9963. (reschedule "rescheduling")
  9964. (delschedule "no longer scheduled")
  9965. (redeadline "changing deadline")
  9966. (deldeadline "removing deadline")
  9967. (refile "refiling")
  9968. (note "this entry")
  9969. (state
  9970. (format "state change from \"%s\" to \"%s\""
  9971. (or org-log-note-previous-state "")
  9972. (or org-log-note-state "")))
  9973. (t (error "This should not happen")))))
  9974. (when org-log-note-extra (insert org-log-note-extra))
  9975. (setq-local org-finish-function 'org-store-log-note)
  9976. (run-hooks 'org-log-buffer-setup-hook)))
  9977. (defvar org-note-abort nil) ; dynamically scoped
  9978. (defun org-store-log-note ()
  9979. "Finish taking a log note, and insert it to where it belongs."
  9980. (let ((txt (prog1 (buffer-string)
  9981. (kill-buffer)))
  9982. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  9983. lines)
  9984. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  9985. (setq txt (replace-match "" t t txt)))
  9986. (when (string-match "\\s-+\\'" txt)
  9987. (setq txt (replace-match "" t t txt)))
  9988. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  9989. (when (org-string-nw-p note)
  9990. (setq note
  9991. (org-replace-escapes
  9992. note
  9993. (list (cons "%u" (user-login-name))
  9994. (cons "%U" user-full-name)
  9995. (cons "%t" (format-time-string
  9996. (org-time-stamp-format 'long 'inactive)
  9997. org-log-note-effective-time))
  9998. (cons "%T" (format-time-string
  9999. (org-time-stamp-format 'long nil)
  10000. org-log-note-effective-time))
  10001. (cons "%d" (format-time-string
  10002. (org-time-stamp-format nil 'inactive)
  10003. org-log-note-effective-time))
  10004. (cons "%D" (format-time-string
  10005. (org-time-stamp-format nil nil)
  10006. org-log-note-effective-time))
  10007. (cons "%s" (cond
  10008. ((not org-log-note-state) "")
  10009. ((string-match-p org-ts-regexp
  10010. org-log-note-state)
  10011. (format "\"[%s]\""
  10012. (substring org-log-note-state 1 -1)))
  10013. (t (format "\"%s\"" org-log-note-state))))
  10014. (cons "%S"
  10015. (cond
  10016. ((not org-log-note-previous-state) "")
  10017. ((string-match-p org-ts-regexp
  10018. org-log-note-previous-state)
  10019. (format "\"[%s]\""
  10020. (substring
  10021. org-log-note-previous-state 1 -1)))
  10022. (t (format "\"%s\""
  10023. org-log-note-previous-state)))))))
  10024. (when lines (setq note (concat note " \\\\")))
  10025. (push note lines))
  10026. (when (and lines (not org-note-abort))
  10027. (with-current-buffer (marker-buffer org-log-note-marker)
  10028. (org-with-wide-buffer
  10029. ;; Find location for the new note.
  10030. (goto-char org-log-note-marker)
  10031. (set-marker org-log-note-marker nil)
  10032. ;; Note associated to a clock is to be located right after
  10033. ;; the clock. Do not move point.
  10034. (unless (eq org-log-note-purpose 'clock-out)
  10035. (goto-char (org-log-beginning t)))
  10036. ;; Make sure point is at the beginning of an empty line.
  10037. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  10038. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  10039. ;; In an existing list, add a new item at the top level.
  10040. ;; Otherwise, indent line like a regular one.
  10041. (let ((itemp (org-in-item-p)))
  10042. (if itemp
  10043. (indent-line-to
  10044. (let ((struct (save-excursion
  10045. (goto-char itemp) (org-list-struct))))
  10046. (org-list-get-ind (org-list-get-top-point struct) struct)))
  10047. (org-indent-line)))
  10048. (insert (org-list-bullet-string "-") (pop lines))
  10049. (let ((ind (org-list-item-body-column (line-beginning-position))))
  10050. (dolist (line lines)
  10051. (insert "\n")
  10052. (indent-line-to ind)
  10053. (insert line)))
  10054. (message "Note stored")
  10055. (org-back-to-heading t)))))
  10056. ;; Don't add undo information when called from `org-agenda-todo'.
  10057. (set-window-configuration org-log-note-window-configuration)
  10058. (with-current-buffer (marker-buffer org-log-note-return-to)
  10059. (goto-char org-log-note-return-to))
  10060. (move-marker org-log-note-return-to nil)
  10061. (when org-log-post-message (message "%s" org-log-post-message)))
  10062. (defun org-remove-empty-drawer-at (pos)
  10063. "Remove an empty drawer at position POS.
  10064. POS may also be a marker."
  10065. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  10066. (org-with-wide-buffer
  10067. (goto-char pos)
  10068. (let ((drawer (org-element-at-point)))
  10069. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  10070. (not (org-element-property :contents-begin drawer)))
  10071. (delete-region (org-element-property :begin drawer)
  10072. (progn (goto-char (org-element-property :end drawer))
  10073. (skip-chars-backward " \r\t\n")
  10074. (forward-line)
  10075. (point))))))))
  10076. (defvar org-ts-type nil)
  10077. (defun org-sparse-tree (&optional arg type)
  10078. "Create a sparse tree, prompt for the details.
  10079. This command can create sparse trees. You first need to select the type
  10080. of match used to create the tree:
  10081. t Show all TODO entries.
  10082. T Show entries with a specific TODO keyword.
  10083. m Show entries selected by a tags/property match.
  10084. p Enter a property name and its value (both with completion on existing
  10085. names/values) and show entries with that property.
  10086. r Show entries matching a regular expression (`/' can be used as well).
  10087. b Show deadlines and scheduled items before a date.
  10088. a Show deadlines and scheduled items after a date.
  10089. d Show deadlines due within `org-deadline-warning-days'.
  10090. D Show deadlines and scheduled items between a date range."
  10091. (interactive "P")
  10092. (setq type (or type org-sparse-tree-default-date-type))
  10093. (setq org-ts-type type)
  10094. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  10095. [d]eadlines [b]efore-date [a]fter-date [D]ates range
  10096. [c]ycle through date types: %s"
  10097. (cl-case type
  10098. (all "all timestamps")
  10099. (scheduled "only scheduled")
  10100. (deadline "only deadline")
  10101. (active "only active timestamps")
  10102. (inactive "only inactive timestamps")
  10103. (closed "with a closed time-stamp")
  10104. (otherwise "scheduled/deadline")))
  10105. (let ((answer (read-char-exclusive)))
  10106. (cl-case answer
  10107. (?c
  10108. (org-sparse-tree
  10109. arg
  10110. (cadr
  10111. (memq type '(nil all scheduled deadline active inactive closed)))))
  10112. (?d (call-interactively 'org-check-deadlines))
  10113. (?b (call-interactively 'org-check-before-date))
  10114. (?a (call-interactively 'org-check-after-date))
  10115. (?D (call-interactively 'org-check-dates-range))
  10116. (?t (call-interactively 'org-show-todo-tree))
  10117. (?T (org-show-todo-tree '(4)))
  10118. (?m (call-interactively 'org-match-sparse-tree))
  10119. ((?p ?P)
  10120. (let* ((kwd (completing-read
  10121. "Property: " (mapcar #'list (org-buffer-property-keys))))
  10122. (value (completing-read
  10123. "Value: " (mapcar #'list (org-property-values kwd)))))
  10124. (unless (string-match "\\`{.*}\\'" value)
  10125. (setq value (concat "\"" value "\"")))
  10126. (org-match-sparse-tree arg (concat kwd "=" value))))
  10127. ((?r ?R ?/) (call-interactively 'org-occur))
  10128. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  10129. (defvar-local org-occur-highlights nil
  10130. "List of overlays used for occur matches.")
  10131. (defvar-local org-occur-parameters nil
  10132. "Parameters of the active org-occur calls.
  10133. This is a list, each call to org-occur pushes as cons cell,
  10134. containing the regular expression and the callback, onto the list.
  10135. The list can contain several entries if `org-occur' has been called
  10136. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  10137. will only contain one set of parameters. When the highlights are
  10138. removed (for example with `C-c C-c', or with the next edit (depending
  10139. on `org-remove-highlights-with-change'), this variable is emptied
  10140. as well.")
  10141. (defun org-occur (regexp &optional keep-previous callback)
  10142. "Make a compact tree showing all matches of REGEXP.
  10143. The tree will show the lines where the regexp matches, and any other context
  10144. defined in `org-show-context-detail', which see.
  10145. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  10146. done by a previous call to `org-occur' will be kept, to allow stacking of
  10147. calls to this command.
  10148. Optional argument CALLBACK can be a function of no argument. In this case,
  10149. it is called with point at the end of the match, match data being set
  10150. accordingly. Current match is shown only if the return value is non-nil.
  10151. The function must neither move point nor alter narrowing."
  10152. (interactive "sRegexp: \nP")
  10153. (when (equal regexp "")
  10154. (user-error "Regexp cannot be empty"))
  10155. (unless keep-previous
  10156. (org-remove-occur-highlights nil nil t))
  10157. (push (cons regexp callback) org-occur-parameters)
  10158. (let ((cnt 0))
  10159. (save-excursion
  10160. (goto-char (point-min))
  10161. (when (or (not keep-previous) ; do not want to keep
  10162. (not org-occur-highlights)) ; no previous matches
  10163. ;; hide everything
  10164. (org-overview))
  10165. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  10166. (isearch-no-upper-case-p regexp t)
  10167. org-occur-case-fold-search)))
  10168. (while (re-search-forward regexp nil t)
  10169. (when (or (not callback)
  10170. (save-match-data (funcall callback)))
  10171. (setq cnt (1+ cnt))
  10172. (when org-highlight-sparse-tree-matches
  10173. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  10174. (org-show-context 'occur-tree)))))
  10175. (when org-remove-highlights-with-change
  10176. (add-hook 'before-change-functions 'org-remove-occur-highlights
  10177. nil 'local))
  10178. (unless org-sparse-tree-open-archived-trees
  10179. (org-hide-archived-subtrees (point-min) (point-max)))
  10180. (run-hooks 'org-occur-hook)
  10181. (when (called-interactively-p 'interactive)
  10182. (message "%d match(es) for regexp %s" cnt regexp))
  10183. cnt))
  10184. (defun org-occur-next-match (&optional n _reset)
  10185. "Function for `next-error-function' to find sparse tree matches.
  10186. N is the number of matches to move, when negative move backwards.
  10187. This function always goes back to the starting point when no
  10188. match is found."
  10189. (let* ((limit (if (< n 0) (point-min) (point-max)))
  10190. (search-func (if (< n 0)
  10191. 'previous-single-char-property-change
  10192. 'next-single-char-property-change))
  10193. (n (abs n))
  10194. (pos (point))
  10195. p1)
  10196. (catch 'exit
  10197. (while (setq p1 (funcall search-func (point) 'org-type))
  10198. (when (equal p1 limit)
  10199. (goto-char pos)
  10200. (user-error "No more matches"))
  10201. (when (equal (get-char-property p1 'org-type) 'org-occur)
  10202. (setq n (1- n))
  10203. (when (= n 0)
  10204. (goto-char p1)
  10205. (throw 'exit (point))))
  10206. (goto-char p1))
  10207. (goto-char p1)
  10208. (user-error "No more matches"))))
  10209. (defun org-highlight-new-match (beg end)
  10210. "Highlight from BEG to END and mark the highlight is an occur headline."
  10211. (let ((ov (make-overlay beg end)))
  10212. (overlay-put ov 'face 'secondary-selection)
  10213. (overlay-put ov 'org-type 'org-occur)
  10214. (push ov org-occur-highlights)))
  10215. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  10216. "Remove the occur highlights from the buffer.
  10217. BEG and END are ignored. If NOREMOVE is nil, remove this function
  10218. from the `before-change-functions' in the current buffer."
  10219. (interactive)
  10220. (unless org-inhibit-highlight-removal
  10221. (mapc #'delete-overlay org-occur-highlights)
  10222. (setq org-occur-highlights nil)
  10223. (setq org-occur-parameters nil)
  10224. (unless noremove
  10225. (remove-hook 'before-change-functions
  10226. 'org-remove-occur-highlights 'local))))
  10227. ;;;; Priorities
  10228. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]+\\)\\] ?\\)"
  10229. "Regular expression matching the priority indicator.
  10230. A priority indicator can be e.g. [#A] or [#1].
  10231. This regular expression matches these groups:
  10232. 0 : the whole match, e.g. \"TODO [#A] Hack\"
  10233. 1 : the priority cookie, e.g. \"[#A]\"
  10234. 2 : the value of the priority cookie, e.g. \"A\".")
  10235. (defun org-priority-up ()
  10236. "Increase the priority of the current item."
  10237. (interactive)
  10238. (org-priority 'up))
  10239. (defun org-priority-down ()
  10240. "Decrease the priority of the current item."
  10241. (interactive)
  10242. (org-priority 'down))
  10243. (defun org-priority (&optional action show)
  10244. "Change the priority of an item.
  10245. When called interactively with a `\\[universal-argument]' prefix,
  10246. show the priority in the minibuffer instead of changing it.
  10247. When called programmatically, ACTION can be `set', `up', `down',
  10248. or a character."
  10249. (interactive "P")
  10250. (when show
  10251. ;; Deprecation warning inserted for Org 9.2; once enough time has
  10252. ;; passed the SHOW argument should be removed.
  10253. (warn "`org-priority' called with deprecated SHOW argument"))
  10254. (if (equal action '(4))
  10255. (org-priority-show)
  10256. (unless org-priority-enable-commands
  10257. (user-error "Priority commands are disabled"))
  10258. (setq action (or action 'set))
  10259. (let ((nump (< org-priority-lowest 65))
  10260. current new news have remove)
  10261. (save-excursion
  10262. (org-back-to-heading t)
  10263. (when (looking-at org-priority-regexp)
  10264. (let ((ms (match-string 2)))
  10265. (setq current (org-priority-to-value ms)
  10266. have t)))
  10267. (cond
  10268. ((eq action 'remove)
  10269. (setq remove t new ?\ ))
  10270. ((or (eq action 'set)
  10271. (integerp action))
  10272. (if (not (eq action 'set))
  10273. (setq new action)
  10274. (setq
  10275. new
  10276. (if nump
  10277. (let ((msg (format "Priority %s-%s, SPC to remove: "
  10278. (number-to-string org-priority-highest)
  10279. (number-to-string org-priority-lowest))))
  10280. (if (< 9 org-priority-lowest)
  10281. (string-to-number (read-string msg))
  10282. (message msg)
  10283. (string-to-number (char-to-string (read-char-exclusive)))))
  10284. (progn (message "Priority %c-%c, SPC to remove: "
  10285. org-priority-highest org-priority-lowest)
  10286. (save-match-data
  10287. (setq new (read-char-exclusive)))))))
  10288. (when (and (= (upcase org-priority-highest) org-priority-highest)
  10289. (= (upcase org-priority-lowest) org-priority-lowest))
  10290. (setq new (upcase new)))
  10291. (cond ((equal new ?\s) (setq remove t))
  10292. ((or (< (upcase new) org-priority-highest) (> (upcase new) org-priority-lowest))
  10293. (user-error
  10294. (if nump
  10295. "Priority must be between `%s' and `%s'"
  10296. "Priority must be between `%c' and `%c'")
  10297. org-priority-highest org-priority-lowest))))
  10298. ((eq action 'up)
  10299. (setq new (if have
  10300. (1- current) ; normal cycling
  10301. ;; last priority was empty
  10302. (if (eq last-command this-command)
  10303. org-priority-lowest ; wrap around empty to lowest
  10304. ;; default
  10305. (if org-priority-start-cycle-with-default
  10306. org-priority-default
  10307. (1- org-priority-default))))))
  10308. ((eq action 'down)
  10309. (setq new (if have
  10310. (1+ current) ; normal cycling
  10311. ;; last priority was empty
  10312. (if (eq last-command this-command)
  10313. org-priority-highest ; wrap around empty to highest
  10314. ;; default
  10315. (if org-priority-start-cycle-with-default
  10316. org-priority-default
  10317. (1+ org-priority-default))))))
  10318. (t (user-error "Invalid action")))
  10319. (when (or (< (upcase new) org-priority-highest)
  10320. (> (upcase new) org-priority-lowest))
  10321. (if (and (memq action '(up down))
  10322. (not have) (not (eq last-command this-command)))
  10323. ;; `new' is from default priority
  10324. (error
  10325. "The default can not be set, see `org-priority-default' why")
  10326. ;; normal cycling: `new' is beyond highest/lowest priority
  10327. ;; and is wrapped around to the empty priority
  10328. (setq remove t)))
  10329. ;; Numerical priorities are limited to 64, beyond that number,
  10330. ;; assume the priority cookie is a character.
  10331. (setq news (if (> new 64) (format "%c" new) (format "%s" new)))
  10332. (if have
  10333. (if remove
  10334. (replace-match "" t t nil 1)
  10335. (replace-match news t t nil 2))
  10336. (if remove
  10337. (user-error "No priority cookie found in line")
  10338. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  10339. (if (match-end 2)
  10340. (progn
  10341. (goto-char (match-end 2))
  10342. (insert " [#" news "]"))
  10343. (goto-char (match-beginning 3))
  10344. (insert "[#" news "] "))))
  10345. (org-align-tags))
  10346. (if remove
  10347. (message "Priority removed")
  10348. (message "Priority of current item set to %s" news)))))
  10349. (defalias 'org-show-priority 'org-priority-show)
  10350. (defun org-priority-show ()
  10351. "Show the priority of the current item.
  10352. This priority is composed of the main priority given with the [#A] cookies,
  10353. and by additional input from the age of a schedules or deadline entry."
  10354. (interactive)
  10355. (let ((pri (if (eq major-mode 'org-agenda-mode)
  10356. (org-get-at-bol 'priority)
  10357. (save-excursion
  10358. (save-match-data
  10359. (beginning-of-line)
  10360. (and (looking-at org-heading-regexp)
  10361. (org-get-priority (match-string 0))))))))
  10362. (message "Priority is %d" (if pri pri -1000))))
  10363. (defun org-get-priority (s)
  10364. "Find priority cookie and return priority.
  10365. S is a string against which you can match `org-priority-regexp'.
  10366. If `org-priority-get-priority-function' is set to a custom
  10367. function, use it. Otherwise process S and output the priority
  10368. value, an integer."
  10369. (save-match-data
  10370. (if (functionp org-priority-get-priority-function)
  10371. (funcall org-priority-get-priority-function s)
  10372. (if (not (string-match org-priority-regexp s))
  10373. (* 1000 (- org-priority-lowest org-priority-default))
  10374. (* 1000 (- org-priority-lowest
  10375. (org-priority-to-value (match-string 2 s))))))))
  10376. ;;;; Tags
  10377. (defvar org-agenda-archives-mode)
  10378. (defvar org-map-continue-from nil
  10379. "Position from where mapping should continue.
  10380. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  10381. (defvar org-scanner-tags nil
  10382. "The current tag list while the tags scanner is running.")
  10383. (defvar org-trust-scanner-tags nil
  10384. "Should `org-get-tags' use the tags for the scanner.
  10385. This is for internal dynamical scoping only.
  10386. When this is non-nil, the function `org-get-tags' will return the value
  10387. of `org-scanner-tags' instead of building the list by itself. This
  10388. can lead to large speed-ups when the tags scanner is used in a file with
  10389. many entries, and when the list of tags is retrieved, for example to
  10390. obtain a list of properties. Building the tags list for each entry in such
  10391. a file becomes an N^2 operation - but with this variable set, it scales
  10392. as N.")
  10393. (defvar org--matcher-tags-todo-only nil)
  10394. (defun org-scan-tags (action matcher todo-only &optional start-level)
  10395. "Scan headline tags with inheritance and produce output ACTION.
  10396. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  10397. or `agenda' to produce an entry list for an agenda view. It can also be
  10398. a Lisp form or a function that should be called at each matched headline, in
  10399. this case the return value is a list of all return values from these calls.
  10400. MATCHER is a function accepting three arguments, returning
  10401. a non-nil value whenever a given set of tags qualifies a headline
  10402. for inclusion. See `org-make-tags-matcher' for more information.
  10403. As a special case, it can also be set to t (respectively nil) in
  10404. order to match all (respectively none) headline.
  10405. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  10406. included in the output.
  10407. START-LEVEL can be a string with asterisks, reducing the scope to
  10408. headlines matching this string."
  10409. (require 'org-agenda)
  10410. (let* ((re (concat "^"
  10411. (if start-level
  10412. ;; Get the correct level to match
  10413. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  10414. org-outline-regexp)
  10415. " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
  10416. " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
  10417. (props (list 'face 'default
  10418. 'done-face 'org-agenda-done
  10419. 'undone-face 'default
  10420. 'mouse-face 'highlight
  10421. 'org-not-done-regexp org-not-done-regexp
  10422. 'org-todo-regexp org-todo-regexp
  10423. 'org-complex-heading-regexp org-complex-heading-regexp
  10424. 'help-echo
  10425. (format "mouse-2 or RET jump to Org file %S"
  10426. (abbreviate-file-name
  10427. (or (buffer-file-name (buffer-base-buffer))
  10428. (buffer-name (buffer-base-buffer)))))))
  10429. (org-map-continue-from nil)
  10430. lspos tags tags-list
  10431. (tags-alist (list (cons 0 org-file-tags)))
  10432. (llast 0) rtn rtn1 level category i txt
  10433. todo marker entry priority
  10434. ts-date ts-date-type ts-date-pair)
  10435. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  10436. (setq action (list 'lambda nil action)))
  10437. (save-excursion
  10438. (goto-char (point-min))
  10439. (when (eq action 'sparse-tree)
  10440. (org-overview)
  10441. (org-remove-occur-highlights))
  10442. (if (org-element--cache-active-p)
  10443. (let ((fast-re (concat "^"
  10444. (if start-level
  10445. ;; Get the correct level to match
  10446. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  10447. org-outline-regexp))))
  10448. (org-element-cache-map
  10449. (lambda (el)
  10450. (goto-char (org-element-property :begin el))
  10451. (setq todo (org-element-property :todo-keyword el)
  10452. level (org-element-property :level el)
  10453. category (org-entry-get-with-inheritance "CATEGORY" nil el)
  10454. tags-list (org-get-tags el)
  10455. org-scanner-tags tags-list)
  10456. (when (eq action 'agenda)
  10457. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  10458. ts-date (car ts-date-pair)
  10459. ts-date-type (cdr ts-date-pair)))
  10460. (catch :skip
  10461. (when (and
  10462. ;; eval matcher only when the todo condition is OK
  10463. (and (or (not todo-only) (member todo org-todo-keywords-1))
  10464. (if (functionp matcher)
  10465. (let ((case-fold-search t) (org-trust-scanner-tags t))
  10466. (funcall matcher todo tags-list level))
  10467. matcher))
  10468. ;; Call the skipper, but return t if it does not
  10469. ;; skip, so that the `and' form continues evaluating.
  10470. (progn
  10471. (unless (eq action 'sparse-tree) (org-agenda-skip el))
  10472. t)
  10473. ;; Check if timestamps are deselecting this entry
  10474. (or (not todo-only)
  10475. (and (member todo org-todo-keywords-1)
  10476. (or (not org-agenda-tags-todo-honor-ignore-options)
  10477. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  10478. ;; select this headline
  10479. (cond
  10480. ((eq action 'sparse-tree)
  10481. (and org-highlight-sparse-tree-matches
  10482. (org-get-heading) (match-end 0)
  10483. (org-highlight-new-match
  10484. (match-beginning 1) (match-end 1)))
  10485. (org-show-context 'tags-tree))
  10486. ((eq action 'agenda)
  10487. (setq txt (org-agenda-format-item
  10488. ""
  10489. (concat
  10490. (if (eq org-tags-match-list-sublevels 'indented)
  10491. (make-string (1- level) ?.) "")
  10492. (org-get-heading))
  10493. (make-string level ?\s)
  10494. category
  10495. tags-list)
  10496. priority (org-get-priority txt))
  10497. (goto-char (org-element-property :begin el))
  10498. (setq marker (org-agenda-new-marker))
  10499. (org-add-props txt props
  10500. 'org-marker marker 'org-hd-marker marker 'org-category category
  10501. 'todo-state todo
  10502. 'ts-date ts-date
  10503. 'priority priority
  10504. 'type (concat "tagsmatch" ts-date-type))
  10505. (push txt rtn))
  10506. ((functionp action)
  10507. (setq org-map-continue-from nil)
  10508. (save-excursion
  10509. (setq rtn1 (funcall action))
  10510. (push rtn1 rtn)))
  10511. (t (user-error "Invalid action")))
  10512. ;; if we are to skip sublevels, jump to end of subtree
  10513. (unless org-tags-match-list-sublevels
  10514. (goto-char (1- (org-element-property :end el))))))
  10515. ;; Get the correct position from where to continue
  10516. (when org-map-continue-from
  10517. (goto-char org-map-continue-from))
  10518. ;; Return nil.
  10519. nil)
  10520. :next-re fast-re
  10521. :fail-re fast-re
  10522. :narrow t))
  10523. (while (let (case-fold-search)
  10524. (re-search-forward re nil t))
  10525. (setq org-map-continue-from nil)
  10526. (catch :skip
  10527. ;; Ignore closing parts of inline tasks.
  10528. (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
  10529. (throw :skip t))
  10530. (setq todo (and (match-end 1) (match-string-no-properties 1)))
  10531. (setq tags (and (match-end 4) (org-trim (match-string-no-properties 4))))
  10532. (goto-char (setq lspos (match-beginning 0)))
  10533. (setq level (org-reduced-level (org-outline-level))
  10534. category (org-get-category))
  10535. (when (eq action 'agenda)
  10536. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  10537. ts-date (car ts-date-pair)
  10538. ts-date-type (cdr ts-date-pair)))
  10539. (setq i llast llast level)
  10540. ;; remove tag lists from same and sublevels
  10541. (while (>= i level)
  10542. (when (setq entry (assoc i tags-alist))
  10543. (setq tags-alist (delete entry tags-alist)))
  10544. (setq i (1- i)))
  10545. ;; add the next tags
  10546. (when tags
  10547. (setq tags (org-split-string tags ":")
  10548. tags-alist
  10549. (cons (cons level tags) tags-alist)))
  10550. ;; compile tags for current headline
  10551. (setq tags-list
  10552. (if org-use-tag-inheritance
  10553. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  10554. tags)
  10555. org-scanner-tags tags-list)
  10556. (when org-use-tag-inheritance
  10557. (setcdr (car tags-alist)
  10558. (mapcar (lambda (x)
  10559. (setq x (copy-sequence x))
  10560. (org-add-prop-inherited x))
  10561. (cdar tags-alist))))
  10562. (when (and tags org-use-tag-inheritance
  10563. (or (not (eq t org-use-tag-inheritance))
  10564. org-tags-exclude-from-inheritance))
  10565. ;; Selective inheritance, remove uninherited ones.
  10566. (setcdr (car tags-alist)
  10567. (org-remove-uninherited-tags (cdar tags-alist))))
  10568. (when (and
  10569. ;; eval matcher only when the todo condition is OK
  10570. (and (or (not todo-only) (member todo org-todo-keywords-1))
  10571. (if (functionp matcher)
  10572. (let ((case-fold-search t) (org-trust-scanner-tags t))
  10573. (funcall matcher todo tags-list level))
  10574. matcher))
  10575. ;; Call the skipper, but return t if it does not
  10576. ;; skip, so that the `and' form continues evaluating.
  10577. (progn
  10578. (unless (eq action 'sparse-tree) (org-agenda-skip))
  10579. t)
  10580. ;; Check if timestamps are deselecting this entry
  10581. (or (not todo-only)
  10582. (and (member todo org-todo-keywords-1)
  10583. (or (not org-agenda-tags-todo-honor-ignore-options)
  10584. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  10585. ;; select this headline
  10586. (cond
  10587. ((eq action 'sparse-tree)
  10588. (and org-highlight-sparse-tree-matches
  10589. (org-get-heading) (match-end 0)
  10590. (org-highlight-new-match
  10591. (match-beginning 1) (match-end 1)))
  10592. (org-show-context 'tags-tree))
  10593. ((eq action 'agenda)
  10594. (setq txt (org-agenda-format-item
  10595. ""
  10596. (concat
  10597. (if (eq org-tags-match-list-sublevels 'indented)
  10598. (make-string (1- level) ?.) "")
  10599. (org-get-heading))
  10600. (make-string level ?\s)
  10601. category
  10602. tags-list)
  10603. priority (org-get-priority txt))
  10604. (goto-char lspos)
  10605. (setq marker (org-agenda-new-marker))
  10606. (org-add-props txt props
  10607. 'org-marker marker 'org-hd-marker marker 'org-category category
  10608. 'todo-state todo
  10609. 'ts-date ts-date
  10610. 'priority priority
  10611. 'type (concat "tagsmatch" ts-date-type))
  10612. (push txt rtn))
  10613. ((functionp action)
  10614. (setq org-map-continue-from nil)
  10615. (save-excursion
  10616. (setq rtn1 (funcall action))
  10617. (push rtn1 rtn)))
  10618. (t (user-error "Invalid action")))
  10619. ;; if we are to skip sublevels, jump to end of subtree
  10620. (unless org-tags-match-list-sublevels
  10621. (org-end-of-subtree t)
  10622. (backward-char 1))))
  10623. ;; Get the correct position from where to continue
  10624. (if org-map-continue-from
  10625. (goto-char org-map-continue-from)
  10626. (and (= (point) lspos) (end-of-line 1))))))
  10627. (when (and (eq action 'sparse-tree)
  10628. (not org-sparse-tree-open-archived-trees))
  10629. (org-hide-archived-subtrees (point-min) (point-max)))
  10630. (nreverse rtn)))
  10631. (defun org-remove-uninherited-tags (tags)
  10632. "Remove all tags that are not inherited from the list TAGS."
  10633. (cond
  10634. ((eq org-use-tag-inheritance t)
  10635. (if org-tags-exclude-from-inheritance
  10636. (org-delete-all org-tags-exclude-from-inheritance tags)
  10637. tags))
  10638. ((not org-use-tag-inheritance) nil)
  10639. ((stringp org-use-tag-inheritance)
  10640. (delq nil (mapcar
  10641. (lambda (x)
  10642. (if (and (string-match org-use-tag-inheritance x)
  10643. (not (member x org-tags-exclude-from-inheritance)))
  10644. x nil))
  10645. tags)))
  10646. ((listp org-use-tag-inheritance)
  10647. (delq nil (mapcar
  10648. (lambda (x)
  10649. (if (member x org-use-tag-inheritance) x nil))
  10650. tags)))))
  10651. (defun org-match-sparse-tree (&optional todo-only match)
  10652. "Create a sparse tree according to tags string MATCH.
  10653. MATCH is a string with match syntax. It can contain a selection
  10654. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  10655. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  10656. those. See the manual for details.
  10657. If optional argument TODO-ONLY is non-nil, only select lines that
  10658. are also TODO tasks."
  10659. (interactive "P")
  10660. (org-agenda-prepare-buffers (list (current-buffer)))
  10661. (let ((org--matcher-tags-todo-only todo-only))
  10662. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match t))
  10663. org--matcher-tags-todo-only)))
  10664. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  10665. (defvar org-cached-props nil)
  10666. (defun org-cached-entry-get (pom property)
  10667. (if (or (eq t org-use-property-inheritance)
  10668. (and (stringp org-use-property-inheritance)
  10669. (let ((case-fold-search t))
  10670. (string-match-p org-use-property-inheritance property)))
  10671. (and (listp org-use-property-inheritance)
  10672. (member-ignore-case property org-use-property-inheritance)))
  10673. ;; Caching is not possible, check it directly.
  10674. (org-entry-get pom property 'inherit)
  10675. ;; Get all properties, so we can do complicated checks easily.
  10676. (cdr (assoc-string property
  10677. (or org-cached-props
  10678. (setq org-cached-props (org-entry-properties pom)))
  10679. t))))
  10680. (defun org-global-tags-completion-table (&optional files)
  10681. "Return the list of all tags in all agenda buffer/files.
  10682. Optional FILES argument is a list of files which can be used
  10683. instead of the agenda files."
  10684. (save-excursion
  10685. (org-uniquify
  10686. (delq nil
  10687. (apply #'append
  10688. (mapcar
  10689. (lambda (file)
  10690. (set-buffer (find-file-noselect file))
  10691. (org--tag-add-to-alist
  10692. (org-get-buffer-tags)
  10693. (mapcar (lambda (x)
  10694. (and (stringp (car-safe x))
  10695. (list (car-safe x))))
  10696. org-current-tag-alist)))
  10697. (if (car-safe files) files
  10698. (org-agenda-files))))))))
  10699. (defun org-make-tags-matcher (match &optional only-local-tags)
  10700. "Create the TAGS/TODO matcher form for the selection string MATCH.
  10701. Returns a cons of the selection string MATCH and a function
  10702. implementing the matcher.
  10703. The matcher is to be called at an Org entry, with point on the
  10704. headline, and returns non-nil if the entry matches the selection
  10705. string MATCH. It must be called with three arguments: the TODO
  10706. keyword at the entry (or nil if none), the list of all tags at
  10707. the entry including inherited ones and the reduced level of the
  10708. headline. Additionally, the category of the entry, if any, must
  10709. be specified as the text property `org-category' on the headline.
  10710. This function sets the variable `org--matcher-tags-todo-only' to
  10711. a non-nil value if the matcher restricts matching to TODO
  10712. entries, otherwise it is not touched.
  10713. When ONLY-LOCAL-TAGS is non-nil, ignore the global tag completion
  10714. table, only get buffer tags.
  10715. See also `org-scan-tags'."
  10716. (unless match
  10717. ;; Get a new match request, with completion against the global
  10718. ;; tags table and the local tags in current buffer.
  10719. (let ((org-last-tags-completion-table
  10720. (org--tag-add-to-alist
  10721. (org-get-buffer-tags)
  10722. (unless only-local-tags
  10723. (org-global-tags-completion-table)))))
  10724. (setq match
  10725. (completing-read
  10726. "Match: "
  10727. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  10728. (let ((match0 match)
  10729. (re (concat
  10730. "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
  10731. "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
  10732. "\\([<>=]\\{1,2\\}\\)"
  10733. "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
  10734. "\\|" org-tag-re "\\)"))
  10735. (start 0)
  10736. tagsmatch todomatch tagsmatcher todomatcher)
  10737. ;; Expand group tags.
  10738. (setq match (org-tags-expand match))
  10739. ;; Check if there is a TODO part of this match, which would be the
  10740. ;; part after a "/". To make sure that this slash is not part of
  10741. ;; a property value to be matched against, we also check that
  10742. ;; there is no / after that slash. First, find the last slash.
  10743. (let ((s 0))
  10744. (while (string-match "/+" match s)
  10745. (setq start (match-beginning 0))
  10746. (setq s (match-end 0))))
  10747. (if (and (string-match "/+" match start)
  10748. (not (string-match-p "\"" match start)))
  10749. ;; Match contains also a TODO-matching request.
  10750. (progn
  10751. (setq tagsmatch (substring match 0 (match-beginning 0)))
  10752. (setq todomatch (substring match (match-end 0)))
  10753. (when (string-prefix-p "!" todomatch)
  10754. (setq org--matcher-tags-todo-only t)
  10755. (setq todomatch (substring todomatch 1)))
  10756. (when (string-match "\\`\\s-*\\'" todomatch)
  10757. (setq todomatch nil)))
  10758. ;; Only matching tags.
  10759. (setq tagsmatch match)
  10760. (setq todomatch nil))
  10761. ;; Make the tags matcher.
  10762. (when (org-string-nw-p tagsmatch)
  10763. (let ((orlist nil)
  10764. (orterms (org-split-string tagsmatch "|"))
  10765. term)
  10766. (while (setq term (pop orterms))
  10767. (while (and (equal (substring term -1) "\\") orterms)
  10768. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  10769. (while (string-match re term)
  10770. (let* ((rest (substring term (match-end 0)))
  10771. (minus (and (match-end 1)
  10772. (equal (match-string 1 term) "-")))
  10773. (tag (save-match-data
  10774. (replace-regexp-in-string
  10775. "\\\\-" "-" (match-string 2 term))))
  10776. (regexp (eq (string-to-char tag) ?{))
  10777. (levelp (match-end 4))
  10778. (propp (match-end 5))
  10779. (mm
  10780. (cond
  10781. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  10782. (levelp
  10783. `(,(org-op-to-function (match-string 3 term))
  10784. level
  10785. ,(string-to-number (match-string 4 term))))
  10786. (propp
  10787. (let* ((gv (pcase (upcase (match-string 5 term))
  10788. ("CATEGORY"
  10789. '(org-get-category (point)))
  10790. ("TODO" 'todo)
  10791. (p `(org-cached-entry-get nil ,p))))
  10792. (pv (match-string 7 term))
  10793. (regexp (eq (string-to-char pv) ?{))
  10794. (strp (eq (string-to-char pv) ?\"))
  10795. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  10796. (po (org-op-to-function (match-string 6 term)
  10797. (if timep 'time strp))))
  10798. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  10799. (when timep (setq pv (org-matcher-time pv)))
  10800. (cond ((and regexp (eq po '/=))
  10801. `(not (string-match ,pv (or ,gv ""))))
  10802. (regexp `(string-match ,pv (or ,gv "")))
  10803. (strp `(,po (or ,gv "") ,pv))
  10804. (t
  10805. `(,po
  10806. (string-to-number (or ,gv ""))
  10807. ,(string-to-number pv))))))
  10808. (t `(member ,tag tags-list)))))
  10809. (push (if minus `(not ,mm) mm) tagsmatcher)
  10810. (setq term rest)))
  10811. (push `(and ,@tagsmatcher) orlist)
  10812. (setq tagsmatcher nil))
  10813. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  10814. ;; Make the TODO matcher.
  10815. (when (org-string-nw-p todomatch)
  10816. (let ((orlist nil))
  10817. (dolist (term (org-split-string todomatch "|"))
  10818. (while (string-match re term)
  10819. (let* ((minus (and (match-end 1)
  10820. (equal (match-string 1 term) "-")))
  10821. (kwd (match-string 2 term))
  10822. (regexp (eq (string-to-char kwd) ?{))
  10823. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  10824. `(equal todo ,kwd))))
  10825. (push (if minus `(not ,mm) mm) todomatcher))
  10826. (setq term (substring term (match-end 0))))
  10827. (push (if (> (length todomatcher) 1)
  10828. (cons 'and todomatcher)
  10829. (car todomatcher))
  10830. orlist)
  10831. (setq todomatcher nil))
  10832. (setq todomatcher (cons 'or orlist))))
  10833. ;; Return the string and function of the matcher. If no
  10834. ;; tags-specific or todo-specific matcher exists, match
  10835. ;; everything.
  10836. (let ((matcher (if (and tagsmatcher todomatcher)
  10837. `(and ,tagsmatcher ,todomatcher)
  10838. (or tagsmatcher todomatcher t))))
  10839. (when org--matcher-tags-todo-only
  10840. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  10841. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  10842. (defun org--tags-expand-group (group tag-groups expanded)
  10843. "Recursively expand all tags in GROUP, according to TAG-GROUPS.
  10844. TAG-GROUPS is the list of groups used for expansion. EXPANDED is
  10845. an accumulator used in recursive calls."
  10846. (dolist (tag group)
  10847. (unless (member tag expanded)
  10848. (let ((group (assoc tag tag-groups)))
  10849. (push tag expanded)
  10850. (when group
  10851. (setq expanded
  10852. (org--tags-expand-group (cdr group) tag-groups expanded))))))
  10853. expanded)
  10854. (defun org-tags-expand (match &optional single-as-list)
  10855. "Expand group tags in MATCH.
  10856. This replaces every group tag in MATCH with a regexp tag search.
  10857. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  10858. will be replaced like this:
  10859. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10860. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10861. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10862. Replacing by a regexp preserves the structure of the match.
  10863. E.g., this expansion
  10864. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  10865. will match anything tagged with \"Lab\" and \"Home\", or tagged
  10866. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"Home\".
  10867. A group tag in MATCH can contain regular expressions of its own.
  10868. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  10869. will be replaced like this:
  10870. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  10871. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  10872. assumed to be a single group tag, and the function will return
  10873. the list of tags in this group."
  10874. (unless (org-string-nw-p match) (error "Invalid match tag: %S" match))
  10875. (let ((tag-groups
  10876. (or org-tag-groups-alist-for-agenda org-tag-groups-alist)))
  10877. (cond
  10878. (single-as-list (org--tags-expand-group (list match) tag-groups nil))
  10879. (org-group-tags
  10880. (let* ((case-fold-search t)
  10881. (tag-syntax org-mode-syntax-table)
  10882. (group-keys (mapcar #'car tag-groups))
  10883. (key-regexp (concat "\\([+-]?\\)" (regexp-opt group-keys 'words)))
  10884. (return-match match))
  10885. ;; Mark regexp-expressions in the match-expression so that we
  10886. ;; do not replace them later on.
  10887. (let ((s 0))
  10888. (while (string-match "{.+?}" return-match s)
  10889. (setq s (match-end 0))
  10890. (add-text-properties
  10891. (match-beginning 0) (match-end 0) '(regexp t) return-match)))
  10892. ;; @ and _ are allowed as word-components in tags.
  10893. (modify-syntax-entry ?@ "w" tag-syntax)
  10894. (modify-syntax-entry ?_ "w" tag-syntax)
  10895. ;; For each tag token found in MATCH, compute a regexp and it
  10896. (with-syntax-table tag-syntax
  10897. (replace-regexp-in-string
  10898. key-regexp
  10899. (lambda (m)
  10900. (if (get-text-property (match-beginning 2) 'regexp m)
  10901. m ;regexp tag: ignore
  10902. (let* ((operator (match-string 1 m))
  10903. (tag-token (let ((tag (match-string 2 m)))
  10904. (list tag)))
  10905. regexp-tags regular-tags)
  10906. ;; Partition tags between regexp and regular tags.
  10907. ;; Remove curly bracket syntax from regexp tags.
  10908. (dolist (tag (org--tags-expand-group tag-token tag-groups nil))
  10909. (save-match-data
  10910. (if (string-match "{\\(.+?\\)}" tag)
  10911. (push (match-string 1 tag) regexp-tags)
  10912. (push tag regular-tags))))
  10913. ;; Replace tag token by the appropriate regexp.
  10914. ;; Regular tags need to be regexp-quoted, whereas
  10915. ;; regexp-tags are inserted as-is.
  10916. (let ((regular (regexp-opt regular-tags))
  10917. (regexp (mapconcat #'identity regexp-tags "\\|")))
  10918. (concat operator
  10919. (cond
  10920. ((null regular-tags) (format "{%s}" regexp))
  10921. ((null regexp-tags) (format "{\\<%s\\>}" regular))
  10922. (t (format "{\\<%s\\>\\|%s}" regular regexp))))))))
  10923. return-match
  10924. t t))))
  10925. (t match))))
  10926. (defun org-op-to-function (op &optional stringp)
  10927. "Turn an operator into the appropriate function."
  10928. (setq op
  10929. (cond
  10930. ((equal op "<" ) '(< org-string< org-time<))
  10931. ((equal op ">" ) '(> org-string> org-time>))
  10932. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  10933. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  10934. ((member op '("=" "==")) '(= string= org-time=))
  10935. ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
  10936. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  10937. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  10938. (defvar org-tags-overlay (make-overlay 1 1))
  10939. (delete-overlay org-tags-overlay)
  10940. (defun org-add-prop-inherited (s)
  10941. (add-text-properties 0 (length s) '(inherited t) s)
  10942. s)
  10943. (defun org-toggle-tag (tag &optional onoff)
  10944. "Toggle the tag TAG for the current line.
  10945. If ONOFF is `on' or `off', don't toggle but set to this state."
  10946. (save-excursion
  10947. (org-back-to-heading t)
  10948. (let ((current
  10949. ;; Reverse the tags list so any new tag is appended to the
  10950. ;; current list of tags.
  10951. (nreverse (org-get-tags nil t)))
  10952. res)
  10953. (pcase onoff
  10954. (`off (setq current (delete tag current)))
  10955. ((or `on (guard (not (member tag current))))
  10956. (setq res t)
  10957. (cl-pushnew tag current :test #'equal))
  10958. (_ (setq current (delete tag current))))
  10959. (org-set-tags (nreverse current))
  10960. res)))
  10961. (defun org--align-tags-here (to-col)
  10962. "Align tags on the current headline to TO-COL.
  10963. Assume point is on a headline. Preserve point when aligning
  10964. tags."
  10965. (when (org-match-line org-tag-line-re)
  10966. (let* ((tags-start (match-beginning 1))
  10967. (blank-start (save-excursion
  10968. (goto-char tags-start)
  10969. (skip-chars-backward " \t")
  10970. (point)))
  10971. (new (max (if (>= to-col 0) to-col
  10972. (- (abs to-col) (string-width (match-string 1))))
  10973. ;; Introduce at least one space after the heading
  10974. ;; or the stars.
  10975. (save-excursion
  10976. (goto-char blank-start)
  10977. (1+ (current-column)))))
  10978. (current
  10979. (save-excursion (goto-char tags-start) (current-column)))
  10980. (origin (point-marker))
  10981. (column (current-column))
  10982. (in-blank? (and (> origin blank-start) (<= origin tags-start))))
  10983. (when (/= new current)
  10984. (delete-region blank-start tags-start)
  10985. (goto-char blank-start)
  10986. (let ((indent-tabs-mode nil)) (indent-to new))
  10987. ;; Try to move back to original position. If point was in the
  10988. ;; blanks before the tags, ORIGIN marker is of no use because
  10989. ;; it now points to BLANK-START. Use COLUMN instead.
  10990. (if in-blank? (org-move-to-column column) (goto-char origin))))))
  10991. (defun org-set-tags-command (&optional arg)
  10992. "Set the tags for the current visible entry.
  10993. When called with `\\[universal-argument]' prefix argument ARG, \
  10994. realign all tags
  10995. in the current buffer.
  10996. When called with `\\[universal-argument] \\[universal-argument]' prefix argument, \
  10997. unconditionally do not
  10998. offer the fast tag selection interface.
  10999. If a region is active, set tags in the region according to the
  11000. setting of `org-loop-over-headlines-in-active-region'.
  11001. This function is for interactive use only;
  11002. in Lisp code use `org-set-tags' instead."
  11003. (interactive "P")
  11004. (let ((org-use-fast-tag-selection
  11005. (unless (equal '(16) arg) org-use-fast-tag-selection)))
  11006. (cond
  11007. ((equal '(4) arg) (org-align-tags t))
  11008. ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11009. (let (org-loop-over-headlines-in-active-region) ; hint: infinite recursion.
  11010. (org-map-entries
  11011. #'org-set-tags-command
  11012. nil
  11013. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11014. 'region-start-level
  11015. 'region)
  11016. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
  11017. (t
  11018. (save-excursion
  11019. (org-back-to-heading)
  11020. (let* ((all-tags (org-get-tags))
  11021. (table (setq org-last-tags-completion-table
  11022. (org--tag-add-to-alist
  11023. (and org-complete-tags-always-offer-all-agenda-tags
  11024. (org-global-tags-completion-table
  11025. (org-agenda-files)))
  11026. (or org-current-tag-alist (org-get-buffer-tags)))))
  11027. (current-tags
  11028. (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
  11029. all-tags))
  11030. (inherited-tags
  11031. (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
  11032. all-tags))
  11033. (tags
  11034. (replace-regexp-in-string
  11035. ;; Ignore all forbidden characters in tags.
  11036. "[^[:alnum:]_@#%]+" ":"
  11037. (if (or (eq t org-use-fast-tag-selection)
  11038. (and org-use-fast-tag-selection
  11039. (delq nil (mapcar #'cdr table))))
  11040. (org-fast-tag-selection
  11041. current-tags
  11042. inherited-tags
  11043. table
  11044. (and org-fast-tag-selection-include-todo org-todo-key-alist))
  11045. (let ((org-add-colon-after-tag-completion (< 1 (length table)))
  11046. (crm-separator "[ \t]*:[ \t]*"))
  11047. (mapconcat #'identity
  11048. (completing-read-multiple
  11049. "Tags: "
  11050. org-last-tags-completion-table
  11051. nil nil (org-make-tag-string current-tags)
  11052. 'org-tags-history)
  11053. ":"))))))
  11054. (org-set-tags tags)))))
  11055. ;; `save-excursion' may not replace the point at the right
  11056. ;; position.
  11057. (when (and (save-excursion (skip-chars-backward "*") (bolp))
  11058. (looking-at-p " "))
  11059. (forward-char))))
  11060. (defun org-align-tags (&optional all)
  11061. "Align tags in current entry.
  11062. When optional argument ALL is non-nil, align all tags in the
  11063. visible part of the buffer."
  11064. (let ((get-indent-column
  11065. (lambda ()
  11066. (let ((offset (if (bound-and-true-p org-indent-mode)
  11067. (* (1- org-indent-indentation-per-level)
  11068. (1- (org-current-level)))
  11069. 0)))
  11070. (+ org-tags-column
  11071. (if (> org-tags-column 0) (- offset) offset))))))
  11072. (if (and (not all) (org-at-heading-p))
  11073. (org--align-tags-here (funcall get-indent-column))
  11074. (save-excursion
  11075. (if all
  11076. (progn
  11077. (goto-char (point-min))
  11078. (while (re-search-forward org-tag-line-re nil t)
  11079. (org--align-tags-here (funcall get-indent-column))))
  11080. (org-back-to-heading t)
  11081. (org--align-tags-here (funcall get-indent-column)))))))
  11082. (defun org-set-tags (tags)
  11083. "Set the tags of the current entry to TAGS, replacing current tags.
  11084. TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
  11085. If TAGS is nil or the empty string, all tags are removed.
  11086. This function assumes point is on a headline."
  11087. (org-with-wide-buffer
  11088. (let ((tags (pcase tags
  11089. ((pred listp) tags)
  11090. ((pred stringp) (split-string (org-trim tags) ":" t))
  11091. (_ (error "Invalid tag specification: %S" tags))))
  11092. (old-tags (org-get-tags nil t))
  11093. (tags-change? nil))
  11094. (when (functionp org-tags-sort-function)
  11095. (setq tags (sort tags org-tags-sort-function)))
  11096. (setq tags-change? (not (equal tags old-tags)))
  11097. (when tags-change?
  11098. ;; Delete previous tags and any trailing white space.
  11099. (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
  11100. (line-end-position)))
  11101. (skip-chars-backward " \t")
  11102. (delete-region (point) (line-end-position))
  11103. ;; Deleting white spaces may break an otherwise empty headline.
  11104. ;; Re-introduce one space in this case.
  11105. (unless (org-at-heading-p) (insert " "))
  11106. (when tags
  11107. (save-excursion (insert " " (org-make-tag-string tags)))
  11108. ;; When text is being inserted on an invisible region
  11109. ;; boundary, it can be inadvertently sucked into
  11110. ;; invisibility.
  11111. (unless (org-invisible-p (line-beginning-position))
  11112. (org-flag-region (point) (line-end-position) nil 'outline))))
  11113. ;; Align tags, if any.
  11114. (when tags (org-align-tags))
  11115. (when tags-change? (run-hooks 'org-after-tags-change-hook)))))
  11116. (defun org-change-tag-in-region (beg end tag off)
  11117. "Add or remove TAG for each entry in the region.
  11118. This works in the agenda, and also in an Org buffer."
  11119. (interactive
  11120. (list (region-beginning) (region-end)
  11121. (let ((org-last-tags-completion-table
  11122. (if (derived-mode-p 'org-mode)
  11123. (org--tag-add-to-alist
  11124. (org-get-buffer-tags)
  11125. (org-global-tags-completion-table))
  11126. (org-global-tags-completion-table))))
  11127. (completing-read
  11128. "Tag: " org-last-tags-completion-table nil nil nil
  11129. 'org-tags-history))
  11130. (progn
  11131. (message "[s]et or [r]emove? ")
  11132. (equal (read-char-exclusive) ?r))))
  11133. (when (fboundp 'deactivate-mark) (deactivate-mark))
  11134. (let ((agendap (equal major-mode 'org-agenda-mode))
  11135. l1 l2 m buf pos newhead (cnt 0))
  11136. (goto-char end)
  11137. (setq l2 (1- (org-current-line)))
  11138. (goto-char beg)
  11139. (setq l1 (org-current-line))
  11140. (cl-loop for l from l1 to l2 do
  11141. (org-goto-line l)
  11142. (setq m (get-text-property (point) 'org-hd-marker))
  11143. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  11144. (and agendap m))
  11145. (setq buf (if agendap (marker-buffer m) (current-buffer))
  11146. pos (if agendap m (point)))
  11147. (with-current-buffer buf
  11148. (save-excursion
  11149. (save-restriction
  11150. (goto-char pos)
  11151. (setq cnt (1+ cnt))
  11152. (org-toggle-tag tag (if off 'off 'on))
  11153. (setq newhead (org-get-heading)))))
  11154. (and agendap (org-agenda-change-all-lines newhead m))))
  11155. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  11156. (defun org-tags-completion-function (string _predicate &optional flag)
  11157. "Complete tag STRING.
  11158. FLAG specifies the type of completion operation to perform. This
  11159. function is passed as a collection function to `completing-read',
  11160. which see."
  11161. (let ((completion-ignore-case nil) ;tags are case-sensitive
  11162. (confirm (lambda (x) (stringp (car x))))
  11163. (prefix ""))
  11164. (when (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  11165. (setq prefix (match-string 1 string))
  11166. (setq string (match-string 2 string)))
  11167. (pcase flag
  11168. (`t (all-completions string org-last-tags-completion-table confirm))
  11169. (`lambda (assoc string org-last-tags-completion-table)) ;exact match?
  11170. (`nil
  11171. (pcase (try-completion string org-last-tags-completion-table confirm)
  11172. ((and completion (pred stringp))
  11173. (concat prefix
  11174. completion
  11175. (if (and org-add-colon-after-tag-completion
  11176. (assoc completion org-last-tags-completion-table))
  11177. ":"
  11178. "")))
  11179. (completion completion)))
  11180. (_ nil))))
  11181. (defun org-fast-tag-insert (kwd tags face &optional end)
  11182. "Insert KWD, and the TAGS, the latter with face FACE.
  11183. Also insert END."
  11184. (insert (format "%-12s" (concat kwd ":"))
  11185. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  11186. (or end "")))
  11187. (defun org-fast-tag-show-exit (flag)
  11188. (save-excursion
  11189. (org-goto-line 3)
  11190. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  11191. (replace-match ""))
  11192. (when flag
  11193. (end-of-line 1)
  11194. (org-move-to-column (- (window-width) 19) t)
  11195. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  11196. (defun org-set-current-tags-overlay (current prefix)
  11197. "Add an overlay to CURRENT tag with PREFIX."
  11198. (let ((s (org-make-tag-string current)))
  11199. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  11200. (org-overlay-display org-tags-overlay (concat prefix s))))
  11201. (defvar org-last-tag-selection-key nil)
  11202. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  11203. "Fast tag selection with single keys.
  11204. CURRENT is the current list of tags in the headline, INHERITED is the
  11205. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  11206. possibly with grouping information. TODO-TABLE is a similar table with
  11207. TODO keywords, should these have keys assigned to them.
  11208. If the keys are nil, a-z are automatically assigned.
  11209. Returns the new tags string, or nil to not change the current settings."
  11210. (let* ((fulltable (append table todo-table))
  11211. (maxlen (if (null fulltable) 0
  11212. (apply #'max
  11213. (mapcar (lambda (x)
  11214. (if (stringp (car x)) (string-width (car x))
  11215. 0))
  11216. fulltable))))
  11217. (buf (current-buffer))
  11218. (expert (eq org-fast-tag-selection-single-key 'expert))
  11219. (tab-tags nil)
  11220. (fwidth (+ maxlen 3 1 3))
  11221. (ncol (/ (- (window-width) 4) fwidth))
  11222. (i-face 'org-done)
  11223. (c-face 'org-todo)
  11224. tg cnt e c char c1 c2 ntable tbl rtn
  11225. ov-start ov-end ov-prefix
  11226. (exit-after-next org-fast-tag-selection-single-key)
  11227. (done-keywords org-done-keywords)
  11228. groups ingroup intaggroup)
  11229. (save-excursion
  11230. (beginning-of-line)
  11231. (if (looking-at org-tag-line-re)
  11232. (setq ov-start (match-beginning 1)
  11233. ov-end (match-end 1)
  11234. ov-prefix "")
  11235. (setq ov-start (1- (point-at-eol))
  11236. ov-end (1+ ov-start))
  11237. (skip-chars-forward "^\n\r")
  11238. (setq ov-prefix
  11239. (concat
  11240. (buffer-substring (1- (point)) (point))
  11241. (if (> (current-column) org-tags-column)
  11242. " "
  11243. (make-string (- org-tags-column (current-column)) ?\ ))))))
  11244. (move-overlay org-tags-overlay ov-start ov-end)
  11245. (save-excursion
  11246. (save-window-excursion
  11247. (if expert
  11248. (set-buffer (get-buffer-create " *Org tags*"))
  11249. (delete-other-windows)
  11250. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  11251. (org-switch-to-buffer-other-window " *Org tags*"))
  11252. (erase-buffer)
  11253. (setq-local org-done-keywords done-keywords)
  11254. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  11255. (org-fast-tag-insert "Current" current c-face "\n\n")
  11256. (org-fast-tag-show-exit exit-after-next)
  11257. (org-set-current-tags-overlay current ov-prefix)
  11258. (setq tbl fulltable char ?a cnt 0)
  11259. (while (setq e (pop tbl))
  11260. (cond
  11261. ((eq (car e) :startgroup)
  11262. (push '() groups) (setq ingroup t)
  11263. (unless (zerop cnt)
  11264. (setq cnt 0)
  11265. (insert "\n"))
  11266. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  11267. ((eq (car e) :endgroup)
  11268. (setq ingroup nil cnt 0)
  11269. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  11270. ((eq (car e) :startgrouptag)
  11271. (setq intaggroup t)
  11272. (unless (zerop cnt)
  11273. (setq cnt 0)
  11274. (insert "\n"))
  11275. (insert "[ "))
  11276. ((eq (car e) :endgrouptag)
  11277. (setq intaggroup nil cnt 0)
  11278. (insert "]\n"))
  11279. ((equal e '(:newline))
  11280. (unless (zerop cnt)
  11281. (setq cnt 0)
  11282. (insert "\n")
  11283. (setq e (car tbl))
  11284. (while (equal (car tbl) '(:newline))
  11285. (insert "\n")
  11286. (setq tbl (cdr tbl)))))
  11287. ((equal e '(:grouptags)) (insert " : "))
  11288. (t
  11289. (setq tg (copy-sequence (car e)) c2 nil)
  11290. (if (cdr e)
  11291. (setq c (cdr e))
  11292. ;; automatically assign a character.
  11293. (setq c1 (string-to-char
  11294. (downcase (substring
  11295. tg (if (= (string-to-char tg) ?@) 1 0)))))
  11296. (if (or (rassoc c1 ntable) (rassoc c1 table))
  11297. (while (or (rassoc char ntable) (rassoc char table))
  11298. (setq char (1+ char)))
  11299. (setq c2 c1))
  11300. (setq c (or c2 char)))
  11301. (when ingroup (push tg (car groups)))
  11302. (setq tg (org-add-props tg nil 'face
  11303. (cond
  11304. ((not (assoc tg table))
  11305. (org-get-todo-face tg))
  11306. ((member tg current) c-face)
  11307. ((member tg inherited) i-face))))
  11308. (when (equal (caar tbl) :grouptags)
  11309. (org-add-props tg nil 'face 'org-tag-group))
  11310. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  11311. (insert "[" c "] " tg (make-string
  11312. (- fwidth 4 (length tg)) ?\ ))
  11313. (push (cons tg c) ntable)
  11314. (when (= (cl-incf cnt) ncol)
  11315. (unless (memq (caar tbl) '(:endgroup :endgrouptag))
  11316. (insert "\n")
  11317. (when (or ingroup intaggroup) (insert " ")))
  11318. (setq cnt 0)))))
  11319. (setq ntable (nreverse ntable))
  11320. (insert "\n")
  11321. (goto-char (point-min))
  11322. (unless expert (org-fit-window-to-buffer))
  11323. (setq rtn
  11324. (catch 'exit
  11325. (while t
  11326. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  11327. (if (not groups) "no " "")
  11328. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  11329. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11330. (setq org-last-tag-selection-key c)
  11331. (cond
  11332. ((= c ?\r) (throw 'exit t))
  11333. ((= c ?!)
  11334. (setq groups (not groups))
  11335. (goto-char (point-min))
  11336. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  11337. ((= c ?\C-c)
  11338. (if (not expert)
  11339. (org-fast-tag-show-exit
  11340. (setq exit-after-next (not exit-after-next)))
  11341. (setq expert nil)
  11342. (delete-other-windows)
  11343. (set-window-buffer (split-window-vertically) " *Org tags*")
  11344. (org-switch-to-buffer-other-window " *Org tags*")
  11345. (org-fit-window-to-buffer)))
  11346. ((or (= c ?\C-g)
  11347. (and (= c ?q) (not (rassoc c ntable))))
  11348. (delete-overlay org-tags-overlay)
  11349. (setq quit-flag t))
  11350. ((= c ?\ )
  11351. (setq current nil)
  11352. (when exit-after-next (setq exit-after-next 'now)))
  11353. ((= c ?\t)
  11354. (condition-case nil
  11355. (unless tab-tags
  11356. (setq tab-tags
  11357. (delq nil
  11358. (mapcar (lambda (x)
  11359. (let ((item (car-safe x)))
  11360. (and (stringp item)
  11361. (list item))))
  11362. (org--tag-add-to-alist
  11363. (with-current-buffer buf
  11364. (org-get-buffer-tags))
  11365. table))))))
  11366. (setq tg (completing-read "Tag: " tab-tags))
  11367. (when (string-match "\\S-" tg)
  11368. (cl-pushnew (list tg) tab-tags :test #'equal)
  11369. (if (member tg current)
  11370. (setq current (delete tg current))
  11371. (push tg current)))
  11372. (when exit-after-next (setq exit-after-next 'now)))
  11373. ((setq e (rassoc c todo-table) tg (car e))
  11374. (with-current-buffer buf
  11375. (save-excursion (org-todo tg)))
  11376. (when exit-after-next (setq exit-after-next 'now)))
  11377. ((setq e (rassoc c ntable) tg (car e))
  11378. (if (member tg current)
  11379. (setq current (delete tg current))
  11380. (cl-loop for g in groups do
  11381. (when (member tg g)
  11382. (dolist (x g) (setq current (delete x current)))))
  11383. (push tg current))
  11384. (when exit-after-next (setq exit-after-next 'now))))
  11385. ;; Create a sorted list
  11386. (setq current
  11387. (sort current
  11388. (lambda (a b)
  11389. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  11390. (when (eq exit-after-next 'now) (throw 'exit t))
  11391. (goto-char (point-min))
  11392. (beginning-of-line 2)
  11393. (delete-region (point) (point-at-eol))
  11394. (org-fast-tag-insert "Current" current c-face)
  11395. (org-set-current-tags-overlay current ov-prefix)
  11396. (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
  11397. (while (re-search-forward tag-re nil t)
  11398. (let ((tag (match-string 1)))
  11399. (add-text-properties
  11400. (match-beginning 1) (match-end 1)
  11401. (list 'face
  11402. (cond
  11403. ((member tag current) c-face)
  11404. ((member tag inherited) i-face)
  11405. (t (get-text-property (match-beginning 1) '
  11406. face))))))))
  11407. (goto-char (point-min)))))
  11408. (delete-overlay org-tags-overlay)
  11409. (if rtn
  11410. (mapconcat 'identity current ":")
  11411. nil)))))
  11412. (defun org-make-tag-string (tags)
  11413. "Return string associated to TAGS.
  11414. TAGS is a list of strings."
  11415. (if (null tags) ""
  11416. (format ":%s:" (mapconcat #'identity tags ":"))))
  11417. (defun org--get-local-tags ()
  11418. "Return list of tags for the current headline.
  11419. Assume point is at the beginning of the headline."
  11420. (let* ((cached (and (org-element--cache-active-p) (org-element-at-point nil 'cached)))
  11421. (cached-tags (org-element-property :tags cached)))
  11422. (if cached
  11423. ;; If we do not wrap result into `cl-copy-list', reference would
  11424. ;; be returned and cache element might be modified directly.
  11425. (cl-copy-list cached-tags)
  11426. ;; Parse tags manually.
  11427. (and (looking-at org-tag-line-re)
  11428. (split-string (match-string-no-properties 2) ":" t)))))
  11429. (defun org-get-tags (&optional pos-or-element local)
  11430. "Get the list of tags specified in the current headline.
  11431. When argument POS-OR-ELEMENT is non-nil, retrieve tags for headline at
  11432. POS.
  11433. According to `org-use-tag-inheritance', tags may be inherited
  11434. from parent headlines, and from the whole document, through
  11435. `org-file-tags'. In this case, the returned list of tags
  11436. contains tags in this order: file tags, tags inherited from
  11437. parent headlines, local tags. If a tag appears multiple times,
  11438. only the most local tag is returned.
  11439. However, when optional argument LOCAL is non-nil, only return
  11440. tags specified at the headline.
  11441. Inherited tags have the `inherited' text property."
  11442. (save-match-data
  11443. (if (and org-trust-scanner-tags
  11444. (or (not pos-or-element) (eq pos-or-element (point)))
  11445. (not local))
  11446. org-scanner-tags
  11447. (org-with-point-at (unless (org-element-type pos-or-element)
  11448. (or pos-or-element (point)))
  11449. (unless (and (not (org-element-type pos-or-element))
  11450. (org-before-first-heading-p))
  11451. (unless (org-element-type pos-or-element) (org-back-to-heading t))
  11452. (let ((ltags (if (org-element-type pos-or-element)
  11453. (org-element-property :tags (org-element-lineage pos-or-element '(headline) t))
  11454. (org--get-local-tags)))
  11455. itags)
  11456. (if (or local (not org-use-tag-inheritance)) ltags
  11457. (let ((cached (and (org-element--cache-active-p)
  11458. (if (org-element-type pos-or-element)
  11459. (org-element-lineage pos-or-element '(headline) t)
  11460. (org-element-at-point nil 'cached)))))
  11461. (if cached
  11462. (while (setq cached (org-element-property :parent cached))
  11463. (setq itags (nconc (mapcar #'org-add-prop-inherited
  11464. ;; If we do not wrap result into `cl-copy-list', reference would
  11465. ;; be returned and cache element might be modified directly.
  11466. (cl-copy-list (org-element-property :tags cached)))
  11467. itags)))
  11468. (while (org-up-heading-safe)
  11469. (setq itags (nconc (mapcar #'org-add-prop-inherited
  11470. (org--get-local-tags))
  11471. itags)))))
  11472. (setq itags (append org-file-tags itags))
  11473. (nreverse
  11474. (delete-dups
  11475. (nreverse (nconc (org-remove-uninherited-tags itags) ltags)))))))))))
  11476. (defun org-get-buffer-tags ()
  11477. "Get a table of all tags used in the buffer, for completion."
  11478. (org-with-point-at 1
  11479. (let (tags)
  11480. (while (re-search-forward org-tag-line-re nil t)
  11481. (setq tags (nconc (split-string (match-string-no-properties 2) ":")
  11482. tags)))
  11483. (mapcar #'list (delete-dups (append org-file-tags tags))))))
  11484. ;;;; The mapping API
  11485. (defvar org-agenda-skip-comment-trees)
  11486. (defvar org-agenda-skip-function)
  11487. (defun org-map-entries (func &optional match scope &rest skip)
  11488. "Call FUNC at each headline selected by MATCH in SCOPE.
  11489. FUNC is a function or a Lisp form. The function will be called without
  11490. arguments, with the cursor positioned at the beginning of the headline.
  11491. The return values of all calls to the function will be collected and
  11492. returned as a list.
  11493. The call to FUNC will be wrapped into a `save-excursion' form, so FUNC
  11494. does not need to preserve point. After evaluation, the cursor will be
  11495. moved to the end of the line (presumably of the headline of the
  11496. processed entry) and search continues from there. Under some
  11497. circumstances, this may not produce the wanted results. For example,
  11498. if you have removed (e.g. archived) the current (sub)tree it could
  11499. mean that the next entry will be skipped entirely. In such cases, you
  11500. can specify the position from where search should continue by making
  11501. FUNC set the variable `org-map-continue-from' to the desired buffer
  11502. position.
  11503. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  11504. Only headlines that are matched by this query will be considered during
  11505. the iteration. When MATCH is nil or t, all headlines will be
  11506. visited by the iteration.
  11507. SCOPE determines the scope of this command. It can be any of:
  11508. nil The current buffer, respecting the restriction if any
  11509. tree The subtree started with the entry at point
  11510. region The entries within the active region, if any
  11511. region-start-level
  11512. The entries within the active region, but only those at
  11513. the same level than the first one.
  11514. file The current buffer, without restriction
  11515. file-with-archives
  11516. The current buffer, and any archives associated with it
  11517. agenda All agenda files
  11518. agenda-with-archives
  11519. All agenda files with any archive files associated with them
  11520. \(file1 file2 ...)
  11521. If this is a list, all files in the list will be scanned
  11522. The remaining args are treated as settings for the skipping facilities of
  11523. the scanner. The following items can be given here:
  11524. archive skip trees with the archive tag
  11525. comment skip trees with the COMMENT keyword
  11526. function or Emacs Lisp form:
  11527. will be used as value for `org-agenda-skip-function', so
  11528. whenever the function returns a position, FUNC will not be
  11529. called for that entry and search will continue from the
  11530. position returned
  11531. If your function needs to retrieve the tags including inherited tags
  11532. at the *current* entry, you can use the value of the variable
  11533. `org-scanner-tags' which will be much faster than getting the value
  11534. with `org-get-tags'. If your function gets properties with
  11535. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  11536. to t around the call to `org-entry-properties' to get the same speedup.
  11537. Note that if your function moves around to retrieve tags and properties at
  11538. a *different* entry, you cannot use these techniques."
  11539. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  11540. (not (org-region-active-p)))
  11541. (let* ((org-agenda-archives-mode nil) ; just to make sure
  11542. (org-agenda-skip-archived-trees (memq 'archive skip))
  11543. (org-agenda-skip-comment-trees (memq 'comment skip))
  11544. (org-agenda-skip-function
  11545. (car (org-delete-all '(comment archive) skip)))
  11546. (org-tags-match-list-sublevels t)
  11547. (start-level (eq scope 'region-start-level))
  11548. matcher res
  11549. org-todo-keywords-for-agenda
  11550. org-done-keywords-for-agenda
  11551. org-todo-keyword-alist-for-agenda
  11552. org-tag-alist-for-agenda
  11553. org--matcher-tags-todo-only)
  11554. (cond
  11555. ((eq match t) (setq matcher t))
  11556. ((eq match nil) (setq matcher t))
  11557. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  11558. (save-excursion
  11559. (save-restriction
  11560. (cond ((eq scope 'tree)
  11561. (org-back-to-heading t)
  11562. (org-narrow-to-subtree)
  11563. (setq scope nil))
  11564. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  11565. (org-region-active-p))
  11566. ;; If needed, set start-level to a string like "2"
  11567. (when start-level
  11568. (save-excursion
  11569. (goto-char (region-beginning))
  11570. (unless (org-at-heading-p) (outline-next-heading))
  11571. (setq start-level (org-current-level))))
  11572. (narrow-to-region (region-beginning)
  11573. (save-excursion
  11574. (goto-char (region-end))
  11575. (unless (and (bolp) (org-at-heading-p))
  11576. (outline-next-heading))
  11577. (point)))
  11578. (setq scope nil)))
  11579. (if (not scope)
  11580. (progn
  11581. (org-agenda-prepare-buffers
  11582. (and buffer-file-name (list buffer-file-name)))
  11583. (setq res
  11584. (org-scan-tags
  11585. func matcher org--matcher-tags-todo-only start-level)))
  11586. ;; Get the right scope
  11587. (cond
  11588. ((and scope (listp scope) (symbolp (car scope)))
  11589. (setq scope (eval scope)))
  11590. ((eq scope 'agenda)
  11591. (setq scope (org-agenda-files t)))
  11592. ((eq scope 'agenda-with-archives)
  11593. (setq scope (org-agenda-files t))
  11594. (setq scope (org-add-archive-files scope)))
  11595. ((eq scope 'file)
  11596. (setq scope (and buffer-file-name (list buffer-file-name))))
  11597. ((eq scope 'file-with-archives)
  11598. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  11599. (org-agenda-prepare-buffers scope)
  11600. (dolist (file scope)
  11601. (with-current-buffer (org-find-base-buffer-visiting file)
  11602. (org-with-wide-buffer
  11603. (goto-char (point-min))
  11604. (setq res
  11605. (append
  11606. res
  11607. (org-scan-tags
  11608. func matcher org--matcher-tags-todo-only)))))))))
  11609. res)))
  11610. ;;; Properties API
  11611. (defconst org-special-properties
  11612. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  11613. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  11614. "The special properties valid in Org mode.
  11615. These are properties that are not defined in the property drawer,
  11616. but in some other way.")
  11617. (defconst org-default-properties
  11618. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  11619. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  11620. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  11621. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  11622. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  11623. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  11624. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  11625. "Some properties that are used by Org mode for various purposes.
  11626. Being in this list makes sure that they are offered for completion.")
  11627. (defun org--valid-property-p (property)
  11628. "Non-nil when string PROPERTY is a valid property name."
  11629. (not
  11630. (or (equal property "")
  11631. (string-match-p "\\s-" property))))
  11632. (defun org--update-property-plist (key val props)
  11633. "Associate KEY to VAL in alist PROPS.
  11634. Modifications are made by side-effect. Return new alist."
  11635. (let* ((appending (string= (substring key -1) "+"))
  11636. (key (if appending (substring key 0 -1) key))
  11637. (old (assoc-string key props t)))
  11638. (if (not old) (cons (cons key val) props)
  11639. (setcdr old (if appending (concat (cdr old) " " val) val))
  11640. props)))
  11641. (defun org-get-property-block (&optional beg force)
  11642. "Return the (beg . end) range of the body of the property drawer.
  11643. BEG is the beginning of the current subtree or the beginning of
  11644. the document if before the first headline. If it is not given,
  11645. it will be found. If the drawer does not exist, create it if
  11646. FORCE is non-nil, or return nil."
  11647. (org-with-wide-buffer
  11648. (let ((beg (cond (beg (goto-char beg))
  11649. ((or (not (featurep 'org-inlinetask))
  11650. (org-inlinetask-in-task-p))
  11651. (org-back-to-heading-or-point-min t) (point))
  11652. (t (org-with-limited-levels
  11653. (org-back-to-heading-or-point-min t))
  11654. (point)))))
  11655. ;; Move point to its position according to its positional rules.
  11656. (cond ((org-before-first-heading-p)
  11657. (while (and (org-at-comment-p) (bolp)) (forward-line)))
  11658. (t (forward-line)
  11659. (when (looking-at-p org-planning-line-re) (forward-line))))
  11660. (cond ((looking-at org-property-drawer-re)
  11661. (forward-line)
  11662. (cons (point) (progn (goto-char (match-end 0))
  11663. (line-beginning-position))))
  11664. (force
  11665. (goto-char beg)
  11666. (org-insert-property-drawer)
  11667. (let ((pos (save-excursion (re-search-forward org-property-drawer-re)
  11668. (line-beginning-position))))
  11669. (cons pos pos)))))))
  11670. (defun org-at-property-drawer-p ()
  11671. "Non-nil when point is at the first line of a property drawer."
  11672. (org-with-wide-buffer
  11673. (beginning-of-line)
  11674. (and (looking-at org-property-drawer-re)
  11675. (or (bobp)
  11676. (progn
  11677. (forward-line -1)
  11678. (cond ((org-at-heading-p))
  11679. ((looking-at org-planning-line-re)
  11680. (forward-line -1)
  11681. (org-at-heading-p))
  11682. ((looking-at org-comment-regexp)
  11683. (forward-line -1)
  11684. (while (and (not (bobp)) (looking-at org-comment-regexp))
  11685. (forward-line -1))
  11686. (looking-at org-comment-regexp))
  11687. (t nil)))))))
  11688. (defun org-at-property-p ()
  11689. "Non-nil when point is inside a property drawer.
  11690. See `org-property-re' for match data, if applicable."
  11691. (save-excursion
  11692. (beginning-of-line)
  11693. (and (looking-at org-property-re)
  11694. (let ((property-drawer (save-match-data (org-get-property-block))))
  11695. (and property-drawer
  11696. (>= (point) (car property-drawer))
  11697. (< (point) (cdr property-drawer)))))))
  11698. (defun org-property-action ()
  11699. "Do an action on properties."
  11700. (interactive)
  11701. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  11702. (let ((c (read-char-exclusive)))
  11703. (cl-case c
  11704. (?s (call-interactively #'org-set-property))
  11705. (?d (call-interactively #'org-delete-property))
  11706. (?D (call-interactively #'org-delete-property-globally))
  11707. (?c (call-interactively #'org-compute-property-at-point))
  11708. (otherwise (user-error "No such property action %c" c)))))
  11709. (defun org-inc-effort ()
  11710. "Increment the value of the effort property in the current entry."
  11711. (interactive)
  11712. (org-set-effort t))
  11713. (defvar org-clock-effort) ; Defined in org-clock.el.
  11714. (defvar org-clock-current-task) ; Defined in org-clock.el.
  11715. (defun org-set-effort (&optional increment value)
  11716. "Set the effort property of the current entry.
  11717. If INCREMENT is non-nil, set the property to the next allowed
  11718. value. Otherwise, if optional argument VALUE is provided, use
  11719. it. Eventually, prompt for the new value if none of the previous
  11720. variables is set."
  11721. (interactive "P")
  11722. (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
  11723. (current (org-entry-get nil org-effort-property))
  11724. (value
  11725. (cond
  11726. (increment
  11727. (unless allowed (user-error "Allowed effort values are not set"))
  11728. (or (cl-caadr (member (list current) allowed))
  11729. (user-error "Unknown value %S among allowed values" current)))
  11730. (value
  11731. (if (stringp value) value
  11732. (error "Invalid effort value: %S" value)))
  11733. (t
  11734. (let ((must-match
  11735. (and allowed
  11736. (not (get-text-property 0 'org-unrestricted
  11737. (caar allowed))))))
  11738. (completing-read "Effort: " allowed nil must-match))))))
  11739. ;; Test whether the value can be interpreted as a duration before
  11740. ;; inserting it in the buffer:
  11741. (org-duration-to-minutes value)
  11742. ;; Maybe update the effort value:
  11743. (unless (equal current value)
  11744. (org-entry-put nil org-effort-property value))
  11745. (org-refresh-property '((effort . identity)
  11746. (effort-minutes . org-duration-to-minutes))
  11747. value)
  11748. (when (equal (org-get-heading t t t t)
  11749. (bound-and-true-p org-clock-current-task))
  11750. (setq org-clock-effort value)
  11751. (org-clock-update-mode-line))
  11752. (message "%s is now %s" org-effort-property value)))
  11753. (defun org-entry-properties (&optional pom which)
  11754. "Get all properties of the current entry.
  11755. When POM is a buffer position, get all properties from the entry
  11756. there instead.
  11757. This includes the TODO keyword, the tags, time strings for
  11758. deadline, scheduled, and clocking, and any additional properties
  11759. defined in the entry.
  11760. If WHICH is nil or `all', get all properties. If WHICH is
  11761. `special' or `standard', only get that subclass. If WHICH is
  11762. a string, only get that property.
  11763. Return value is an alist. Keys are properties, as upcased
  11764. strings."
  11765. (org-with-point-at pom
  11766. (when (and (derived-mode-p 'org-mode)
  11767. (org-back-to-heading-or-point-min t))
  11768. (catch 'exit
  11769. (let* ((beg (point))
  11770. (specific (and (stringp which) (upcase which)))
  11771. (which (cond ((not specific) which)
  11772. ((member specific org-special-properties) 'special)
  11773. (t 'standard)))
  11774. props)
  11775. ;; Get the special properties, like TODO and TAGS.
  11776. (when (memq which '(nil all special))
  11777. (when (or (not specific) (string= specific "CLOCKSUM"))
  11778. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  11779. (when clocksum
  11780. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  11781. props)))
  11782. (when specific (throw 'exit props)))
  11783. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  11784. (let ((clocksumt (get-text-property (point)
  11785. :org-clock-minutes-today)))
  11786. (when clocksumt
  11787. (push (cons "CLOCKSUM_T"
  11788. (org-duration-from-minutes clocksumt))
  11789. props)))
  11790. (when specific (throw 'exit props)))
  11791. (when (or (not specific) (string= specific "ITEM"))
  11792. (let ((case-fold-search nil))
  11793. (when (looking-at org-complex-heading-regexp)
  11794. (push (cons "ITEM"
  11795. (let ((title (match-string-no-properties 4)))
  11796. (if (org-string-nw-p title)
  11797. (org-remove-tabs title)
  11798. "")))
  11799. props)))
  11800. (when specific (throw 'exit props)))
  11801. (when (or (not specific) (string= specific "TODO"))
  11802. (let ((case-fold-search nil))
  11803. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  11804. (push (cons "TODO" (match-string-no-properties 2)) props)))
  11805. (when specific (throw 'exit props)))
  11806. (when (or (not specific) (string= specific "PRIORITY"))
  11807. (push (cons "PRIORITY"
  11808. (if (looking-at org-priority-regexp)
  11809. (match-string-no-properties 2)
  11810. (char-to-string org-priority-default)))
  11811. props)
  11812. (when specific (throw 'exit props)))
  11813. (when (or (not specific) (string= specific "FILE"))
  11814. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  11815. props)
  11816. (when specific (throw 'exit props)))
  11817. (when (or (not specific) (string= specific "TAGS"))
  11818. (let ((tags (org-get-tags nil t)))
  11819. (when tags
  11820. (push (cons "TAGS" (org-make-tag-string tags))
  11821. props)))
  11822. (when specific (throw 'exit props)))
  11823. (when (or (not specific) (string= specific "ALLTAGS"))
  11824. (let ((tags (org-get-tags)))
  11825. (when tags
  11826. (push (cons "ALLTAGS" (org-make-tag-string tags))
  11827. props)))
  11828. (when specific (throw 'exit props)))
  11829. (when (or (not specific) (string= specific "BLOCKED"))
  11830. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  11831. (when specific (throw 'exit props)))
  11832. (when (or (not specific)
  11833. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  11834. (forward-line)
  11835. (when (looking-at-p org-planning-line-re)
  11836. (end-of-line)
  11837. (let ((bol (line-beginning-position))
  11838. ;; Backward compatibility: time keywords used to
  11839. ;; be configurable (before 8.3). Make sure we
  11840. ;; get the correct keyword.
  11841. (key-assoc `(("CLOSED" . ,org-closed-string)
  11842. ("DEADLINE" . ,org-deadline-string)
  11843. ("SCHEDULED" . ,org-scheduled-string))))
  11844. (dolist (pair (if specific (list (assoc specific key-assoc))
  11845. key-assoc))
  11846. (save-excursion
  11847. (when (search-backward (cdr pair) bol t)
  11848. (goto-char (match-end 0))
  11849. (skip-chars-forward " \t")
  11850. (and (looking-at org-ts-regexp-both)
  11851. (push (cons (car pair)
  11852. (match-string-no-properties 0))
  11853. props)))))))
  11854. (when specific (throw 'exit props)))
  11855. (when (or (not specific)
  11856. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  11857. (let ((find-ts
  11858. (lambda (end ts)
  11859. ;; Fix next time-stamp before END. TS is the
  11860. ;; list of time-stamps found so far.
  11861. (let ((ts ts)
  11862. (regexp (cond
  11863. ((string= specific "TIMESTAMP")
  11864. org-ts-regexp)
  11865. ((string= specific "TIMESTAMP_IA")
  11866. org-ts-regexp-inactive)
  11867. ((assoc "TIMESTAMP_IA" ts)
  11868. org-ts-regexp)
  11869. ((assoc "TIMESTAMP" ts)
  11870. org-ts-regexp-inactive)
  11871. (t org-ts-regexp-both))))
  11872. (catch 'next
  11873. (while (re-search-forward regexp end t)
  11874. (backward-char)
  11875. (let ((object (org-element-context)))
  11876. ;; Accept to match timestamps in node
  11877. ;; properties, too.
  11878. (when (memq (org-element-type object)
  11879. '(node-property timestamp))
  11880. (let ((type
  11881. (org-element-property :type object)))
  11882. (cond
  11883. ((and (memq type '(active active-range))
  11884. (not (equal specific "TIMESTAMP_IA")))
  11885. (unless (assoc "TIMESTAMP" ts)
  11886. (push (cons "TIMESTAMP"
  11887. (org-element-property
  11888. :raw-value object))
  11889. ts)
  11890. (when specific (throw 'exit ts))))
  11891. ((and (memq type '(inactive inactive-range))
  11892. (not (string= specific "TIMESTAMP")))
  11893. (unless (assoc "TIMESTAMP_IA" ts)
  11894. (push (cons "TIMESTAMP_IA"
  11895. (org-element-property
  11896. :raw-value object))
  11897. ts)
  11898. (when specific (throw 'exit ts))))))
  11899. ;; Both timestamp types are found,
  11900. ;; move to next part.
  11901. (when (= (length ts) 2) (throw 'next ts)))))
  11902. ts)))))
  11903. (goto-char beg)
  11904. ;; First look for timestamps within headline.
  11905. (let ((ts (funcall find-ts (line-end-position) nil)))
  11906. (if (= (length ts) 2) (setq props (nconc ts props))
  11907. ;; Then find timestamps in the section, skipping
  11908. ;; planning line.
  11909. (let ((end (save-excursion (outline-next-heading))))
  11910. (forward-line)
  11911. (when (looking-at-p org-planning-line-re) (forward-line))
  11912. (setq props (nconc (funcall find-ts end ts) props))))))))
  11913. ;; Get the standard properties, like :PROP:.
  11914. (when (memq which '(nil all standard))
  11915. ;; If we are looking after a specific property, delegate
  11916. ;; to `org-entry-get', which is faster. However, make an
  11917. ;; exception for "CATEGORY", since it can be also set
  11918. ;; through keywords (i.e. #+CATEGORY).
  11919. (if (and specific (not (equal specific "CATEGORY")))
  11920. (let ((value (org-entry-get beg specific nil t)))
  11921. (throw 'exit (and value (list (cons specific value)))))
  11922. (let ((range (org-get-property-block beg)))
  11923. (when range
  11924. (let ((end (cdr range)) seen-base)
  11925. (goto-char (car range))
  11926. ;; Unlike to `org--update-property-plist', we
  11927. ;; handle the case where base values is found
  11928. ;; after its extension. We also forbid standard
  11929. ;; properties to be named as special properties.
  11930. (while (re-search-forward org-property-re end t)
  11931. (let* ((key (upcase (match-string-no-properties 2)))
  11932. (extendp (string-match-p "\\+\\'" key))
  11933. (key-base (if extendp (substring key 0 -1) key))
  11934. (value (match-string-no-properties 3)))
  11935. (cond
  11936. ((member-ignore-case key-base org-special-properties))
  11937. (extendp
  11938. (setq props
  11939. (org--update-property-plist key value props)))
  11940. ((member key seen-base))
  11941. (t (push key seen-base)
  11942. (let ((p (assoc-string key props t)))
  11943. (if p (setcdr p (concat value " " (cdr p)))
  11944. (push (cons key value) props))))))))))))
  11945. (unless (assoc "CATEGORY" props)
  11946. (push (cons "CATEGORY" (org-get-category beg)) props)
  11947. (when (string= specific "CATEGORY") (throw 'exit props)))
  11948. ;; Return value.
  11949. props)))))
  11950. (defun org--property-local-values (property literal-nil &optional element)
  11951. "Return value for PROPERTY in current entry or ELEMENT.
  11952. Value is a list whose car is the base value for PROPERTY and cdr
  11953. a list of accumulated values. Return nil if neither is found in
  11954. the entry. Also return nil when PROPERTY is set to \"nil\",
  11955. unless LITERAL-NIL is non-nil."
  11956. (if-let ((element (or element
  11957. (and (org-element--cache-active-p)
  11958. (org-element-at-point nil 'cached)))))
  11959. (let* ((element (org-element-lineage element '(headline org-data inlinetask) 'with-self))
  11960. (base-value (org-element-property (intern (concat ":" (upcase property))) element))
  11961. (base-value (if literal-nil base-value (org-not-nil base-value)))
  11962. (extra-value (org-element-property (intern (concat ":" (upcase property) "+")) element))
  11963. (extra-value (if (listp extra-value) extra-value (list extra-value)))
  11964. (value (cons base-value extra-value)))
  11965. (and (not (equal value '(nil))) value))
  11966. (let ((range (org-get-property-block)))
  11967. (when range
  11968. (goto-char (car range))
  11969. (let* ((case-fold-search t)
  11970. (end (cdr range))
  11971. (value
  11972. ;; Base value.
  11973. (save-excursion
  11974. (let ((v (and (re-search-forward
  11975. (org-re-property property nil t) end t)
  11976. (match-string-no-properties 3))))
  11977. (list (if literal-nil v (org-not-nil v)))))))
  11978. ;; Find additional values.
  11979. (let* ((property+ (org-re-property (concat property "+") nil t)))
  11980. (while (re-search-forward property+ end t)
  11981. (push (match-string-no-properties 3) value)))
  11982. ;; Return final values.
  11983. (and (not (equal value '(nil))) (nreverse value)))))))
  11984. (defun org--property-global-or-keyword-value (property literal-nil)
  11985. "Return value for PROPERTY as defined by global properties or by keyword.
  11986. Return value is a string. Return nil if property is not set
  11987. globally or by keyword. Also return nil when PROPERTY is set to
  11988. \"nil\", unless LITERAL-NIL is non-nil."
  11989. (let ((global
  11990. (cdr (or (assoc-string property org-keyword-properties t)
  11991. (assoc-string property org-global-properties t)
  11992. (assoc-string property org-global-properties-fixed t)))))
  11993. (if literal-nil global (org-not-nil global))))
  11994. (defun org-entry-get (pom property &optional inherit literal-nil)
  11995. "Get value of PROPERTY for entry or content at point-or-marker POM.
  11996. If INHERIT is non-nil and the entry does not have the property,
  11997. then also check higher levels of the hierarchy. If INHERIT is
  11998. the symbol `selective', use inheritance only if the setting in
  11999. `org-use-property-inheritance' selects PROPERTY for inheritance.
  12000. If the property is present but empty, the return value is the
  12001. empty string. If the property is not present at all, nil is
  12002. returned. In any other case, return the value as a string.
  12003. Search is case-insensitive.
  12004. If LITERAL-NIL is set, return the string value \"nil\" as
  12005. a string, do not interpret it as the list atom nil. This is used
  12006. for inheritance when a \"nil\" value can supersede a non-nil
  12007. value higher up the hierarchy."
  12008. (org-with-point-at pom
  12009. (cond
  12010. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  12011. ;; We need a special property. Use `org-entry-properties' to
  12012. ;; retrieve it, but specify the wanted property.
  12013. (cdr (assoc-string property (org-entry-properties nil property))))
  12014. ((and inherit
  12015. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  12016. (org-entry-get-with-inheritance property literal-nil))
  12017. (t
  12018. (let* ((local (org--property-local-values property literal-nil))
  12019. (value (and local (mapconcat #'identity (delq nil local) " "))))
  12020. (if literal-nil value (org-not-nil value)))))))
  12021. (defun org-property-or-variable-value (var &optional inherit)
  12022. "Check if there is a property fixing the value of VAR.
  12023. If yes, return this value. If not, return the current value of the variable."
  12024. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  12025. (if (and prop (stringp prop) (string-match "\\S-" prop))
  12026. (read prop)
  12027. (symbol-value var))))
  12028. (defun org-entry-delete (pom property)
  12029. "Delete PROPERTY from entry at point-or-marker POM.
  12030. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  12031. non-nil when a property was removed."
  12032. (org-with-point-at pom
  12033. (pcase (org-get-property-block)
  12034. (`(,begin . ,origin)
  12035. (let* ((end (copy-marker origin))
  12036. (re (org-re-property
  12037. (concat (regexp-quote property) "\\+?") t t)))
  12038. (goto-char begin)
  12039. (while (re-search-forward re end t)
  12040. (delete-region (match-beginning 0) (line-beginning-position 2)))
  12041. ;; If drawer is empty, remove it altogether.
  12042. (when (= begin end)
  12043. (delete-region (line-beginning-position 0)
  12044. (line-beginning-position 2)))
  12045. ;; Return non-nil if some property was removed.
  12046. (prog1 (/= end origin) (set-marker end nil))))
  12047. (_ nil))))
  12048. ;; Multi-values properties are properties that contain multiple values
  12049. ;; These values are assumed to be single words, separated by whitespace.
  12050. (defun org-entry-add-to-multivalued-property (pom property value)
  12051. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  12052. (let* ((old (org-entry-get pom property))
  12053. (values (and old (split-string old))))
  12054. (setq value (org-entry-protect-space value))
  12055. (unless (member value values)
  12056. (setq values (append values (list value)))
  12057. (org-entry-put pom property (mapconcat #'identity values " ")))))
  12058. (defun org-entry-remove-from-multivalued-property (pom property value)
  12059. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  12060. (let* ((old (org-entry-get pom property))
  12061. (values (and old (split-string old))))
  12062. (setq value (org-entry-protect-space value))
  12063. (when (member value values)
  12064. (setq values (delete value values))
  12065. (org-entry-put pom property (mapconcat #'identity values " ")))))
  12066. (defun org-entry-member-in-multivalued-property (pom property value)
  12067. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  12068. (let* ((old (org-entry-get pom property))
  12069. (values (and old (split-string old))))
  12070. (setq value (org-entry-protect-space value))
  12071. (member value values)))
  12072. (defun org-entry-get-multivalued-property (pom property)
  12073. "Return a list of values in a multivalued property."
  12074. (let* ((value (org-entry-get pom property))
  12075. (values (and value (split-string value))))
  12076. (mapcar #'org-entry-restore-space values)))
  12077. (defun org-entry-put-multivalued-property (pom property &rest values)
  12078. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  12079. VALUES should be a list of strings. Spaces will be protected."
  12080. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  12081. (let* ((value (org-entry-get pom property))
  12082. (values (and value (split-string value))))
  12083. (mapcar #'org-entry-restore-space values)))
  12084. (defun org-entry-protect-space (s)
  12085. "Protect spaces and newline in string S."
  12086. (while (string-match " " s)
  12087. (setq s (replace-match "%20" t t s)))
  12088. (while (string-match "\n" s)
  12089. (setq s (replace-match "%0A" t t s)))
  12090. s)
  12091. (defun org-entry-restore-space (s)
  12092. "Restore spaces and newline in string S."
  12093. (while (string-match "%20" s)
  12094. (setq s (replace-match " " t t s)))
  12095. (while (string-match "%0A" s)
  12096. (setq s (replace-match "\n" t t s)))
  12097. s)
  12098. (defvar org-entry-property-inherited-from (make-marker)
  12099. "Marker pointing to the entry from where a property was inherited.
  12100. Each call to `org-entry-get-with-inheritance' will set this marker to the
  12101. location of the entry where the inheritance search matched. If there was
  12102. no match, the marker will point nowhere.
  12103. Note that also `org-entry-get' calls this function, if the INHERIT flag
  12104. is set.")
  12105. (defun org-entry-get-with-inheritance (property &optional literal-nil element)
  12106. "Get PROPERTY of entry or content at point, search higher levels if needed.
  12107. The search will stop at the first ancestor which has the property defined.
  12108. If the value found is \"nil\", return nil to show that the property
  12109. should be considered as undefined (this is the meaning of nil here).
  12110. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  12111. (move-marker org-entry-property-inherited-from nil)
  12112. (org-with-wide-buffer
  12113. (let (value at-bob-no-heading)
  12114. (catch 'exit
  12115. (if-let ((element (or element
  12116. (and (org-element--cache-active-p)
  12117. (org-element-at-point nil 'cached)))))
  12118. (let ((element (org-element-lineage element '(headline org-data inlinetask) 'with-self)))
  12119. (while t
  12120. (let* ((v (org--property-local-values property literal-nil element))
  12121. (v (if (listp v) v (list v))))
  12122. (when v
  12123. (setq value
  12124. (concat (mapconcat #'identity (delq nil v) " ")
  12125. (and value " ")
  12126. value)))
  12127. (cond
  12128. ((car v)
  12129. (move-marker org-entry-property-inherited-from (org-element-property :begin element))
  12130. (throw 'exit nil))
  12131. ((org-element-property :parent element)
  12132. (setq element (org-element-property :parent element)))
  12133. (t
  12134. (let ((global (org--property-global-or-keyword-value property literal-nil)))
  12135. (cond ((not global))
  12136. (value (setq value (concat global " " value)))
  12137. (t (setq value global))))
  12138. (throw 'exit nil))))))
  12139. (while t
  12140. (let ((v (org--property-local-values property literal-nil)))
  12141. (when v
  12142. (setq value
  12143. (concat (mapconcat #'identity (delq nil v) " ")
  12144. (and value " ")
  12145. value)))
  12146. (cond
  12147. ((car v)
  12148. (org-back-to-heading-or-point-min t)
  12149. (move-marker org-entry-property-inherited-from (point))
  12150. (throw 'exit nil))
  12151. ((or (org-up-heading-safe)
  12152. (and (not (bobp))
  12153. (goto-char (point-min))
  12154. nil)
  12155. ;; `org-up-heading-safe' returned nil. We are at low
  12156. ;; level heading or bob. If there is headline
  12157. ;; there, do not try to fetch its properties.
  12158. (and (bobp)
  12159. (not at-bob-no-heading)
  12160. (not (org-at-heading-p))
  12161. (setq at-bob-no-heading t))))
  12162. (t
  12163. (let ((global (org--property-global-or-keyword-value property literal-nil)))
  12164. (cond ((not global))
  12165. (value (setq value (concat global " " value)))
  12166. (t (setq value global))))
  12167. (throw 'exit nil)))))))
  12168. (if literal-nil value (org-not-nil value)))))
  12169. (defvar org-property-changed-functions nil
  12170. "Hook called when the value of a property has changed.
  12171. Each hook function should accept two arguments, the name of the property
  12172. and the new value.")
  12173. (defun org-entry-put (pom property value)
  12174. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  12175. If the value is nil, it is converted to the empty string. If it
  12176. is not a string, an error is raised. Also raise an error on
  12177. invalid property names.
  12178. PROPERTY can be any regular property (see
  12179. `org-special-properties'). It can also be \"TODO\",
  12180. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  12181. For the last two properties, VALUE may have any of the special
  12182. values \"earlier\" and \"later\". The function then increases or
  12183. decreases scheduled or deadline date by one day."
  12184. (cond ((null value) (setq value ""))
  12185. ((not (stringp value)) (error "Properties values should be strings"))
  12186. ((not (org--valid-property-p property))
  12187. (user-error "Invalid property name: \"%s\"" property)))
  12188. (org-no-read-only
  12189. (org-with-point-at pom
  12190. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  12191. (org-back-to-heading-or-point-min t)
  12192. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  12193. (let ((beg (point)))
  12194. (cond
  12195. ((equal property "TODO")
  12196. (cond ((not (org-string-nw-p value)) (setq value 'none))
  12197. ((not (member value org-todo-keywords-1))
  12198. (user-error "\"%s\" is not a valid TODO state" value)))
  12199. (org-todo value)
  12200. (org-align-tags))
  12201. ((equal property "PRIORITY")
  12202. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  12203. (org-align-tags))
  12204. ((equal property "SCHEDULED")
  12205. (forward-line)
  12206. (if (and (looking-at-p org-planning-line-re)
  12207. (re-search-forward
  12208. org-scheduled-time-regexp (line-end-position) t))
  12209. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  12210. ((string= value "later") (org-timestamp-change 1 'day))
  12211. ((string= value "") (org-schedule '(4)))
  12212. (t (org-schedule nil value)))
  12213. (if (member value '("earlier" "later" ""))
  12214. (call-interactively #'org-schedule)
  12215. (org-schedule nil value))))
  12216. ((equal property "DEADLINE")
  12217. (forward-line)
  12218. (if (and (looking-at-p org-planning-line-re)
  12219. (re-search-forward
  12220. org-deadline-time-regexp (line-end-position) t))
  12221. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  12222. ((string= value "later") (org-timestamp-change 1 'day))
  12223. ((string= value "") (org-deadline '(4)))
  12224. (t (org-deadline nil value)))
  12225. (if (member value '("earlier" "later" ""))
  12226. (call-interactively #'org-deadline)
  12227. (org-deadline nil value))))
  12228. ((member property org-special-properties)
  12229. (error "The %s property cannot be set with `org-entry-put'" property))
  12230. (t
  12231. (let* ((range (org-get-property-block beg 'force))
  12232. (end (cdr range))
  12233. (case-fold-search t))
  12234. (goto-char (car range))
  12235. (if (re-search-forward (org-re-property property nil t) end t)
  12236. (progn (delete-region (match-beginning 0) (match-end 0))
  12237. (goto-char (match-beginning 0)))
  12238. (goto-char end)
  12239. (insert "\n")
  12240. (backward-char))
  12241. (insert ":" property ":")
  12242. (when value (insert " " value))
  12243. (org-indent-line)))))
  12244. (run-hook-with-args 'org-property-changed-functions property value))))
  12245. (defun org-buffer-property-keys (&optional specials defaults columns)
  12246. "Get all property keys in the current buffer.
  12247. When SPECIALS is non-nil, also list the special properties that
  12248. reflect things like tags and TODO state.
  12249. When DEFAULTS is non-nil, also include properties that has
  12250. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  12251. DESCRIPTION, LOCATION, and LOGGING and others.
  12252. When COLUMNS in non-nil, also include property names given in
  12253. COLUMN formats in the current buffer."
  12254. (let ((case-fold-search t)
  12255. (props (append
  12256. (and specials org-special-properties)
  12257. (and defaults (cons org-effort-property org-default-properties))
  12258. ;; Get property names from #+PROPERTY keywords as well
  12259. (mapcar (lambda (s)
  12260. (nth 0 (split-string s)))
  12261. (cdar (org-collect-keywords '("PROPERTY")))))))
  12262. (org-with-wide-buffer
  12263. (goto-char (point-min))
  12264. (while (re-search-forward org-property-start-re nil t)
  12265. (catch :skip
  12266. (let ((range (org-get-property-block)))
  12267. (unless range (throw :skip nil))
  12268. (goto-char (car range))
  12269. (let ((begin (car range))
  12270. (end (cdr range)))
  12271. ;; Make sure that found property block is not located
  12272. ;; before current point, as it would generate an infloop.
  12273. ;; It can happen, for example, in the following
  12274. ;; situation:
  12275. ;;
  12276. ;; * Headline
  12277. ;; :PROPERTIES:
  12278. ;; ...
  12279. ;; :END:
  12280. ;; *************** Inlinetask
  12281. ;; #+BEGIN_EXAMPLE
  12282. ;; :PROPERTIES:
  12283. ;; #+END_EXAMPLE
  12284. ;;
  12285. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  12286. (while (< (point) end)
  12287. (let ((p (progn (looking-at org-property-re)
  12288. (match-string-no-properties 2))))
  12289. ;; Only add true property name, not extension symbol.
  12290. (push (if (not (string-match-p "\\+\\'" p)) p
  12291. (substring p 0 -1))
  12292. props))
  12293. (forward-line))))
  12294. (outline-next-heading)))
  12295. (when columns
  12296. (goto-char (point-min))
  12297. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  12298. (let ((element (org-element-at-point)))
  12299. (when (memq (org-element-type element) '(keyword node-property))
  12300. (let ((value (org-element-property :value element))
  12301. (start 0))
  12302. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  12303. \\(?:{[^}]+}\\)?"
  12304. value start)
  12305. (setq start (match-end 0))
  12306. (let ((p (match-string-no-properties 1 value)))
  12307. (unless (member-ignore-case p org-special-properties)
  12308. (push p props))))))))))
  12309. (sort (delete-dups
  12310. (append props
  12311. ;; for each xxx_ALL property, make sure the bare
  12312. ;; xxx property is also included
  12313. (delq nil (mapcar (lambda (p)
  12314. (and (string-match-p "._ALL\\'" p)
  12315. (substring p 0 -4)))
  12316. props))))
  12317. (lambda (a b) (string< (upcase a) (upcase b))))))
  12318. (defun org-property-values (key)
  12319. "List all non-nil values of property KEY in current buffer."
  12320. (org-with-wide-buffer
  12321. (goto-char (point-min))
  12322. (let ((case-fold-search t)
  12323. (re (org-re-property key))
  12324. values)
  12325. (while (re-search-forward re nil t)
  12326. (push (org-entry-get (point) key) values))
  12327. (delete-dups values))))
  12328. (defun org-insert-property-drawer ()
  12329. "Insert a property drawer into the current entry.
  12330. Do nothing if the drawer already exists. The newly created
  12331. drawer is immediately hidden."
  12332. (org-with-wide-buffer
  12333. ;; Set point to the position where the drawer should be inserted.
  12334. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  12335. (org-back-to-heading-or-point-min t)
  12336. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  12337. (if (org-before-first-heading-p)
  12338. (while (and (org-at-comment-p) (bolp)) (forward-line))
  12339. (progn
  12340. (forward-line)
  12341. (when (looking-at-p org-planning-line-re) (forward-line))))
  12342. (unless (looking-at-p org-property-drawer-re)
  12343. ;; Make sure we start editing a line from current entry, not from
  12344. ;; next one. It prevents extending text properties or overlays
  12345. ;; belonging to the latter.
  12346. (when (and (bolp) (> (point) (point-min))) (backward-char))
  12347. (let ((begin (if (bobp) (point) (1+ (point))))
  12348. (inhibit-read-only t))
  12349. (unless (bobp) (insert "\n"))
  12350. (insert ":PROPERTIES:\n:END:")
  12351. (org-flag-region (line-end-position 0) (point) t 'outline)
  12352. (when (or (eobp) (= begin (point-min))) (insert "\n"))
  12353. (org-indent-region begin (point))))))
  12354. (defun org-insert-drawer (&optional arg drawer)
  12355. "Insert a drawer at point.
  12356. When optional argument ARG is non-nil, insert a property drawer.
  12357. Optional argument DRAWER, when non-nil, is a string representing
  12358. drawer's name. Otherwise, the user is prompted for a name.
  12359. If a region is active, insert the drawer around that region
  12360. instead.
  12361. Point is left between drawer's boundaries."
  12362. (interactive "P")
  12363. (let* ((drawer (if arg "PROPERTIES"
  12364. (or drawer (read-from-minibuffer "Drawer: ")))))
  12365. (cond
  12366. ;; With C-u, fall back on `org-insert-property-drawer'
  12367. (arg (org-insert-property-drawer))
  12368. ;; Check validity of suggested drawer's name.
  12369. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  12370. (user-error "Invalid drawer name"))
  12371. ;; With an active region, insert a drawer at point.
  12372. ((not (org-region-active-p))
  12373. (progn
  12374. (unless (bolp) (insert "\n"))
  12375. (insert (format ":%s:\n\n:END:\n" drawer))
  12376. (forward-line -2)))
  12377. ;; Otherwise, insert the drawer at point
  12378. (t
  12379. (let ((rbeg (region-beginning))
  12380. (rend (copy-marker (region-end))))
  12381. (unwind-protect
  12382. (progn
  12383. (goto-char rbeg)
  12384. (beginning-of-line)
  12385. (when (save-excursion
  12386. (re-search-forward org-outline-regexp-bol rend t))
  12387. (user-error "Drawers cannot contain headlines"))
  12388. ;; Position point at the beginning of the first
  12389. ;; non-blank line in region. Insert drawer's opening
  12390. ;; there, then indent it.
  12391. (org-skip-whitespace)
  12392. (beginning-of-line)
  12393. (insert ":" drawer ":\n")
  12394. (forward-line -1)
  12395. (indent-for-tab-command)
  12396. ;; Move point to the beginning of the first blank line
  12397. ;; after the last non-blank line in region. Insert
  12398. ;; drawer's closing, then indent it.
  12399. (goto-char rend)
  12400. (skip-chars-backward " \r\t\n")
  12401. (insert "\n:END:")
  12402. (deactivate-mark t)
  12403. (indent-for-tab-command)
  12404. (unless (eolp) (insert "\n")))
  12405. ;; Clear marker, whatever the outcome of insertion is.
  12406. (set-marker rend nil)))))))
  12407. (defvar org-property-set-functions-alist nil
  12408. "Property set function alist.
  12409. Each entry should have the following format:
  12410. (PROPERTY . READ-FUNCTION)
  12411. The read function will be called with the same argument as
  12412. `org-completing-read'.")
  12413. (defun org-set-property-function (property)
  12414. "Get the function that should be used to set PROPERTY.
  12415. This is computed according to `org-property-set-functions-alist'."
  12416. (or (cdr (assoc property org-property-set-functions-alist))
  12417. 'org-completing-read))
  12418. (defun org-read-property-value (property &optional pom default)
  12419. "Read value for PROPERTY, as a string.
  12420. When optional argument POM is non-nil, completion uses additional
  12421. information, i.e., allowed or existing values at point or marker
  12422. POM.
  12423. Optional argument DEFAULT provides a default value for PROPERTY."
  12424. (let* ((completion-ignore-case t)
  12425. (allowed
  12426. (or (org-property-get-allowed-values nil property 'table)
  12427. (and pom (org-property-get-allowed-values pom property 'table))))
  12428. (current (org-entry-get nil property))
  12429. (prompt (format "%s value%s: "
  12430. property
  12431. (if (org-string-nw-p current)
  12432. (format " [%s]" current)
  12433. "")))
  12434. (set-function (org-set-property-function property)))
  12435. (org-trim
  12436. (if allowed
  12437. (funcall set-function
  12438. prompt allowed nil
  12439. (not (get-text-property 0 'org-unrestricted (caar allowed)))
  12440. default nil default)
  12441. (let ((all (mapcar #'list
  12442. (append (org-property-values property)
  12443. (and pom
  12444. (org-with-point-at pom
  12445. (org-property-values property)))))))
  12446. (funcall set-function prompt all nil nil "" nil current))))))
  12447. (defvar org-last-set-property nil)
  12448. (defvar org-last-set-property-value nil)
  12449. (defun org-read-property-name ()
  12450. "Read a property name."
  12451. (let ((completion-ignore-case t)
  12452. (default-prop (or (and (org-at-property-p)
  12453. (match-string-no-properties 2))
  12454. org-last-set-property)))
  12455. (org-completing-read
  12456. (concat "Property"
  12457. (if default-prop (concat " [" default-prop "]") "")
  12458. ": ")
  12459. (mapcar #'list (org-buffer-property-keys nil t t))
  12460. nil nil nil nil default-prop)))
  12461. (defun org-set-property-and-value (use-last)
  12462. "Allow to set [PROPERTY]: [value] direction from prompt.
  12463. When use-default, don't even ask, just use the last
  12464. \"[PROPERTY]: [value]\" string from the history."
  12465. (interactive "P")
  12466. (let* ((completion-ignore-case t)
  12467. (pv (or (and use-last org-last-set-property-value)
  12468. (org-completing-read
  12469. "Enter a \"[Property]: [value]\" pair: "
  12470. nil nil nil nil nil
  12471. org-last-set-property-value)))
  12472. prop val)
  12473. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  12474. (setq prop (match-string 1 pv)
  12475. val (match-string 2 pv))
  12476. (org-set-property prop val))))
  12477. (defun org-set-property (property value)
  12478. "In the current entry, set PROPERTY to VALUE.
  12479. When called interactively, this will prompt for a property name, offering
  12480. completion on existing and default properties. And then it will prompt
  12481. for a value, offering completion either on allowed values (via an inherited
  12482. xxx_ALL property) or on existing values in other instances of this property
  12483. in the current file.
  12484. Throw an error when trying to set a property with an invalid name."
  12485. (interactive (list nil nil))
  12486. (let ((property (or property (org-read-property-name))))
  12487. ;; `org-entry-put' also makes the following check, but this one
  12488. ;; avoids polluting `org-last-set-property' and
  12489. ;; `org-last-set-property-value' needlessly.
  12490. (unless (org--valid-property-p property)
  12491. (user-error "Invalid property name: \"%s\"" property))
  12492. (let ((value (or value (org-read-property-value property)))
  12493. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  12494. (setq org-last-set-property property)
  12495. (setq org-last-set-property-value (concat property ": " value))
  12496. ;; Possibly postprocess the inserted value:
  12497. (when fn (setq value (funcall fn value)))
  12498. (unless (equal (org-entry-get nil property) value)
  12499. (org-entry-put nil property value)))))
  12500. (defun org-find-property (property &optional value)
  12501. "Find first entry in buffer that sets PROPERTY.
  12502. When optional argument VALUE is non-nil, only consider an entry
  12503. if it contains PROPERTY set to this value. If PROPERTY should be
  12504. explicitly set to nil, use string \"nil\" for VALUE.
  12505. Return position where the entry begins, or nil if there is no
  12506. such entry. If narrowing is in effect, only search the visible
  12507. part of the buffer."
  12508. (save-excursion
  12509. (goto-char (point-min))
  12510. (let ((case-fold-search t)
  12511. (re (org-re-property property nil (not value) value)))
  12512. (catch 'exit
  12513. (while (re-search-forward re nil t)
  12514. (when (if value (org-at-property-p)
  12515. (org-entry-get (point) property nil t))
  12516. (throw 'exit (progn (org-back-to-heading-or-point-min t)
  12517. (point)))))))))
  12518. (defun org-delete-property (property)
  12519. "In the current entry, delete PROPERTY."
  12520. (interactive
  12521. (let* ((completion-ignore-case t)
  12522. (cat (org-entry-get (point) "CATEGORY"))
  12523. (props0 (org-entry-properties nil 'standard))
  12524. (props (if cat props0
  12525. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  12526. (prop (if (< 1 (length props))
  12527. (completing-read "Property: " props nil t)
  12528. (caar props))))
  12529. (list prop)))
  12530. (if (not property)
  12531. (message "No property to delete in this entry")
  12532. (org-entry-delete nil property)
  12533. (message "Property \"%s\" deleted" property)))
  12534. (defun org-delete-property-globally (property)
  12535. "Remove PROPERTY globally, from all entries.
  12536. This function ignores narrowing, if any."
  12537. (interactive
  12538. (let* ((completion-ignore-case t)
  12539. (prop (completing-read
  12540. "Globally remove property: "
  12541. (mapcar #'list (org-buffer-property-keys)))))
  12542. (list prop)))
  12543. (org-with-wide-buffer
  12544. (goto-char (point-min))
  12545. (let ((count 0)
  12546. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  12547. (while (re-search-forward re nil t)
  12548. (when (org-entry-delete (point) property) (cl-incf count)))
  12549. (message "Property \"%s\" removed from %d entries" property count))))
  12550. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  12551. (defun org-compute-property-at-point ()
  12552. "Compute the property at point.
  12553. This looks for an enclosing column format, extracts the operator and
  12554. then applies it to the property in the column format's scope."
  12555. (interactive)
  12556. (unless (org-at-property-p)
  12557. (user-error "Not at a property"))
  12558. (let ((prop (match-string-no-properties 2)))
  12559. (org-columns-get-format-and-top-level)
  12560. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  12561. (user-error "No operator defined for property %s" prop))
  12562. (org-columns-compute prop)))
  12563. (defvar org-property-allowed-value-functions nil
  12564. "Hook for functions supplying allowed values for a specific property.
  12565. The functions must take a single argument, the name of the property, and
  12566. return a flat list of allowed values. If \":ETC\" is one of
  12567. the values, this means that these values are intended as defaults for
  12568. completion, but that other values should be allowed too.
  12569. The functions must return nil if they are not responsible for this
  12570. property.")
  12571. (defun org-property-get-allowed-values (pom property &optional table)
  12572. "Get allowed values for the property PROPERTY.
  12573. When TABLE is non-nil, return an alist that can directly be used for
  12574. completion."
  12575. (let (vals)
  12576. (cond
  12577. ((equal property "TODO")
  12578. (setq vals (org-with-point-at pom
  12579. (append org-todo-keywords-1 '("")))))
  12580. ((equal property "PRIORITY")
  12581. (let ((n org-priority-lowest))
  12582. (while (>= n org-priority-highest)
  12583. (push (char-to-string n) vals)
  12584. (setq n (1- n)))))
  12585. ((equal property "CATEGORY"))
  12586. ((member property org-special-properties))
  12587. ((setq vals (run-hook-with-args-until-success
  12588. 'org-property-allowed-value-functions property)))
  12589. (t
  12590. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  12591. (when (and vals (string-match "\\S-" vals))
  12592. (setq vals (car (read-from-string (concat "(" vals ")"))))
  12593. (setq vals (mapcar (lambda (x)
  12594. (cond ((stringp x) x)
  12595. ((numberp x) (number-to-string x))
  12596. ((symbolp x) (symbol-name x))
  12597. (t "???")))
  12598. vals)))))
  12599. (when (member ":ETC" vals)
  12600. (setq vals (remove ":ETC" vals))
  12601. (org-add-props (car vals) '(org-unrestricted t)))
  12602. (if table (mapcar 'list vals) vals)))
  12603. (defun org-property-previous-allowed-value (&optional _previous)
  12604. "Switch to the next allowed value for this property."
  12605. (interactive)
  12606. (org-property-next-allowed-value t))
  12607. (defun org-property-next-allowed-value (&optional previous)
  12608. "Switch to the next allowed value for this property."
  12609. (interactive)
  12610. (unless (org-at-property-p)
  12611. (user-error "Not at a property"))
  12612. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  12613. (key (match-string 2))
  12614. (value (match-string 3))
  12615. (allowed (or (org-property-get-allowed-values (point) key)
  12616. (and (member value '("[ ]" "[-]" "[X]"))
  12617. '("[ ]" "[X]"))))
  12618. (heading (save-match-data (nth 4 (org-heading-components))))
  12619. nval)
  12620. (unless allowed
  12621. (user-error "Allowed values for this property have not been defined"))
  12622. (when previous (setq allowed (reverse allowed)))
  12623. (when (member value allowed)
  12624. (setq nval (car (cdr (member value allowed)))))
  12625. (setq nval (or nval (car allowed)))
  12626. (when (equal nval value)
  12627. (user-error "Only one allowed value for this property"))
  12628. (org-at-property-p)
  12629. (replace-match (concat " :" key ": " nval) t t)
  12630. (org-indent-line)
  12631. (beginning-of-line 1)
  12632. (skip-chars-forward " \t")
  12633. (when (equal prop org-effort-property)
  12634. (org-refresh-property
  12635. '((effort . identity)
  12636. (effort-minutes . org-duration-to-minutes))
  12637. nval)
  12638. (when (string= org-clock-current-task heading)
  12639. (setq org-clock-effort nval)
  12640. (org-clock-update-mode-line)))
  12641. (run-hook-with-args 'org-property-changed-functions key nval)))
  12642. (defun org-find-olp (path &optional this-buffer)
  12643. "Return a marker pointing to the entry at outline path OLP.
  12644. If anything goes wrong, throw an error, and if you need to do
  12645. something based on this error, you can catch it with
  12646. `condition-case'.
  12647. If THIS-BUFFER is set, the outline path does not contain a file,
  12648. only headings."
  12649. (let* ((file (if this-buffer buffer-file-name (pop path)))
  12650. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  12651. (level 1)
  12652. (lmin 1)
  12653. (lmax 1)
  12654. end found flevel)
  12655. (unless buffer (error "File not found :%s" file))
  12656. (with-current-buffer buffer
  12657. (unless (derived-mode-p 'org-mode)
  12658. (error "Buffer %s needs to be in Org mode" buffer))
  12659. (org-with-wide-buffer
  12660. (goto-char (point-min))
  12661. (dolist (heading path)
  12662. (let ((re (format org-complex-heading-regexp-format
  12663. (regexp-quote heading)))
  12664. (cnt 0))
  12665. (while (re-search-forward re end t)
  12666. (setq level (- (match-end 1) (match-beginning 1)))
  12667. (when (and (>= level lmin) (<= level lmax))
  12668. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  12669. (when (= cnt 0)
  12670. (error "Heading not found on level %d: %s" lmax heading))
  12671. (when (> cnt 1)
  12672. (error "Heading not unique on level %d: %s" lmax heading))
  12673. (goto-char found)
  12674. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  12675. (setq end (save-excursion (org-end-of-subtree t t)))))
  12676. (when (org-at-heading-p)
  12677. (point-marker))))))
  12678. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  12679. "Find node HEADING in BUFFER.
  12680. Return a marker to the heading if it was found, or nil if not.
  12681. If POS-ONLY is set, return just the position instead of a marker.
  12682. The heading text must match exact, but it may have a TODO keyword,
  12683. a priority cookie and tags in the standard locations."
  12684. (with-current-buffer (or buffer (current-buffer))
  12685. (org-with-wide-buffer
  12686. (goto-char (point-min))
  12687. (let (case-fold-search)
  12688. (when (re-search-forward
  12689. (format org-complex-heading-regexp-format
  12690. (regexp-quote heading)) nil t)
  12691. (if pos-only
  12692. (match-beginning 0)
  12693. (move-marker (make-marker) (match-beginning 0))))))))
  12694. (defun org-find-exact-heading-in-directory (heading &optional dir)
  12695. "Find Org node headline HEADING in all \".org\" files in directory DIR.
  12696. When the target headline is found, return a marker to this location."
  12697. (let ((files (directory-files (or dir default-directory)
  12698. t "\\`[^.#].*\\.org\\'"))
  12699. visiting m buffer)
  12700. (catch 'found
  12701. (dolist (file files)
  12702. (message "trying %s" file)
  12703. (setq visiting (org-find-base-buffer-visiting file))
  12704. (setq buffer (or visiting (find-file-noselect file)))
  12705. (setq m (org-find-exact-headline-in-buffer
  12706. heading buffer))
  12707. (when (and (not m) (not visiting)) (kill-buffer buffer))
  12708. (and m (throw 'found m))))))
  12709. (defun org-find-entry-with-id (ident)
  12710. "Locate the entry that contains the ID property with exact value IDENT.
  12711. IDENT can be a string, a symbol or a number, this function will search for
  12712. the string representation of it.
  12713. Return the position where this entry starts, or nil if there is no such entry."
  12714. (interactive "sID: ")
  12715. (let ((id (cond
  12716. ((stringp ident) ident)
  12717. ((symbolp ident) (symbol-name ident))
  12718. ((numberp ident) (number-to-string ident))
  12719. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  12720. (org-with-wide-buffer (org-find-property "ID" id))))
  12721. ;;;; Timestamps
  12722. (defvar org-last-changed-timestamp nil)
  12723. (defvar org-last-inserted-timestamp nil
  12724. "The last time stamp inserted with `org-insert-time-stamp'.")
  12725. (defun org-time-stamp (arg &optional inactive)
  12726. "Prompt for a date/time and insert a time stamp.
  12727. If the user specifies a time like HH:MM or if this command is
  12728. called with at least one prefix argument, the time stamp contains
  12729. the date and the time. Otherwise, only the date is included.
  12730. All parts of a date not specified by the user are filled in from
  12731. the timestamp at point, if any, or the current date/time
  12732. otherwise.
  12733. If there is already a timestamp at the cursor, it is replaced.
  12734. With two universal prefix arguments, insert an active timestamp
  12735. with the current time without prompting the user.
  12736. When called from Lisp, the timestamp is inactive if INACTIVE is
  12737. non-nil."
  12738. (interactive "P")
  12739. (let* ((ts (cond
  12740. ((org-at-date-range-p t)
  12741. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  12742. ((org-at-timestamp-p 'lax) (match-string 0))))
  12743. ;; Default time is either the timestamp at point or today.
  12744. ;; When entering a range, only the range start is considered.
  12745. (default-time (and ts (org-time-string-to-time ts)))
  12746. (default-input (and ts (org-get-compact-tod ts)))
  12747. (repeater (and ts
  12748. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  12749. (match-string 0 ts)))
  12750. org-time-was-given
  12751. org-end-time-was-given
  12752. (time
  12753. (if (equal arg '(16)) (current-time)
  12754. ;; Preserve `this-command' and `last-command'.
  12755. (let ((this-command this-command)
  12756. (last-command last-command))
  12757. (org-read-date
  12758. arg 'totime nil nil default-time default-input
  12759. inactive)))))
  12760. (cond
  12761. ((and ts
  12762. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  12763. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  12764. (insert "--")
  12765. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  12766. (ts
  12767. ;; Make sure we're on a timestamp. When in the middle of a date
  12768. ;; range, move arbitrarily to range end.
  12769. (unless (org-at-timestamp-p 'lax)
  12770. (skip-chars-forward "-")
  12771. (org-at-timestamp-p 'lax))
  12772. (replace-match "")
  12773. (setq org-last-changed-timestamp
  12774. (org-insert-time-stamp
  12775. time (or org-time-was-given arg)
  12776. inactive nil nil (list org-end-time-was-given)))
  12777. (when repeater
  12778. (backward-char)
  12779. (insert " " repeater)
  12780. (setq org-last-changed-timestamp
  12781. (concat (substring org-last-inserted-timestamp 0 -1)
  12782. " " repeater ">")))
  12783. (message "Timestamp updated"))
  12784. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  12785. (t (org-insert-time-stamp
  12786. time (or org-time-was-given arg) inactive nil nil
  12787. (list org-end-time-was-given))))))
  12788. ;; FIXME: can we use this for something else, like computing time differences?
  12789. (defun org-get-compact-tod (s)
  12790. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  12791. (let* ((t1 (match-string 1 s))
  12792. (h1 (string-to-number (match-string 2 s)))
  12793. (m1 (string-to-number (match-string 3 s)))
  12794. (t2 (and (match-end 4) (match-string 5 s)))
  12795. (h2 (and t2 (string-to-number (match-string 6 s))))
  12796. (m2 (and t2 (string-to-number (match-string 7 s))))
  12797. dh dm)
  12798. (if (not t2)
  12799. t1
  12800. (setq dh (- h2 h1) dm (- m2 m1))
  12801. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  12802. (concat t1 "+" (number-to-string dh)
  12803. (and (/= 0 dm) (format ":%02d" dm)))))))
  12804. (defun org-time-stamp-inactive (&optional arg)
  12805. "Insert an inactive time stamp.
  12806. An inactive time stamp is enclosed in square brackets instead of
  12807. angle brackets. It is inactive in the sense that it does not
  12808. trigger agenda entries. So these are more for recording a
  12809. certain time/date.
  12810. If the user specifies a time like HH:MM or if this command is called with
  12811. at least one prefix argument, the time stamp contains the date and the time.
  12812. Otherwise, only the date is included.
  12813. When called with two universal prefix arguments, insert an inactive time stamp
  12814. with the current time without prompting the user."
  12815. (interactive "P")
  12816. (org-time-stamp arg 'inactive))
  12817. (defvar org-date-ovl (make-overlay 1 1))
  12818. (overlay-put org-date-ovl 'face 'org-date-selected)
  12819. (delete-overlay org-date-ovl)
  12820. (defvar org-ans1) ; dynamically scoped parameter
  12821. (defvar org-ans2) ; dynamically scoped parameter
  12822. (defvar org-plain-time-of-day-regexp) ; defined below
  12823. (defvar org-overriding-default-time nil) ; dynamically scoped
  12824. (defvar org-read-date-overlay nil)
  12825. (defvar org-read-date-history nil)
  12826. (defvar org-read-date-final-answer nil)
  12827. (defvar org-read-date-analyze-futurep nil)
  12828. (defvar org-read-date-analyze-forced-year nil)
  12829. (defvar org-read-date-inactive)
  12830. (defvar org-def)
  12831. (defvar org-defdecode)
  12832. (defvar org-with-time)
  12833. (defvar calendar-setup) ; Dynamically scoped.
  12834. (defun org-read-date (&optional with-time to-time from-string prompt
  12835. default-time default-input inactive)
  12836. "Read a date, possibly a time, and make things smooth for the user.
  12837. The prompt will suggest to enter an ISO date, but you can also enter anything
  12838. which will at least partially be understood by `parse-time-string'.
  12839. Unrecognized parts of the date will default to the current day, month, year,
  12840. hour and minute. If this command is called to replace a timestamp at point,
  12841. or to enter the second timestamp of a range, the default time is taken
  12842. from the existing stamp. Furthermore, the command prefers the future,
  12843. so if you are giving a date where the year is not given, and the day-month
  12844. combination is already past in the current year, it will assume you
  12845. mean next year. For details, see the manual. A few examples:
  12846. 3-2-5 --> 2003-02-05
  12847. feb 15 --> currentyear-02-15
  12848. 2/15 --> currentyear-02-15
  12849. sep 12 9 --> 2009-09-12
  12850. 12:45 --> today 12:45
  12851. 22 sept 0:34 --> currentyear-09-22 0:34
  12852. 12 --> currentyear-currentmonth-12
  12853. Fri --> nearest Friday after today
  12854. -Tue --> last Tuesday
  12855. etc.
  12856. Furthermore you can specify a relative date by giving, as the *first* thing
  12857. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  12858. change in days weeks, months, years.
  12859. With a single plus or minus, the date is relative to today. With a double
  12860. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  12861. +4d --> four days from today
  12862. +4 --> same as above
  12863. +2w --> two weeks from today
  12864. ++5 --> five days from default date
  12865. The function understands only English month and weekday abbreviations.
  12866. While prompting, a calendar is popped up - you can also select the
  12867. date with the mouse (button 1). The calendar shows a period of three
  12868. months. To scroll it to other months, use the keys `>' and `<'.
  12869. If you don't like the calendar, turn it off with
  12870. (setq org-read-date-popup-calendar nil)
  12871. With optional argument TO-TIME, the date will immediately be converted
  12872. to an internal time.
  12873. With an optional argument WITH-TIME, the prompt will suggest to
  12874. also insert a time. Note that when WITH-TIME is not set, you can
  12875. still enter a time, and this function will inform the calling routine
  12876. about this change. The calling routine may then choose to change the
  12877. format used to insert the time stamp into the buffer to include the time.
  12878. With optional argument FROM-STRING, read from this string instead from
  12879. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  12880. the time/date that is used for everything that is not specified by the
  12881. user."
  12882. (require 'parse-time)
  12883. (let* ((org-with-time with-time)
  12884. (org-time-stamp-rounding-minutes
  12885. (if (equal org-with-time '(16))
  12886. '(0 0)
  12887. org-time-stamp-rounding-minutes))
  12888. (ct (org-current-time))
  12889. (org-def (or org-overriding-default-time default-time ct))
  12890. (org-defdecode (decode-time org-def))
  12891. (cur-frame (selected-frame))
  12892. (mouse-autoselect-window nil) ; Don't let the mouse jump
  12893. (calendar-setup
  12894. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  12895. (calendar-move-hook nil)
  12896. (calendar-view-diary-initially-flag nil)
  12897. (calendar-view-holidays-initially-flag nil)
  12898. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  12899. ;; Rationalize `org-def' and `org-defdecode', if required.
  12900. (when (< (nth 2 org-defdecode) org-extend-today-until)
  12901. (setf (nth 2 org-defdecode) -1)
  12902. (setf (nth 1 org-defdecode) 59)
  12903. (setq org-def (apply #'encode-time org-defdecode))
  12904. (setq org-defdecode (decode-time org-def)))
  12905. (let* ((timestr (format-time-string
  12906. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  12907. org-def))
  12908. (prompt (concat (if prompt (concat prompt " ") "")
  12909. (format "Date+time [%s]: " timestr))))
  12910. (cond
  12911. (from-string (setq ans from-string))
  12912. (org-read-date-popup-calendar
  12913. (save-excursion
  12914. (save-window-excursion
  12915. (calendar)
  12916. (when (eq calendar-setup 'calendar-only)
  12917. (setq cal-frame
  12918. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  12919. (select-frame cal-frame))
  12920. (org-eval-in-calendar '(setq cursor-type nil) t)
  12921. (unwind-protect
  12922. (progn
  12923. (calendar-forward-day (- (time-to-days org-def)
  12924. (calendar-absolute-from-gregorian
  12925. (calendar-current-date))))
  12926. (org-eval-in-calendar nil t)
  12927. (let* ((old-map (current-local-map))
  12928. (map (copy-keymap calendar-mode-map))
  12929. (minibuffer-local-map
  12930. (copy-keymap org-read-date-minibuffer-local-map)))
  12931. (org-defkey map (kbd "RET") 'org-calendar-select)
  12932. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  12933. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  12934. (unwind-protect
  12935. (progn
  12936. (use-local-map map)
  12937. (setq org-read-date-inactive inactive)
  12938. (add-hook 'post-command-hook 'org-read-date-display)
  12939. (setq org-ans0
  12940. (read-string prompt
  12941. default-input
  12942. 'org-read-date-history
  12943. nil))
  12944. ;; org-ans0: from prompt
  12945. ;; org-ans1: from mouse click
  12946. ;; org-ans2: from calendar motion
  12947. (setq ans
  12948. (concat org-ans0 " " (or org-ans1 org-ans2))))
  12949. (remove-hook 'post-command-hook 'org-read-date-display)
  12950. (use-local-map old-map)
  12951. (when org-read-date-overlay
  12952. (delete-overlay org-read-date-overlay)
  12953. (setq org-read-date-overlay nil)))))
  12954. (bury-buffer "*Calendar*")
  12955. (when cal-frame
  12956. (delete-frame cal-frame)
  12957. (select-frame-set-input-focus cur-frame))))))
  12958. (t ; Naked prompt only
  12959. (unwind-protect
  12960. (setq ans (read-string prompt default-input
  12961. 'org-read-date-history timestr))
  12962. (when org-read-date-overlay
  12963. (delete-overlay org-read-date-overlay)
  12964. (setq org-read-date-overlay nil))))))
  12965. (setq final (org-read-date-analyze ans org-def org-defdecode))
  12966. (when org-read-date-analyze-forced-year
  12967. (message "Year was forced into %s"
  12968. (if org-read-date-force-compatible-dates
  12969. "compatible range (1970-2037)"
  12970. "range representable on this machine"))
  12971. (ding))
  12972. (setq final (apply #'encode-time final))
  12973. (setq org-read-date-final-answer ans)
  12974. (if to-time
  12975. final
  12976. ;; This round-trip gets rid of 34th of August and stuff like that....
  12977. (setq final (decode-time final))
  12978. (if (and (boundp 'org-time-was-given) org-time-was-given)
  12979. (format "%04d-%02d-%02d %02d:%02d"
  12980. (nth 5 final) (nth 4 final) (nth 3 final)
  12981. (nth 2 final) (nth 1 final))
  12982. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  12983. (defun org-read-date-display ()
  12984. "Display the current date prompt interpretation in the minibuffer."
  12985. (when org-read-date-display-live
  12986. (when org-read-date-overlay
  12987. (delete-overlay org-read-date-overlay))
  12988. (when (minibufferp (current-buffer))
  12989. (save-excursion
  12990. (end-of-line 1)
  12991. (while (not (equal (buffer-substring
  12992. (max (point-min) (- (point) 4)) (point))
  12993. " "))
  12994. (insert " ")))
  12995. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  12996. " " (or org-ans1 org-ans2)))
  12997. (org-end-time-was-given nil)
  12998. (f (org-read-date-analyze ans org-def org-defdecode))
  12999. (fmts (if org-display-custom-times
  13000. org-time-stamp-custom-formats
  13001. org-time-stamp-formats))
  13002. (fmt (if (or org-with-time
  13003. (and (boundp 'org-time-was-given) org-time-was-given))
  13004. (cdr fmts)
  13005. (car fmts)))
  13006. (txt (format-time-string fmt (apply #'encode-time f)))
  13007. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  13008. (txt (concat "=> " txt)))
  13009. (when (and org-end-time-was-given
  13010. (string-match org-plain-time-of-day-regexp txt))
  13011. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  13012. org-end-time-was-given
  13013. (substring txt (match-end 0)))))
  13014. (when org-read-date-analyze-futurep
  13015. (setq txt (concat txt " (=>F)")))
  13016. (setq org-read-date-overlay
  13017. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  13018. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  13019. (defun org-read-date-analyze (ans def defdecode)
  13020. "Analyze the combined answer of the date prompt."
  13021. ;; FIXME: cleanup and comment
  13022. (let ((org-def def)
  13023. (org-defdecode defdecode)
  13024. (nowdecode (decode-time))
  13025. delta deltan deltaw deltadef year month day
  13026. hour minute second wday pm h2 m2 tl wday1
  13027. iso-year iso-weekday iso-week iso-date futurep kill-year)
  13028. (setq org-read-date-analyze-futurep nil
  13029. org-read-date-analyze-forced-year nil)
  13030. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  13031. (setq ans "+0"))
  13032. (when (setq delta (org-read-date-get-relative ans nil org-def))
  13033. (setq ans (replace-match "" t t ans)
  13034. deltan (car delta)
  13035. deltaw (nth 1 delta)
  13036. deltadef (nth 2 delta)))
  13037. ;; Check if there is an iso week date in there. If yes, store the
  13038. ;; info and postpone interpreting it until the rest of the parsing
  13039. ;; is done.
  13040. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  13041. (setq iso-year (when (match-end 1)
  13042. (org-small-year-to-year
  13043. (string-to-number (match-string 1 ans))))
  13044. iso-weekday (when (match-end 3)
  13045. (string-to-number (match-string 3 ans)))
  13046. iso-week (string-to-number (match-string 2 ans)))
  13047. (setq ans (replace-match "" t t ans)))
  13048. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  13049. (when (string-match
  13050. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  13051. (setq year (if (match-end 2)
  13052. (string-to-number (match-string 2 ans))
  13053. (progn (setq kill-year t)
  13054. (string-to-number (format-time-string "%Y"))))
  13055. month (string-to-number (match-string 3 ans))
  13056. day (string-to-number (match-string 4 ans)))
  13057. (setq year (org-small-year-to-year year))
  13058. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  13059. t nil ans)))
  13060. ;; Help matching dotted european dates
  13061. (when (string-match
  13062. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  13063. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  13064. (setq kill-year t)
  13065. (string-to-number (format-time-string "%Y")))
  13066. day (string-to-number (match-string 1 ans))
  13067. month (string-to-number (match-string 2 ans))
  13068. ans (replace-match (format "%04d-%02d-%02d" year month day)
  13069. t nil ans)))
  13070. ;; Help matching american dates, like 5/30 or 5/30/7
  13071. (when (string-match
  13072. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  13073. (setq year (if (match-end 4)
  13074. (string-to-number (match-string 4 ans))
  13075. (progn (setq kill-year t)
  13076. (string-to-number (format-time-string "%Y"))))
  13077. month (string-to-number (match-string 1 ans))
  13078. day (string-to-number (match-string 2 ans)))
  13079. (setq year (org-small-year-to-year year))
  13080. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  13081. t nil ans)))
  13082. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  13083. ;; If there is a time with am/pm, and *no* time without it, we convert
  13084. ;; so that matching will be successful.
  13085. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  13086. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  13087. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  13088. (setq hour (string-to-number (match-string 1 ans))
  13089. minute (if (match-end 3)
  13090. (string-to-number (match-string 3 ans))
  13091. 0)
  13092. pm (equal ?p
  13093. (string-to-char (downcase (match-string 4 ans)))))
  13094. (if (and (= hour 12) (not pm))
  13095. (setq hour 0)
  13096. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  13097. (setq ans (replace-match (format "%02d:%02d" hour minute)
  13098. t t ans))))
  13099. ;; Help matching HHhMM times, similarly as for am/pm times.
  13100. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  13101. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  13102. (string-match "\\(?:\\(?1:[012]?[0-9]\\)?h\\(?2:[0-5][0-9]\\)\\)\\|\\(?:\\(?1:[012]?[0-9]\\)h\\(?2:[0-5][0-9]\\)?\\)\\>" ans))
  13103. (setq hour (if (match-end 1)
  13104. (string-to-number (match-string 1 ans))
  13105. 0)
  13106. minute (if (match-end 2)
  13107. (string-to-number (match-string 2 ans))
  13108. 0))
  13109. (setq ans (replace-match (format "%02d:%02d" hour minute)
  13110. t t ans))))
  13111. ;; Check if a time range is given as a duration
  13112. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  13113. (setq hour (string-to-number (match-string 1 ans))
  13114. h2 (+ hour (string-to-number (match-string 3 ans)))
  13115. minute (string-to-number (match-string 2 ans))
  13116. m2 (+ minute (if (match-end 5) (string-to-number
  13117. (match-string 5 ans))0)))
  13118. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  13119. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  13120. t t ans)))
  13121. ;; Check if there is a time range
  13122. (when (boundp 'org-end-time-was-given)
  13123. (setq org-time-was-given nil)
  13124. (when (and (string-match org-plain-time-of-day-regexp ans)
  13125. (match-end 8))
  13126. (setq org-end-time-was-given (match-string 8 ans))
  13127. (setq ans (concat (substring ans 0 (match-beginning 7))
  13128. (substring ans (match-end 7))))))
  13129. (setq tl (parse-time-string ans)
  13130. day (or (nth 3 tl) (nth 3 org-defdecode))
  13131. month
  13132. (cond ((nth 4 tl))
  13133. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  13134. ;; Day was specified. Make sure DAY+MONTH
  13135. ;; combination happens in the future.
  13136. ((nth 3 tl)
  13137. (setq futurep t)
  13138. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  13139. (nth 4 nowdecode)))
  13140. (t (nth 4 org-defdecode)))
  13141. year
  13142. (cond ((and (not kill-year) (nth 5 tl)))
  13143. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  13144. ;; Month was guessed in the future and is at least
  13145. ;; equal to NOWDECODE's. Fix year accordingly.
  13146. (futurep
  13147. (if (or (> month (nth 4 nowdecode))
  13148. (>= day (nth 3 nowdecode)))
  13149. (nth 5 nowdecode)
  13150. (1+ (nth 5 nowdecode))))
  13151. ;; Month was specified. Make sure MONTH+YEAR
  13152. ;; combination happens in the future.
  13153. ((nth 4 tl)
  13154. (setq futurep t)
  13155. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  13156. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  13157. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  13158. (t (nth 5 nowdecode))))
  13159. (t (nth 5 org-defdecode)))
  13160. hour (or (nth 2 tl) (nth 2 org-defdecode))
  13161. minute (or (nth 1 tl) (nth 1 org-defdecode))
  13162. second (or (nth 0 tl) 0)
  13163. wday (nth 6 tl))
  13164. (when (and (eq org-read-date-prefer-future 'time)
  13165. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  13166. (equal day (nth 3 nowdecode))
  13167. (equal month (nth 4 nowdecode))
  13168. (equal year (nth 5 nowdecode))
  13169. (nth 2 tl)
  13170. (or (< (nth 2 tl) (nth 2 nowdecode))
  13171. (and (= (nth 2 tl) (nth 2 nowdecode))
  13172. (nth 1 tl)
  13173. (< (nth 1 tl) (nth 1 nowdecode)))))
  13174. (setq day (1+ day)
  13175. futurep t))
  13176. ;; Special date definitions below
  13177. (cond
  13178. (iso-week
  13179. ;; There was an iso week
  13180. (require 'cal-iso)
  13181. (setq futurep nil)
  13182. (setq year (or iso-year year)
  13183. day (or iso-weekday wday 1)
  13184. wday nil ; to make sure that the trigger below does not match
  13185. iso-date (calendar-gregorian-from-absolute
  13186. (calendar-iso-to-absolute
  13187. (list iso-week day year))))
  13188. ; FIXME: Should we also push ISO weeks into the future?
  13189. ; (when (and org-read-date-prefer-future
  13190. ; (not iso-year)
  13191. ; (< (calendar-absolute-from-gregorian iso-date)
  13192. ; (time-to-days nil)))
  13193. ; (setq year (1+ year)
  13194. ; iso-date (calendar-gregorian-from-absolute
  13195. ; (calendar-iso-to-absolute
  13196. ; (list iso-week day year)))))
  13197. (setq month (car iso-date)
  13198. year (nth 2 iso-date)
  13199. day (nth 1 iso-date)))
  13200. (deltan
  13201. (setq futurep nil)
  13202. (unless deltadef
  13203. (let ((now (decode-time)))
  13204. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  13205. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  13206. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  13207. ((equal deltaw "m") (setq month (+ month deltan)))
  13208. ((equal deltaw "y") (setq year (+ year deltan)))))
  13209. ((and wday (not (nth 3 tl)))
  13210. ;; Weekday was given, but no day, so pick that day in the week
  13211. ;; on or after the derived date.
  13212. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  13213. (unless (equal wday wday1)
  13214. (setq day (+ day (% (- wday wday1 -7) 7))))))
  13215. (when (and (boundp 'org-time-was-given)
  13216. (nth 2 tl))
  13217. (setq org-time-was-given t))
  13218. (when (< year 100) (setq year (+ 2000 year)))
  13219. ;; Check of the date is representable
  13220. (if org-read-date-force-compatible-dates
  13221. (progn
  13222. (when (< year 1970)
  13223. (setq year 1970 org-read-date-analyze-forced-year t))
  13224. (when (> year 2037)
  13225. (setq year 2037 org-read-date-analyze-forced-year t)))
  13226. (condition-case nil
  13227. (ignore (encode-time second minute hour day month year))
  13228. (error
  13229. (setq year (nth 5 org-defdecode))
  13230. (setq org-read-date-analyze-forced-year t))))
  13231. (setq org-read-date-analyze-futurep futurep)
  13232. (list second minute hour day month year)))
  13233. (defvar parse-time-weekdays)
  13234. (defun org-read-date-get-relative (s today default)
  13235. "Check string S for special relative date string.
  13236. TODAY and DEFAULT are internal times, for today and for a default.
  13237. Return shift list (N what def-flag)
  13238. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  13239. N is the number of WHATs to shift.
  13240. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  13241. the DEFAULT date rather than TODAY."
  13242. (require 'parse-time)
  13243. (when (and
  13244. (string-match
  13245. (concat
  13246. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  13247. "\\([0-9]+\\)?"
  13248. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  13249. "\\([ \t]\\|$\\)") s)
  13250. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  13251. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  13252. (string-to-char (substring (match-string 1 s) -1))
  13253. ?+))
  13254. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  13255. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  13256. (what (if (match-end 3) (match-string 3 s) "d"))
  13257. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  13258. (date (if rel default today))
  13259. (wday (nth 6 (decode-time date)))
  13260. delta)
  13261. (if wday1
  13262. (progn
  13263. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  13264. (when (= delta 0) (setq delta 7))
  13265. (when (= dir ?-)
  13266. (setq delta (- delta 7))
  13267. (when (= delta 0) (setq delta -7)))
  13268. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  13269. (list delta "d" rel))
  13270. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  13271. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  13272. "Turn a user-specified date into the internal representation.
  13273. The internal representation needed by the calendar is (month day year).
  13274. This is a wrapper to handle the brain-dead convention in calendar that
  13275. user function argument order change dependent on argument order."
  13276. (pcase calendar-date-style
  13277. (`american (list arg1 arg2 arg3))
  13278. (`european (list arg2 arg1 arg3))
  13279. (`iso (list arg2 arg3 arg1))))
  13280. (defun org-eval-in-calendar (form &optional keepdate)
  13281. "Eval FORM in the calendar window and return to current window.
  13282. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  13283. (let ((sf (selected-frame))
  13284. (sw (selected-window)))
  13285. (select-window (get-buffer-window "*Calendar*" t))
  13286. (eval form)
  13287. (when (and (not keepdate) (calendar-cursor-to-date))
  13288. (let* ((date (calendar-cursor-to-date))
  13289. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  13290. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  13291. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  13292. (select-window sw)
  13293. (select-frame-set-input-focus sf)))
  13294. (defun org-calendar-select ()
  13295. "Return to `org-read-date' with the date currently selected.
  13296. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  13297. (interactive)
  13298. (when (calendar-cursor-to-date)
  13299. (let* ((date (calendar-cursor-to-date))
  13300. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  13301. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  13302. (when (active-minibuffer-window) (exit-minibuffer))))
  13303. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  13304. "Insert a date stamp for the date given by the internal TIME.
  13305. See `format-time-string' for the format of TIME.
  13306. WITH-HM means use the stamp format that includes the time of the day.
  13307. INACTIVE means use square brackets instead of angular ones, so that the
  13308. stamp will not contribute to the agenda.
  13309. PRE and POST are optional strings to be inserted before and after the
  13310. stamp.
  13311. The command returns the inserted time stamp."
  13312. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  13313. stamp)
  13314. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  13315. (insert-before-markers (or pre ""))
  13316. (when (listp extra)
  13317. (setq extra (car extra))
  13318. (if (and (stringp extra)
  13319. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  13320. (setq extra (format "-%02d:%02d"
  13321. (string-to-number (match-string 1 extra))
  13322. (string-to-number (match-string 2 extra))))
  13323. (setq extra nil)))
  13324. (when extra
  13325. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  13326. (insert-before-markers (setq stamp (format-time-string fmt time)))
  13327. (insert-before-markers (or post ""))
  13328. (setq org-last-inserted-timestamp stamp)))
  13329. (defun org-toggle-time-stamp-overlays ()
  13330. "Toggle the use of custom time stamp formats."
  13331. (interactive)
  13332. (setq org-display-custom-times (not org-display-custom-times))
  13333. (unless org-display-custom-times
  13334. (let ((p (point-min)) (bmp (buffer-modified-p)))
  13335. (while (setq p (next-single-property-change p 'display))
  13336. (when (and (get-text-property p 'display)
  13337. (eq (get-text-property p 'face) 'org-date))
  13338. (remove-text-properties
  13339. p (setq p (next-single-property-change p 'display))
  13340. '(display t))))
  13341. (set-buffer-modified-p bmp)))
  13342. (org-restart-font-lock)
  13343. (setq org-table-may-need-update t)
  13344. (if org-display-custom-times
  13345. (message "Time stamps are overlaid with custom format")
  13346. (message "Time stamp overlays removed")))
  13347. (defun org-display-custom-time (beg end)
  13348. "Overlay modified time stamp format over timestamp between BEG and END."
  13349. (let* ((ts (buffer-substring beg end))
  13350. t1 with-hm tf time str (off 0))
  13351. (save-match-data
  13352. (setq t1 (org-parse-time-string ts t))
  13353. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  13354. (setq off (- (match-end 0) (match-beginning 0)))))
  13355. (setq end (- end off))
  13356. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  13357. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  13358. time (org-fix-decoded-time t1)
  13359. str (org-add-props
  13360. (format-time-string
  13361. (substring tf 1 -1) (apply 'encode-time time))
  13362. nil 'mouse-face 'highlight))
  13363. (put-text-property beg end 'display str)))
  13364. (defun org-fix-decoded-time (time)
  13365. "Set 0 instead of nil for the first 6 elements of time.
  13366. Don't touch the rest."
  13367. (let ((n 0))
  13368. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  13369. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  13370. "Difference between TIMESTAMP-STRING and now in days.
  13371. If SECONDS is non-nil, return the difference in seconds."
  13372. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  13373. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  13374. (funcall fdiff nil))))
  13375. (defun org-deadline-close-p (timestamp-string &optional ndays)
  13376. "Is the time in TIMESTAMP-STRING close to the current date?"
  13377. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  13378. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  13379. (not (org-entry-is-done-p))))
  13380. (defun org-get-wdays (ts &optional delay zero-delay)
  13381. "Get the deadline lead time appropriate for timestring TS.
  13382. When DELAY is non-nil, get the delay time for scheduled items
  13383. instead of the deadline lead time. When ZERO-DELAY is non-nil
  13384. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  13385. don't try to find the delay cookie in the scheduled timestamp."
  13386. (let ((tv (if delay org-scheduled-delay-days
  13387. org-deadline-warning-days)))
  13388. (cond
  13389. ((or (and delay (< tv 0))
  13390. (and delay zero-delay (<= tv 0))
  13391. (and (not delay) (<= tv 0)))
  13392. ;; Enforce this value no matter what
  13393. (- tv))
  13394. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  13395. ;; lead time is specified.
  13396. (floor (* (string-to-number (match-string 1 ts))
  13397. (cdr (assoc (match-string 2 ts)
  13398. '(("d" . 1) ("w" . 7)
  13399. ("m" . 30.4) ("y" . 365.25)
  13400. ("h" . 0.041667)))))))
  13401. ;; go for the default.
  13402. (t tv))))
  13403. (defun org-calendar-select-mouse (ev)
  13404. "Return to `org-read-date' with the date currently selected.
  13405. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  13406. (interactive "e")
  13407. (mouse-set-point ev)
  13408. (when (calendar-cursor-to-date)
  13409. (let* ((date (calendar-cursor-to-date))
  13410. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  13411. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  13412. (when (active-minibuffer-window) (exit-minibuffer))))
  13413. (defun org-check-deadlines (ndays)
  13414. "Check if there are any deadlines due or past due.
  13415. A deadline is considered due if it happens within `org-deadline-warning-days'
  13416. days from today's date. If the deadline appears in an entry marked DONE,
  13417. it is not shown. A numeric prefix argument NDAYS can be used to test that
  13418. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  13419. are shown."
  13420. (interactive "P")
  13421. (let* ((org-warn-days
  13422. (cond
  13423. ((equal ndays '(4)) 100000)
  13424. (ndays (prefix-numeric-value ndays))
  13425. (t (abs org-deadline-warning-days))))
  13426. (case-fold-search nil)
  13427. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  13428. (callback
  13429. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  13430. (message "%d deadlines past-due or due within %d days"
  13431. (org-occur regexp nil callback)
  13432. org-warn-days)))
  13433. (defsubst org-re-timestamp (type)
  13434. "Return a regexp for timestamp TYPE.
  13435. Allowed values for TYPE are:
  13436. all: all timestamps
  13437. active: only active timestamps (<...>)
  13438. inactive: only inactive timestamps ([...])
  13439. scheduled: only scheduled timestamps
  13440. deadline: only deadline timestamps
  13441. closed: only closed time-stamps
  13442. When TYPE is nil, fall back on returning a regexp that matches
  13443. both scheduled and deadline timestamps."
  13444. (cl-case type
  13445. (all org-ts-regexp-both)
  13446. (active org-ts-regexp)
  13447. (inactive org-ts-regexp-inactive)
  13448. (scheduled org-scheduled-time-regexp)
  13449. (deadline org-deadline-time-regexp)
  13450. (closed org-closed-time-regexp)
  13451. (otherwise
  13452. (concat "\\<"
  13453. (regexp-opt (list org-deadline-string org-scheduled-string))
  13454. " *<\\([^>]+\\)>"))))
  13455. (defun org-check-before-date (d)
  13456. "Check if there are deadlines or scheduled entries before date D."
  13457. (interactive (list (org-read-date)))
  13458. (let* ((case-fold-search nil)
  13459. (regexp (org-re-timestamp org-ts-type))
  13460. (ts-type org-ts-type)
  13461. (callback
  13462. (lambda ()
  13463. (let ((match (match-string 1)))
  13464. (and (if (memq ts-type '(active inactive all))
  13465. (eq (org-element-type (save-excursion
  13466. (backward-char)
  13467. (org-element-context)))
  13468. 'timestamp)
  13469. (org-at-planning-p))
  13470. (time-less-p
  13471. (org-time-string-to-time match)
  13472. (org-time-string-to-time d)))))))
  13473. (message "%d entries before %s"
  13474. (org-occur regexp nil callback)
  13475. d)))
  13476. (defun org-check-after-date (d)
  13477. "Check if there are deadlines or scheduled entries after date D."
  13478. (interactive (list (org-read-date)))
  13479. (let* ((case-fold-search nil)
  13480. (regexp (org-re-timestamp org-ts-type))
  13481. (ts-type org-ts-type)
  13482. (callback
  13483. (lambda ()
  13484. (let ((match (match-string 1)))
  13485. (and (if (memq ts-type '(active inactive all))
  13486. (eq (org-element-type (save-excursion
  13487. (backward-char)
  13488. (org-element-context)))
  13489. 'timestamp)
  13490. (org-at-planning-p))
  13491. (not (time-less-p
  13492. (org-time-string-to-time match)
  13493. (org-time-string-to-time d))))))))
  13494. (message "%d entries after %s"
  13495. (org-occur regexp nil callback)
  13496. d)))
  13497. (defun org-check-dates-range (start-date end-date)
  13498. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  13499. (interactive (list (org-read-date nil nil nil "Range starts")
  13500. (org-read-date nil nil nil "Range end")))
  13501. (let ((case-fold-search nil)
  13502. (regexp (org-re-timestamp org-ts-type))
  13503. (callback
  13504. (let ((type org-ts-type))
  13505. (lambda ()
  13506. (let ((match (match-string 1)))
  13507. (and
  13508. (if (memq type '(active inactive all))
  13509. (eq (org-element-type (save-excursion
  13510. (backward-char)
  13511. (org-element-context)))
  13512. 'timestamp)
  13513. (org-at-planning-p))
  13514. (not (time-less-p
  13515. (org-time-string-to-time match)
  13516. (org-time-string-to-time start-date)))
  13517. (time-less-p
  13518. (org-time-string-to-time match)
  13519. (org-time-string-to-time end-date))))))))
  13520. (message "%d entries between %s and %s"
  13521. (org-occur regexp nil callback) start-date end-date)))
  13522. (defun org-evaluate-time-range (&optional to-buffer)
  13523. "Evaluate a time range by computing the difference between start and end.
  13524. Normally the result is just printed in the echo area, but with prefix arg
  13525. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  13526. If the time range is actually in a table, the result is inserted into the
  13527. next column.
  13528. For time difference computation, a year is assumed to be exactly 365
  13529. days in order to avoid rounding problems."
  13530. (interactive "P")
  13531. (or
  13532. (org-clock-update-time-maybe)
  13533. (save-excursion
  13534. (unless (org-at-date-range-p t)
  13535. (goto-char (point-at-bol))
  13536. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  13537. (unless (org-at-date-range-p t)
  13538. (user-error "Not at a time-stamp range, and none found in current line")))
  13539. (let* ((ts1 (match-string 1))
  13540. (ts2 (match-string 2))
  13541. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  13542. (match-end (match-end 0))
  13543. (time1 (org-time-string-to-time ts1))
  13544. (time2 (org-time-string-to-time ts2))
  13545. (diff (abs (float-time (time-subtract time2 time1))))
  13546. (negative (time-less-p time2 time1))
  13547. ;; (ys (floor (* 365 24 60 60)))
  13548. (ds (* 24 60 60))
  13549. (hs (* 60 60))
  13550. (fy "%dy %dd %02d:%02d")
  13551. (fy1 "%dy %dd")
  13552. (fd "%dd %02d:%02d")
  13553. (fd1 "%dd")
  13554. (fh "%02d:%02d")
  13555. y d h m align)
  13556. (if havetime
  13557. (setq ; y (floor diff ys) diff (mod diff ys)
  13558. y 0
  13559. d (floor diff ds) diff (mod diff ds)
  13560. h (floor diff hs) diff (mod diff hs)
  13561. m (floor diff 60))
  13562. (setq ; y (floor diff ys) diff (mod diff ys)
  13563. y 0
  13564. d (round diff ds)
  13565. h 0 m 0))
  13566. (if (not to-buffer)
  13567. (message "%s" (org-make-tdiff-string y d h m))
  13568. (if (org-at-table-p)
  13569. (progn
  13570. (goto-char match-end)
  13571. (setq align t)
  13572. (and (looking-at " *|") (goto-char (match-end 0))))
  13573. (goto-char match-end))
  13574. (when (looking-at
  13575. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  13576. (replace-match ""))
  13577. (when negative (insert " -"))
  13578. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  13579. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  13580. (insert " " (format fh h m))))
  13581. (when align (org-table-align))
  13582. (message "Time difference inserted")))))
  13583. (defun org-make-tdiff-string (y d h m)
  13584. (let ((fmt "")
  13585. (l nil))
  13586. (when (> y 0)
  13587. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  13588. (push y l))
  13589. (when (> d 0)
  13590. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  13591. (push d l))
  13592. (when (> h 0)
  13593. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  13594. (push h l))
  13595. (when (> m 0)
  13596. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  13597. (push m l))
  13598. (apply 'format fmt (nreverse l))))
  13599. (defun org-time-string-to-time (s)
  13600. "Convert timestamp string S into internal time."
  13601. (apply #'encode-time (org-parse-time-string s)))
  13602. (defun org-time-string-to-seconds (s)
  13603. "Convert a timestamp string S into a number of seconds."
  13604. (float-time (org-time-string-to-time s)))
  13605. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  13606. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  13607. "Convert time stamp S to an absolute day number.
  13608. If DAYNR in non-nil, and there is a specifier for a cyclic time
  13609. stamp, get the closest date to DAYNR. If PREFER is
  13610. `past' (respectively `future') return a date past (respectively
  13611. after) or equal to DAYNR.
  13612. POS is the location of time stamp S, as a buffer position in
  13613. BUFFER.
  13614. Diary sexp timestamps are matched against DAYNR, when non-nil.
  13615. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  13616. signaled."
  13617. (cond
  13618. ((string-match "\\`%%\\((.*)\\)" s)
  13619. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  13620. ;; only able to match individual dates. If it fails, raise an
  13621. ;; error.
  13622. (if (and daynr
  13623. (org-diary-sexp-entry
  13624. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  13625. daynr
  13626. (signal 'org-diary-sexp-no-match (list s))))
  13627. (daynr (org-closest-date s daynr prefer))
  13628. (t (time-to-days
  13629. (condition-case errdata
  13630. (org-time-string-to-time s)
  13631. (error (error "Bad timestamp `%s'%s\nError was: %s"
  13632. s
  13633. (if (not (and buffer pos)) ""
  13634. (format-message " at %d in buffer `%s'" pos buffer))
  13635. (cdr errdata))))))))
  13636. (defun org-days-to-iso-week (days)
  13637. "Return the ISO week number."
  13638. (require 'cal-iso)
  13639. (car (calendar-iso-from-absolute days)))
  13640. (defun org-small-year-to-year (year)
  13641. "Convert 2-digit years into 4-digit years.
  13642. YEAR is expanded into one of the 30 next years, if possible, or
  13643. into a past one. Any year larger than 99 is returned unchanged."
  13644. (if (>= year 100) year
  13645. (let* ((current (string-to-number (format-time-string "%Y")))
  13646. (century (/ current 100))
  13647. (offset (- year (% current 100))))
  13648. (cond ((> offset 30) (+ (* (1- century) 100) year))
  13649. ((> offset -70) (+ (* century 100) year))
  13650. (t (+ (* (1+ century) 100) year))))))
  13651. (defun org-time-from-absolute (d)
  13652. "Return the time corresponding to date D.
  13653. D may be an absolute day number, or a calendar-type list (month day year)."
  13654. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  13655. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  13656. (defvar org-agenda-current-date)
  13657. (defun org-calendar-holiday ()
  13658. "List of holidays, for Diary display in Org mode."
  13659. (require 'holidays)
  13660. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  13661. (and hl (mapconcat #'identity hl "; "))))
  13662. (defun org-diary-sexp-entry (sexp entry d)
  13663. "Process a SEXP diary ENTRY for date D."
  13664. (require 'diary-lib)
  13665. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  13666. ;; dynamically.
  13667. (let* ((sexp `(let ((entry ,entry)
  13668. (date ',d))
  13669. ,(car (read-from-string sexp))))
  13670. (result (if calendar-debug-sexp (eval sexp)
  13671. (condition-case nil
  13672. (eval sexp)
  13673. (error
  13674. (beep)
  13675. (message "Bad sexp at line %d in %s: %s"
  13676. (org-current-line)
  13677. (buffer-file-name) sexp)
  13678. (sleep-for 2))))))
  13679. (cond ((stringp result) (split-string result "; "))
  13680. ((and (consp result)
  13681. (not (consp (cdr result)))
  13682. (stringp (cdr result))) (cdr result))
  13683. ((and (consp result)
  13684. (stringp (car result))) result)
  13685. (result entry))))
  13686. (defun org-diary-to-ical-string (frombuf)
  13687. "Get iCalendar entries from diary entries in buffer FROMBUF.
  13688. This uses the icalendar.el library."
  13689. (let* ((tmpdir temporary-file-directory)
  13690. (tmpfile (make-temp-name
  13691. (expand-file-name "orgics" tmpdir)))
  13692. buf rtn b e)
  13693. (with-current-buffer frombuf
  13694. (icalendar-export-region (point-min) (point-max) tmpfile)
  13695. (setq buf (find-buffer-visiting tmpfile))
  13696. (set-buffer buf)
  13697. (goto-char (point-min))
  13698. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  13699. (setq b (match-beginning 0)))
  13700. (goto-char (point-max))
  13701. (when (re-search-backward "^END:VEVENT" nil t)
  13702. (setq e (match-end 0)))
  13703. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  13704. (kill-buffer buf)
  13705. (delete-file tmpfile)
  13706. rtn))
  13707. (defun org-closest-date (start current prefer)
  13708. "Return closest date to CURRENT starting from START.
  13709. CURRENT and START are both time stamps.
  13710. When PREFER is `past', return a date that is either CURRENT or
  13711. past. When PREFER is `future', return a date that is either
  13712. CURRENT or future.
  13713. Only time stamps with a repeater are modified. Any other time
  13714. stamp stay unchanged. In any case, return value is an absolute
  13715. day number."
  13716. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  13717. ;; No repeater. Do not shift time stamp.
  13718. (time-to-days (org-time-string-to-time start))
  13719. (let ((value (string-to-number (match-string 1 start)))
  13720. (type (match-string 2 start)))
  13721. (if (= 0 value)
  13722. ;; Repeater with a 0-value is considered as void.
  13723. (time-to-days (org-time-string-to-time start))
  13724. (let* ((base (org-date-to-gregorian start))
  13725. (target (org-date-to-gregorian current))
  13726. (sday (calendar-absolute-from-gregorian base))
  13727. (cday (calendar-absolute-from-gregorian target))
  13728. n1 n2)
  13729. ;; If START is already past CURRENT, just return START.
  13730. (if (<= cday sday) sday
  13731. ;; Compute closest date before (N1) and closest date past
  13732. ;; (N2) CURRENT.
  13733. (pcase type
  13734. ("h"
  13735. (let ((missing-hours
  13736. (mod (+ (- (* 24 (- cday sday))
  13737. (nth 2 (org-parse-time-string start)))
  13738. org-extend-today-until)
  13739. value)))
  13740. (setf n1 (if (= missing-hours 0) cday
  13741. (- cday (1+ (/ missing-hours 24)))))
  13742. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  13743. ((or "d" "w")
  13744. (let ((value (if (equal type "w") (* 7 value) value)))
  13745. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  13746. (setf n2 (+ n1 value))))
  13747. ("m"
  13748. (let* ((add-months
  13749. (lambda (d n)
  13750. ;; Add N months to gregorian date D, i.e.,
  13751. ;; a list (MONTH DAY YEAR). Return a valid
  13752. ;; gregorian date.
  13753. (let ((m (+ (nth 0 d) n)))
  13754. (list (mod m 12)
  13755. (nth 1 d)
  13756. (+ (/ m 12) (nth 2 d))))))
  13757. (months ; Complete months to TARGET.
  13758. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  13759. (- (nth 0 target) (nth 0 base))
  13760. ;; If START's day is greater than
  13761. ;; TARGET's, remove incomplete month.
  13762. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  13763. value)
  13764. value))
  13765. (before (funcall add-months base months)))
  13766. (setf n1 (calendar-absolute-from-gregorian before))
  13767. (setf n2
  13768. (calendar-absolute-from-gregorian
  13769. (funcall add-months before value)))))
  13770. (_
  13771. (let* ((d (nth 1 base))
  13772. (m (nth 0 base))
  13773. (y (nth 2 base))
  13774. (years ; Complete years to TARGET.
  13775. (* (/ (- (nth 2 target)
  13776. y
  13777. ;; If START's month and day are
  13778. ;; greater than TARGET's, remove
  13779. ;; incomplete year.
  13780. (if (or (> (nth 0 target) m)
  13781. (and (= (nth 0 target) m)
  13782. (> (nth 1 target) d)))
  13783. 0
  13784. 1))
  13785. value)
  13786. value))
  13787. (before (list m d (+ y years))))
  13788. (setf n1 (calendar-absolute-from-gregorian before))
  13789. (setf n2 (calendar-absolute-from-gregorian
  13790. (list m d (+ (nth 2 before) value)))))))
  13791. ;; Handle PREFER parameter, if any.
  13792. (cond
  13793. ((eq prefer 'past) (if (= cday n2) n2 n1))
  13794. ((eq prefer 'future) (if (= cday n1) n1 n2))
  13795. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  13796. (defun org-date-to-gregorian (d)
  13797. "Turn any specification of date D into a Gregorian date for the calendar."
  13798. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  13799. ((and (listp d) (= (length d) 3)) d)
  13800. ((stringp d)
  13801. (let ((d (org-parse-time-string d)))
  13802. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  13803. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  13804. (defun org-timestamp-up (&optional arg)
  13805. "Increase the date item at the cursor by one.
  13806. If the cursor is on the year, change the year. If it is on the month,
  13807. the day or the time, change that. If the cursor is on the enclosing
  13808. bracket, change the timestamp type.
  13809. With prefix ARG, change by that many units."
  13810. (interactive "p")
  13811. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  13812. (defun org-timestamp-down (&optional arg)
  13813. "Decrease the date item at the cursor by one.
  13814. If the cursor is on the year, change the year. If it is on the month,
  13815. the day or the time, change that. If the cursor is on the enclosing
  13816. bracket, change the timestamp type.
  13817. With prefix ARG, change by that many units."
  13818. (interactive "p")
  13819. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  13820. (defun org-timestamp-up-day (&optional arg)
  13821. "Increase the date in the time stamp by one day.
  13822. With prefix ARG, change that many days."
  13823. (interactive "p")
  13824. (if (and (not (org-at-timestamp-p 'lax))
  13825. (org-at-heading-p))
  13826. (org-todo 'up)
  13827. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  13828. (defun org-timestamp-down-day (&optional arg)
  13829. "Decrease the date in the time stamp by one day.
  13830. With prefix ARG, change that many days."
  13831. (interactive "p")
  13832. (if (and (not (org-at-timestamp-p 'lax))
  13833. (org-at-heading-p))
  13834. (org-todo 'down)
  13835. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  13836. (defun org-at-timestamp-p (&optional extended)
  13837. "Non-nil if point is inside a timestamp.
  13838. By default, the function only consider syntactically valid active
  13839. timestamps. However, the caller may have a broader definition
  13840. for timestamps. As a consequence, optional argument EXTENDED can
  13841. be set to the following values
  13842. `inactive'
  13843. Include also syntactically valid inactive timestamps.
  13844. `agenda'
  13845. Include timestamps allowed in Agenda, i.e., those in
  13846. properties drawers, planning lines and clock lines.
  13847. `lax'
  13848. Ignore context. The function matches any part of the
  13849. document looking like a timestamp. This includes comments,
  13850. example blocks...
  13851. For backward-compatibility with Org 9.0, every other non-nil
  13852. value is equivalent to `inactive'.
  13853. When at a timestamp, return the position of the point as a symbol
  13854. among `bracket', `after', `year', `month', `hour', `minute',
  13855. `day' or a number of character from the last know part of the
  13856. time stamp.
  13857. When matching, the match groups are the following:
  13858. group 1: year
  13859. group 2: month
  13860. group 3: day number
  13861. group 4: day name
  13862. group 5: hours, if any
  13863. group 6: minutes, if any"
  13864. (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
  13865. (pos (point))
  13866. (match?
  13867. (let ((boundaries (org-in-regexp regexp)))
  13868. (save-match-data
  13869. (cond ((null boundaries) nil)
  13870. ((eq extended 'lax) t)
  13871. (t
  13872. (or (and (eq extended 'agenda)
  13873. (or (org-at-planning-p)
  13874. (org-at-property-p)
  13875. (and (bound-and-true-p
  13876. org-agenda-include-inactive-timestamps)
  13877. (org-at-clock-log-p))))
  13878. (eq 'timestamp
  13879. (save-excursion
  13880. (when (= pos (cdr boundaries)) (forward-char -1))
  13881. (org-element-type (org-element-context)))))))))))
  13882. (cond
  13883. ((not match?) nil)
  13884. ((= pos (match-beginning 0)) 'bracket)
  13885. ;; Distinguish location right before the closing bracket from
  13886. ;; right after it.
  13887. ((= pos (1- (match-end 0))) 'bracket)
  13888. ((= pos (match-end 0)) 'after)
  13889. ((org-pos-in-match-range pos 2) 'year)
  13890. ((org-pos-in-match-range pos 3) 'month)
  13891. ((org-pos-in-match-range pos 7) 'hour)
  13892. ((org-pos-in-match-range pos 8) 'minute)
  13893. ((or (org-pos-in-match-range pos 4)
  13894. (org-pos-in-match-range pos 5)) 'day)
  13895. ((and (> pos (or (match-end 8) (match-end 5)))
  13896. (< pos (match-end 0)))
  13897. (- pos (or (match-end 8) (match-end 5))))
  13898. (t 'day))))
  13899. (defun org-toggle-timestamp-type ()
  13900. "Toggle the type (<active> or [inactive]) of a time stamp."
  13901. (interactive)
  13902. (when (org-at-timestamp-p 'lax)
  13903. (let ((beg (match-beginning 0)) (end (match-end 0))
  13904. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  13905. (save-excursion
  13906. (goto-char beg)
  13907. (while (re-search-forward "[][<>]" end t)
  13908. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  13909. t t)))
  13910. (message "Timestamp is now %sactive"
  13911. (if (equal (char-after beg) ?<) "" "in")))))
  13912. (defun org-at-clock-log-p ()
  13913. "Non-nil if point is on a clock log line."
  13914. (and (org-match-line org-clock-line-re)
  13915. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  13916. (defvar org-clock-history) ; defined in org-clock.el
  13917. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  13918. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  13919. "Change the date in the time stamp at point.
  13920. The date is changed by N times WHAT. WHAT can be `day', `month',
  13921. `year', `hour', or `minute'. If WHAT is not given, the cursor
  13922. position in the timestamp determines what is changed.
  13923. When optional argument UPDOWN is non-nil, minutes are rounded
  13924. according to `org-time-stamp-rounding-minutes'.
  13925. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like
  13926. \"--2d\"."
  13927. (let ((origin (point))
  13928. (timestamp? (org-at-timestamp-p 'lax))
  13929. origin-cat
  13930. with-hm inactive
  13931. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  13932. extra rem
  13933. ts time time0 fixnext clrgx)
  13934. (unless timestamp? (user-error "Not at a timestamp"))
  13935. (if (and (not what) (eq timestamp? 'bracket))
  13936. (org-toggle-timestamp-type)
  13937. ;; Point isn't on brackets. Remember the part of the time-stamp
  13938. ;; the point was in. Indeed, size of time-stamps may change,
  13939. ;; but point must be kept in the same category nonetheless.
  13940. (setq origin-cat timestamp?)
  13941. (when (and (not what) (not (eq timestamp? 'day))
  13942. org-display-custom-times
  13943. (get-text-property (point) 'display)
  13944. (not (get-text-property (1- (point)) 'display)))
  13945. (setq timestamp? 'day))
  13946. (setq timestamp? (or what timestamp?)
  13947. inactive (= (char-after (match-beginning 0)) ?\[)
  13948. ts (match-string 0))
  13949. (replace-match "")
  13950. (when (string-match
  13951. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  13952. ts)
  13953. (setq extra (match-string 1 ts))
  13954. (when suppress-tmp-delay
  13955. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  13956. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  13957. (setq with-hm t))
  13958. (setq time0 (org-parse-time-string ts))
  13959. (when (and updown
  13960. (eq timestamp? 'minute)
  13961. (not current-prefix-arg))
  13962. ;; This looks like s-up and s-down. Change by one rounding step.
  13963. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  13964. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  13965. (setcar (cdr time0) (+ (nth 1 time0)
  13966. (if (> n 0) (- rem) (- dm rem))))))
  13967. (setq time
  13968. (apply #'encode-time
  13969. (or (car time0) 0)
  13970. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  13971. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  13972. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  13973. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  13974. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  13975. (nthcdr 6 time0)))
  13976. (when (and (memq timestamp? '(hour minute))
  13977. extra
  13978. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  13979. (setq extra (org-modify-ts-extra
  13980. extra
  13981. (if (eq timestamp? 'hour) 2 5)
  13982. n dm)))
  13983. (when (integerp timestamp?)
  13984. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  13985. (when (eq what 'calendar)
  13986. (let ((cal-date (org-get-date-from-calendar)))
  13987. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  13988. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  13989. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  13990. (setcar time0 (or (car time0) 0))
  13991. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  13992. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  13993. (setq time (apply 'encode-time time0))))
  13994. ;; Insert the new time-stamp, and ensure point stays in the same
  13995. ;; category as before (i.e. not after the last position in that
  13996. ;; category).
  13997. (let ((pos (point)))
  13998. ;; Stay before inserted string. `save-excursion' is of no use.
  13999. (setq org-last-changed-timestamp
  14000. (org-insert-time-stamp time with-hm inactive nil nil extra))
  14001. (goto-char pos))
  14002. (save-match-data
  14003. (looking-at org-ts-regexp3)
  14004. (goto-char
  14005. (pcase origin-cat
  14006. ;; `day' category ends before `hour' if any, or at the end
  14007. ;; of the day name.
  14008. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  14009. (`hour (min (match-end 7) origin))
  14010. (`minute (min (1- (match-end 8)) origin))
  14011. ((pred integerp) (min (1- (match-end 0)) origin))
  14012. ;; Point was right after the time-stamp. However, the
  14013. ;; time-stamp length might have changed, so refer to
  14014. ;; (match-end 0) instead.
  14015. (`after (match-end 0))
  14016. ;; `year' and `month' have both fixed size: point couldn't
  14017. ;; have moved into another part.
  14018. (_ origin))))
  14019. ;; Update clock if on a CLOCK line.
  14020. (org-clock-update-time-maybe)
  14021. ;; Maybe adjust the closest clock in `org-clock-history'
  14022. (when org-clock-adjust-closest
  14023. (if (not (and (org-at-clock-log-p)
  14024. (< 1 (length (delq nil (mapcar 'marker-position
  14025. org-clock-history))))))
  14026. (message "No clock to adjust")
  14027. (cond ((save-excursion ; fix previous clock?
  14028. (re-search-backward org-ts-regexp0 nil t)
  14029. (looking-back (concat org-clock-string " \\[")
  14030. (line-beginning-position)))
  14031. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  14032. ((save-excursion ; fix next clock?
  14033. (re-search-backward org-ts-regexp0 nil t)
  14034. (looking-at (concat org-ts-regexp0 "\\] =>")))
  14035. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  14036. (save-window-excursion
  14037. ;; Find closest clock to point, adjust the previous/next one in history
  14038. (let* ((p (save-excursion (org-back-to-heading t)))
  14039. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  14040. (clfixnth
  14041. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  14042. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  14043. (if (not clfixpos)
  14044. (message "No clock to adjust")
  14045. (save-excursion
  14046. (org-goto-marker-or-bmk clfixpos)
  14047. (org-show-subtree)
  14048. (when (re-search-forward clrgx nil t)
  14049. (goto-char (match-beginning 1))
  14050. (let (org-clock-adjust-closest)
  14051. (org-timestamp-change n timestamp? updown))
  14052. (message "Clock adjusted in %s for heading: %s"
  14053. (file-name-nondirectory (buffer-file-name))
  14054. (org-get-heading t t)))))))))
  14055. ;; Try to recenter the calendar window, if any.
  14056. (when (and org-calendar-follow-timestamp-change
  14057. (get-buffer-window "*Calendar*" t)
  14058. (memq timestamp? '(day month year)))
  14059. (org-recenter-calendar (time-to-days time))))))
  14060. (defun org-modify-ts-extra (s pos n dm)
  14061. "Change the different parts of the lead-time and repeat fields in timestamp."
  14062. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  14063. ng h m new rem)
  14064. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  14065. (cond
  14066. ((or (org-pos-in-match-range pos 2)
  14067. (org-pos-in-match-range pos 3))
  14068. (setq m (string-to-number (match-string 3 s))
  14069. h (string-to-number (match-string 2 s)))
  14070. (if (org-pos-in-match-range pos 2)
  14071. (setq h (+ h n))
  14072. (setq n (* dm (with-no-warnings (cl-signum n))))
  14073. (unless (= 0 (setq rem (% m dm)))
  14074. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  14075. (setq m (+ m n)))
  14076. (when (< m 0) (setq m (+ m 60) h (1- h)))
  14077. (when (> m 59) (setq m (- m 60) h (1+ h)))
  14078. (setq h (mod h 24))
  14079. (setq ng 1 new (format "-%02d:%02d" h m)))
  14080. ((org-pos-in-match-range pos 6)
  14081. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  14082. ((org-pos-in-match-range pos 5)
  14083. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  14084. ((org-pos-in-match-range pos 9)
  14085. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  14086. ((org-pos-in-match-range pos 8)
  14087. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  14088. (when ng
  14089. (setq s (concat
  14090. (substring s 0 (match-beginning ng))
  14091. new
  14092. (substring s (match-end ng))))))
  14093. s))
  14094. (defun org-recenter-calendar (d)
  14095. "If the calendar is visible, recenter it to date D."
  14096. (let ((cwin (get-buffer-window "*Calendar*" t)))
  14097. (when cwin
  14098. (let ((calendar-move-hook nil))
  14099. (with-selected-window cwin
  14100. (calendar-goto-date
  14101. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  14102. (defun org-goto-calendar (&optional arg)
  14103. "Go to the Emacs calendar at the current date.
  14104. If there is a time stamp in the current line, go to that date.
  14105. A prefix ARG can be used to force the current date."
  14106. (interactive "P")
  14107. (let ((calendar-move-hook nil)
  14108. (calendar-view-holidays-initially-flag nil)
  14109. (calendar-view-diary-initially-flag nil)
  14110. diff)
  14111. (when (or (org-at-timestamp-p 'lax)
  14112. (org-match-line (concat ".*" org-ts-regexp)))
  14113. (let ((d1 (time-to-days nil))
  14114. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  14115. (setq diff (- d2 d1))))
  14116. (calendar)
  14117. (calendar-goto-today)
  14118. (when (and diff (not arg)) (calendar-forward-day diff))))
  14119. (defun org-get-date-from-calendar ()
  14120. "Return a list (month day year) of date at point in calendar."
  14121. (with-current-buffer "*Calendar*"
  14122. (save-match-data
  14123. (calendar-cursor-to-date))))
  14124. (defun org-date-from-calendar ()
  14125. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  14126. If there is already a time stamp at the cursor position, update it."
  14127. (interactive)
  14128. (if (org-at-timestamp-p 'lax)
  14129. (org-timestamp-change 0 'calendar)
  14130. (let ((cal-date (org-get-date-from-calendar)))
  14131. (org-insert-time-stamp
  14132. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  14133. (defcustom org-image-actual-width t
  14134. "When non-nil, use the actual width of images when inlining them.
  14135. When set to a number, use imagemagick (when available) to set the
  14136. image's width to this value.
  14137. When set to a number in a list, try to get the width from any
  14138. #+ATTR.* keyword if it matches a width specification like
  14139. #+ATTR_HTML: :width 300px
  14140. and fall back on that number if none is found.
  14141. When set to nil, try to get the width from an #+ATTR.* keyword
  14142. and fall back on the original width if none is found.
  14143. When set to any other non-nil value, always use the image width.
  14144. This requires Emacs >= 24.1, built with imagemagick support."
  14145. :group 'org-appearance
  14146. :version "24.4"
  14147. :package-version '(Org . "8.0")
  14148. :type '(choice
  14149. (const :tag "Use the image width" t)
  14150. (integer :tag "Use a number of pixels")
  14151. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  14152. (const :tag "Use #+ATTR* or don't resize" nil)))
  14153. (defcustom org-agenda-inhibit-startup nil
  14154. "Inhibit startup when preparing agenda buffers.
  14155. When this variable is t, the initialization of the Org agenda
  14156. buffers is inhibited: e.g. the visibility state is not set, the
  14157. tables are not re-aligned, etc."
  14158. :type 'boolean
  14159. :version "24.3"
  14160. :group 'org-agenda)
  14161. (defcustom org-agenda-ignore-properties nil
  14162. "Avoid updating text properties when building the agenda.
  14163. Properties are used to prepare buffers for effort estimates,
  14164. appointments, statistics and subtree-local categories.
  14165. If you don't use these in the agenda, you can add them to this
  14166. list and agenda building will be a bit faster.
  14167. The value is a list, with zero or more of the symbols `effort', `appt',
  14168. `stats' or `category'."
  14169. :type '(set :greedy t
  14170. (const effort)
  14171. (const appt)
  14172. (const stats)
  14173. (const category))
  14174. :version "26.1"
  14175. :package-version '(Org . "8.3")
  14176. :group 'org-agenda)
  14177. ;;;; Files
  14178. (defun org-save-all-org-buffers ()
  14179. "Save all Org buffers without user confirmation."
  14180. (interactive)
  14181. (message "Saving all Org buffers...")
  14182. (save-some-buffers t (lambda () (and (derived-mode-p 'org-mode) t)))
  14183. (when (featurep 'org-id) (org-id-locations-save))
  14184. (message "Saving all Org buffers... done"))
  14185. (defun org-revert-all-org-buffers ()
  14186. "Revert all Org buffers.
  14187. Prompt for confirmation when there are unsaved changes.
  14188. Be sure you know what you are doing before letting this function
  14189. overwrite your changes.
  14190. This function is useful in a setup where one tracks Org files
  14191. with a version control system, to revert on one machine after pulling
  14192. changes from another. I believe the procedure must be like this:
  14193. 1. \\[org-save-all-org-buffers]
  14194. 2. Pull changes from the other machine, resolve conflicts
  14195. 3. \\[org-revert-all-org-buffers]"
  14196. (interactive)
  14197. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  14198. (user-error "Abort"))
  14199. (save-excursion
  14200. (save-window-excursion
  14201. (dolist (b (buffer-list))
  14202. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  14203. (with-current-buffer b buffer-file-name))
  14204. (pop-to-buffer-same-window b)
  14205. (revert-buffer t 'no-confirm)))
  14206. (when (and (featurep 'org-id) org-id-track-globally)
  14207. (org-id-locations-load)))))
  14208. ;;;; Agenda files
  14209. ;;;###autoload
  14210. (defun org-switchb (&optional arg)
  14211. "Switch between Org buffers.
  14212. With `\\[universal-argument]' prefix, restrict available buffers to files.
  14213. With `\\[universal-argument] \\[universal-argument]' \
  14214. prefix, restrict available buffers to agenda files."
  14215. (interactive "P")
  14216. (let ((blist (org-buffer-list
  14217. (cond ((equal arg '(4)) 'files)
  14218. ((equal arg '(16)) 'agenda)))))
  14219. (pop-to-buffer-same-window
  14220. (completing-read "Org buffer: "
  14221. (mapcar #'list (mapcar #'buffer-name blist))
  14222. nil t))))
  14223. (defun org-buffer-list (&optional predicate exclude-tmp)
  14224. "Return a list of Org buffers.
  14225. PREDICATE can be `export', `files' or `agenda'.
  14226. export restrict the list to Export buffers.
  14227. files restrict the list to buffers visiting Org files.
  14228. agenda restrict the list to buffers visiting agenda files.
  14229. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  14230. (let* ((bfn nil)
  14231. (agenda-files (and (eq predicate 'agenda)
  14232. (mapcar 'file-truename (org-agenda-files t))))
  14233. (filter
  14234. (cond
  14235. ((eq predicate 'files)
  14236. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  14237. ((eq predicate 'export)
  14238. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  14239. ((eq predicate 'agenda)
  14240. (lambda (b)
  14241. (with-current-buffer b
  14242. (and (derived-mode-p 'org-mode)
  14243. (setq bfn (buffer-file-name b))
  14244. (member (file-truename bfn) agenda-files)))))
  14245. (t (lambda (b) (with-current-buffer b
  14246. (or (derived-mode-p 'org-mode)
  14247. (string-match "\\*Org .*Export"
  14248. (buffer-name b)))))))))
  14249. (delq nil
  14250. (mapcar
  14251. (lambda(b)
  14252. (if (and (funcall filter b)
  14253. (or (not exclude-tmp)
  14254. (not (string-match "tmp" (buffer-name b)))))
  14255. b
  14256. nil))
  14257. (buffer-list)))))
  14258. (defun org-agenda-files (&optional unrestricted archives)
  14259. "Get the list of agenda files.
  14260. Optional UNRESTRICTED means return the full list even if a restriction
  14261. is currently in place.
  14262. When ARCHIVES is t, include all archive files that are really being
  14263. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  14264. `org-agenda-archives-mode' is t."
  14265. (let ((files
  14266. (cond
  14267. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  14268. ((stringp org-agenda-files) (org-read-agenda-file-list))
  14269. ((listp org-agenda-files) org-agenda-files)
  14270. (t (error "Invalid value of `org-agenda-files'")))))
  14271. (setq files (apply 'append
  14272. (mapcar (lambda (f)
  14273. (if (file-directory-p f)
  14274. (directory-files
  14275. f t org-agenda-file-regexp)
  14276. (list (expand-file-name f org-directory))))
  14277. files)))
  14278. (when org-agenda-skip-unavailable-files
  14279. (setq files (delq nil
  14280. (mapcar (lambda (file)
  14281. (and (file-readable-p file) file))
  14282. files))))
  14283. (when (or (eq archives t)
  14284. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  14285. (setq files (org-add-archive-files files)))
  14286. files))
  14287. (defun org-agenda-file-p (&optional file)
  14288. "Return non-nil, if FILE is an agenda file.
  14289. If FILE is omitted, use the file associated with the current
  14290. buffer."
  14291. (let ((fname (or file (buffer-file-name))))
  14292. (and fname
  14293. (member (file-truename fname)
  14294. (mapcar #'file-truename (org-agenda-files t))))))
  14295. (defun org-edit-agenda-file-list ()
  14296. "Edit the list of agenda files.
  14297. Depending on setup, this either uses customize to edit the variable
  14298. `org-agenda-files', or it visits the file that is holding the list. In the
  14299. latter case, the buffer is set up in a way that saving it automatically kills
  14300. the buffer and restores the previous window configuration."
  14301. (interactive)
  14302. (if (stringp org-agenda-files)
  14303. (let ((cw (current-window-configuration)))
  14304. (find-file org-agenda-files)
  14305. (setq-local org-window-configuration cw)
  14306. (add-hook 'after-save-hook
  14307. (lambda ()
  14308. (set-window-configuration
  14309. (prog1 org-window-configuration
  14310. (kill-buffer (current-buffer))))
  14311. (org-install-agenda-files-menu)
  14312. (message "New agenda file list installed"))
  14313. nil 'local)
  14314. (message "%s" (substitute-command-keys
  14315. "Edit list and finish with \\[save-buffer]")))
  14316. (customize-variable 'org-agenda-files)))
  14317. (defun org-store-new-agenda-file-list (list)
  14318. "Set new value for the agenda file list and save it correctly."
  14319. (if (stringp org-agenda-files)
  14320. (let ((fe (org-read-agenda-file-list t)) b u)
  14321. (while (setq b (find-buffer-visiting org-agenda-files))
  14322. (kill-buffer b))
  14323. (with-temp-file org-agenda-files
  14324. (insert
  14325. (mapconcat
  14326. (lambda (f) ;; Keep un-expanded entries.
  14327. (if (setq u (assoc f fe))
  14328. (cdr u)
  14329. f))
  14330. list "\n")
  14331. "\n")))
  14332. (let ((org-mode-hook nil) (org-inhibit-startup t)
  14333. (org-insert-mode-line-in-empty-file nil))
  14334. (setq org-agenda-files list)
  14335. (customize-save-variable 'org-agenda-files org-agenda-files))))
  14336. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  14337. "Read the list of agenda files from a file.
  14338. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  14339. filenames, used by `org-store-new-agenda-file-list' to write back
  14340. un-expanded file names."
  14341. (when (file-directory-p org-agenda-files)
  14342. (error "`org-agenda-files' cannot be a single directory"))
  14343. (when (stringp org-agenda-files)
  14344. (with-temp-buffer
  14345. (insert-file-contents org-agenda-files)
  14346. (mapcar
  14347. (lambda (f)
  14348. (let ((e (expand-file-name (substitute-in-file-name f)
  14349. org-directory)))
  14350. (if pair-with-expansion
  14351. (cons e f)
  14352. e)))
  14353. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  14354. ;;;###autoload
  14355. (defun org-cycle-agenda-files ()
  14356. "Cycle through the files in `org-agenda-files'.
  14357. If the current buffer visits an agenda file, find the next one in the list.
  14358. If the current buffer does not, find the first agenda file."
  14359. (interactive)
  14360. (let* ((fs (or (org-agenda-files t)
  14361. (user-error "No agenda files")))
  14362. (files (copy-sequence fs))
  14363. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  14364. file)
  14365. (when tcf
  14366. (while (and (setq file (pop files))
  14367. (not (equal (file-truename file) tcf)))))
  14368. (find-file (car (or files fs)))
  14369. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  14370. (defun org-agenda-file-to-front (&optional to-end)
  14371. "Move/add the current file to the top of the agenda file list.
  14372. If the file is not present in the list, it is added to the front. If it is
  14373. present, it is moved there. With optional argument TO-END, add/move to the
  14374. end of the list."
  14375. (interactive "P")
  14376. (let ((org-agenda-skip-unavailable-files nil)
  14377. (file-alist (mapcar (lambda (x)
  14378. (cons (file-truename x) x))
  14379. (org-agenda-files t)))
  14380. (ctf (file-truename
  14381. (or buffer-file-name
  14382. (user-error "Please save the current buffer to a file"))))
  14383. x had)
  14384. (setq x (assoc ctf file-alist) had x)
  14385. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  14386. (if to-end
  14387. (setq file-alist (append (delq x file-alist) (list x)))
  14388. (setq file-alist (cons x (delq x file-alist))))
  14389. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  14390. (org-install-agenda-files-menu)
  14391. (message "File %s to %s of agenda file list"
  14392. (if had "moved" "added") (if to-end "end" "front"))))
  14393. (defun org-remove-file (&optional file)
  14394. "Remove current file from the list of files in variable `org-agenda-files'.
  14395. These are the files which are being checked for agenda entries.
  14396. Optional argument FILE means use this file instead of the current."
  14397. (interactive)
  14398. (let* ((org-agenda-skip-unavailable-files nil)
  14399. (file (or file buffer-file-name
  14400. (user-error "Current buffer does not visit a file")))
  14401. (true-file (file-truename file))
  14402. (afile (abbreviate-file-name file))
  14403. (files (delq nil (mapcar
  14404. (lambda (x)
  14405. (unless (equal true-file
  14406. (file-truename x))
  14407. x))
  14408. (org-agenda-files t)))))
  14409. (if (not (= (length files) (length (org-agenda-files t))))
  14410. (progn
  14411. (org-store-new-agenda-file-list files)
  14412. (org-install-agenda-files-menu)
  14413. (message "Removed from Org Agenda list: %s" afile))
  14414. (message "File was not in list: %s (not removed)" afile))))
  14415. (defun org-file-menu-entry (file)
  14416. (vector file (list 'find-file file) t))
  14417. (defun org-check-agenda-file (file)
  14418. "Make sure FILE exists. If not, ask user what to do."
  14419. (unless (file-exists-p file)
  14420. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  14421. (abbreviate-file-name file))
  14422. (let ((r (downcase (read-char-exclusive))))
  14423. (cond
  14424. ((equal r ?r)
  14425. (org-remove-file file)
  14426. (throw 'nextfile t))
  14427. (t (user-error "Abort"))))))
  14428. (defun org-get-agenda-file-buffer (file)
  14429. "Get an agenda buffer visiting FILE.
  14430. If the buffer needs to be created, add it to the list of buffers
  14431. which might be released later."
  14432. (let ((buf (org-find-base-buffer-visiting file)))
  14433. (if buf
  14434. buf ; just return it
  14435. ;; Make a new buffer and remember it
  14436. (setq buf (find-file-noselect file))
  14437. (when buf (push buf org-agenda-new-buffers))
  14438. buf)))
  14439. (defun org-release-buffers (blist)
  14440. "Release all buffers in list, asking the user for confirmation when needed.
  14441. When a buffer is unmodified, it is just killed. When modified, it is saved
  14442. \(if the user agrees) and then killed."
  14443. (let (file)
  14444. (dolist (buf blist)
  14445. (setq file (buffer-file-name buf))
  14446. (when (and (buffer-modified-p buf)
  14447. file
  14448. (y-or-n-p (format "Save file %s? " file)))
  14449. (with-current-buffer buf (save-buffer)))
  14450. (kill-buffer buf))))
  14451. (defun org-agenda-prepare-buffers (files)
  14452. "Create buffers for all agenda files, protect archived trees and comments."
  14453. (interactive)
  14454. (let ((inhibit-read-only t)
  14455. (org-inhibit-startup org-agenda-inhibit-startup)
  14456. pos)
  14457. (setq org-tag-alist-for-agenda nil
  14458. org-tag-groups-alist-for-agenda nil)
  14459. (save-excursion
  14460. (save-restriction
  14461. (dolist (file files)
  14462. (catch 'nextfile
  14463. (if (bufferp file)
  14464. (set-buffer file)
  14465. (org-check-agenda-file file)
  14466. (set-buffer (org-get-agenda-file-buffer file)))
  14467. (widen)
  14468. (org-set-regexps-and-options 'tags-only)
  14469. (setq pos (point))
  14470. (or (memq 'category org-agenda-ignore-properties)
  14471. (org-refresh-category-properties))
  14472. (or (memq 'stats org-agenda-ignore-properties)
  14473. (org-refresh-stats-properties))
  14474. (or (memq 'effort org-agenda-ignore-properties)
  14475. (unless (org-element--cache-active-p)
  14476. (org-refresh-effort-properties)))
  14477. (or (memq 'appt org-agenda-ignore-properties)
  14478. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  14479. (setq org-todo-keywords-for-agenda
  14480. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  14481. (setq org-done-keywords-for-agenda
  14482. (append org-done-keywords-for-agenda org-done-keywords))
  14483. (setq org-todo-keyword-alist-for-agenda
  14484. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  14485. (setq org-tag-alist-for-agenda
  14486. (org--tag-add-to-alist
  14487. org-tag-alist-for-agenda
  14488. org-current-tag-alist))
  14489. ;; Merge current file's tag groups into global
  14490. ;; `org-tag-groups-alist-for-agenda'.
  14491. (when org-group-tags
  14492. (dolist (alist org-tag-groups-alist)
  14493. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  14494. (if old
  14495. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  14496. (push alist org-tag-groups-alist-for-agenda)))))
  14497. (goto-char pos)))))
  14498. (setq org-todo-keywords-for-agenda
  14499. (org-uniquify org-todo-keywords-for-agenda))
  14500. (setq org-todo-keyword-alist-for-agenda
  14501. (org-uniquify org-todo-keyword-alist-for-agenda))))
  14502. ;;;; CDLaTeX minor mode
  14503. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  14504. "Keymap for the minor `org-cdlatex-mode'.")
  14505. (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
  14506. (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
  14507. (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
  14508. (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
  14509. (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
  14510. (defvar org-cdlatex-texmathp-advice-is-done nil
  14511. "Flag remembering if we have applied the advice to texmathp already.")
  14512. (define-minor-mode org-cdlatex-mode
  14513. "Toggle the minor `org-cdlatex-mode'.
  14514. This mode supports entering LaTeX environment and math in LaTeX fragments
  14515. in Org mode.
  14516. \\{org-cdlatex-mode-map}"
  14517. :lighter " OCDL"
  14518. (when org-cdlatex-mode
  14519. (require 'cdlatex)
  14520. (run-hooks 'cdlatex-mode-hook)
  14521. (cdlatex-compute-tables))
  14522. (unless org-cdlatex-texmathp-advice-is-done
  14523. (setq org-cdlatex-texmathp-advice-is-done t)
  14524. (defadvice texmathp (around org-math-always-on activate)
  14525. "Always return t in Org buffers.
  14526. This is because we want to insert math symbols without dollars even outside
  14527. the LaTeX math segments. If Org mode thinks that point is actually inside
  14528. an embedded LaTeX fragment, let `texmathp' do its job.
  14529. `\\[org-cdlatex-mode-map]'"
  14530. (interactive)
  14531. (let (p)
  14532. (cond
  14533. ((not (derived-mode-p 'org-mode)) ad-do-it)
  14534. ((eq this-command 'cdlatex-math-symbol)
  14535. (setq ad-return-value t
  14536. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  14537. (t
  14538. (let ((p (org-inside-LaTeX-fragment-p)))
  14539. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  14540. (setq ad-return-value t
  14541. texmathp-why '("Org mode embedded math" . 0))
  14542. (when p ad-do-it)))))))))
  14543. (defun turn-on-org-cdlatex ()
  14544. "Unconditionally turn on `org-cdlatex-mode'."
  14545. (org-cdlatex-mode 1))
  14546. (defun org-try-cdlatex-tab ()
  14547. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  14548. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  14549. - inside a LaTeX fragment, or
  14550. - after the first word in a line, where an abbreviation expansion could
  14551. insert a LaTeX environment."
  14552. (when org-cdlatex-mode
  14553. (cond
  14554. ;; Before any word on the line: No expansion possible.
  14555. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  14556. ;; Just after first word on the line: Expand it. Make sure it
  14557. ;; cannot happen on headlines, though.
  14558. ((save-excursion
  14559. (skip-chars-backward "a-zA-Z0-9*")
  14560. (skip-chars-backward " \t")
  14561. (and (bolp) (not (org-at-heading-p))))
  14562. (cdlatex-tab) t)
  14563. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  14564. (defun org-cdlatex-underscore-caret (&optional _arg)
  14565. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  14566. Revert to the normal definition outside of these fragments."
  14567. (interactive "P")
  14568. (if (org-inside-LaTeX-fragment-p)
  14569. (call-interactively 'cdlatex-sub-superscript)
  14570. (let (org-cdlatex-mode)
  14571. (call-interactively (key-binding (vector last-input-event))))))
  14572. (defun org-cdlatex-math-modify (&optional _arg)
  14573. "Execute `cdlatex-math-modify' in LaTeX fragments.
  14574. Revert to the normal definition outside of these fragments."
  14575. (interactive "P")
  14576. (if (org-inside-LaTeX-fragment-p)
  14577. (call-interactively 'cdlatex-math-modify)
  14578. (let (org-cdlatex-mode)
  14579. (call-interactively (key-binding (vector last-input-event))))))
  14580. (defun org-cdlatex-environment-indent (&optional environment item)
  14581. "Execute `cdlatex-environment' and indent the inserted environment.
  14582. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  14583. The inserted environment is indented to current indentation
  14584. unless point is at the beginning of the line, in which the
  14585. environment remains unintended."
  14586. (interactive)
  14587. ;; cdlatex-environment always return nil. Therefore, capture output
  14588. ;; first and determine if an environment was selected.
  14589. (let* ((beg (point-marker))
  14590. (end (copy-marker (point) t))
  14591. (inserted (progn
  14592. (ignore-errors (cdlatex-environment environment item))
  14593. (< beg end)))
  14594. ;; Figure out how many lines to move forward after the
  14595. ;; environment has been inserted.
  14596. (lines (when inserted
  14597. (save-excursion
  14598. (- (cl-loop while (< beg (point))
  14599. with x = 0
  14600. do (forward-line -1)
  14601. (cl-incf x)
  14602. finally return x)
  14603. (if (progn (goto-char beg)
  14604. (and (progn (skip-chars-forward " \t") (eolp))
  14605. (progn (skip-chars-backward " \t") (bolp))))
  14606. 1 0)))))
  14607. (env (org-trim (delete-and-extract-region beg end))))
  14608. (when inserted
  14609. ;; Get indentation of next line unless at column 0.
  14610. (let ((ind (if (bolp) 0
  14611. (save-excursion
  14612. (org-return t)
  14613. (prog1 (current-indentation)
  14614. (when (progn (skip-chars-forward " \t") (eolp))
  14615. (delete-region beg (point)))))))
  14616. (bol (progn (skip-chars-backward " \t") (bolp))))
  14617. ;; Insert a newline before environment unless at column zero
  14618. ;; to "escape" the current line. Insert a newline if
  14619. ;; something is one the same line as \end{ENVIRONMENT}.
  14620. (insert
  14621. (concat (unless bol "\n") env
  14622. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  14623. (unless (zerop ind)
  14624. (save-excursion
  14625. (goto-char beg)
  14626. (while (< (point) end)
  14627. (unless (eolp) (indent-line-to ind))
  14628. (forward-line))))
  14629. (goto-char beg)
  14630. (forward-line lines)
  14631. (indent-line-to ind)))
  14632. (set-marker beg nil)
  14633. (set-marker end nil)))
  14634. ;;;; LaTeX fragments
  14635. (defun org-inside-LaTeX-fragment-p ()
  14636. "Test if point is inside a LaTeX fragment.
  14637. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  14638. sequence appearing also before point.
  14639. Even though the matchers for math are configurable, this function assumes
  14640. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  14641. delimiters are skipped when they have been removed by customization.
  14642. The return value is nil, or a cons cell with the delimiter and the
  14643. position of this delimiter.
  14644. This function does a reasonably good job, but can locally be fooled by
  14645. for example currency specifications. For example it will assume being in
  14646. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  14647. fragments that are properly closed, but during editing, we have to live
  14648. with the uncertainty caused by missing closing delimiters. This function
  14649. looks only before point, not after."
  14650. (catch 'exit
  14651. (let ((pos (point))
  14652. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  14653. (lim (progn
  14654. (re-search-backward (concat "^\\(" paragraph-start "\\)") nil
  14655. 'move)
  14656. (point)))
  14657. dd-on str (start 0) m re)
  14658. (goto-char pos)
  14659. (when dodollar
  14660. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  14661. re (nth 1 (assoc "$" org-latex-regexps)))
  14662. (while (string-match re str start)
  14663. (cond
  14664. ((= (match-end 0) (length str))
  14665. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  14666. ((= (match-end 0) (- (length str) 5))
  14667. (throw 'exit nil))
  14668. (t (setq start (match-end 0))))))
  14669. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  14670. (goto-char pos)
  14671. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  14672. (and (match-beginning 2) (throw 'exit nil))
  14673. ;; count $$
  14674. (while (re-search-backward "\\$\\$" lim t)
  14675. (setq dd-on (not dd-on)))
  14676. (goto-char pos)
  14677. (when dd-on (cons "$$" m))))))
  14678. (defun org-inside-latex-macro-p ()
  14679. "Is point inside a LaTeX macro or its arguments?"
  14680. (save-match-data
  14681. (org-in-regexp
  14682. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  14683. (defun org--make-preview-overlay (beg end image &optional imagetype)
  14684. "Build an overlay between BEG and END using IMAGE file.
  14685. Argument IMAGETYPE is the extension of the displayed image,
  14686. as a string. It defaults to \"png\"."
  14687. (let ((ov (make-overlay beg end))
  14688. (imagetype (or (intern imagetype) 'png)))
  14689. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  14690. (overlay-put ov 'evaporate t)
  14691. (overlay-put ov
  14692. 'modification-hooks
  14693. (list (lambda (o _flag _beg _end &optional _l)
  14694. (delete-overlay o))))
  14695. (overlay-put ov
  14696. 'display
  14697. (list 'image :type imagetype :file image :ascent 'center))))
  14698. (defun org-clear-latex-preview (&optional beg end)
  14699. "Remove all overlays with LaTeX fragment images in current buffer.
  14700. When optional arguments BEG and END are non-nil, remove all
  14701. overlays between them instead. Return a non-nil value when some
  14702. overlays were removed, nil otherwise."
  14703. (let ((overlays
  14704. (cl-remove-if-not
  14705. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  14706. (overlays-in (or beg (point-min)) (or end (point-max))))))
  14707. (mapc #'delete-overlay overlays)
  14708. overlays))
  14709. (defun org--latex-preview-region (beg end)
  14710. "Preview LaTeX fragments between BEG and END.
  14711. BEG and END are buffer positions."
  14712. (let ((file (buffer-file-name (buffer-base-buffer))))
  14713. (save-excursion
  14714. (org-format-latex
  14715. (concat org-preview-latex-image-directory "org-ltximg")
  14716. beg end
  14717. ;; Emacs cannot overlay images from remote hosts. Create it in
  14718. ;; `temporary-file-directory' instead.
  14719. (if (or (not file) (file-remote-p file))
  14720. temporary-file-directory
  14721. default-directory)
  14722. 'overlays nil 'forbuffer org-preview-latex-default-process))))
  14723. (defun org-latex-preview (&optional arg)
  14724. "Toggle preview of the LaTeX fragment at point.
  14725. If the cursor is on a LaTeX fragment, create the image and
  14726. overlay it over the source code, if there is none. Remove it
  14727. otherwise. If there is no fragment at point, display images for
  14728. all fragments in the current section.
  14729. With a `\\[universal-argument]' prefix argument ARG, clear images \
  14730. for all fragments
  14731. in the current section.
  14732. With a `\\[universal-argument] \\[universal-argument]' prefix \
  14733. argument ARG, display image for all
  14734. fragments in the buffer.
  14735. With a `\\[universal-argument] \\[universal-argument] \
  14736. \\[universal-argument]' prefix argument ARG, clear image for all
  14737. fragments in the buffer."
  14738. (interactive "P")
  14739. (cond
  14740. ((not (display-graphic-p)) nil)
  14741. ;; Clear whole buffer.
  14742. ((equal arg '(64))
  14743. (org-clear-latex-preview (point-min) (point-max))
  14744. (message "LaTeX previews removed from buffer"))
  14745. ;; Preview whole buffer.
  14746. ((equal arg '(16))
  14747. (message "Creating LaTeX previews in buffer...")
  14748. (org--latex-preview-region (point-min) (point-max))
  14749. (message "Creating LaTeX previews in buffer... done."))
  14750. ;; Clear current section.
  14751. ((equal arg '(4))
  14752. (org-clear-latex-preview
  14753. (if (org-before-first-heading-p) (point-min)
  14754. (save-excursion
  14755. (org-with-limited-levels (org-back-to-heading t) (point))))
  14756. (org-with-limited-levels (org-entry-end-position))))
  14757. ;; Toggle preview on LaTeX code at point.
  14758. ((let ((datum (org-element-context)))
  14759. (and (memq (org-element-type datum) '(latex-environment latex-fragment))
  14760. (let ((beg (org-element-property :begin datum))
  14761. (end (org-element-property :end datum)))
  14762. (if (org-clear-latex-preview beg end)
  14763. (message "LaTeX preview removed")
  14764. (message "Creating LaTeX preview...")
  14765. (org--latex-preview-region beg end)
  14766. (message "Creating LaTeX preview... done."))
  14767. t))))
  14768. ;; Preview current section.
  14769. (t
  14770. (let ((beg (if (org-before-first-heading-p) (point-min)
  14771. (save-excursion
  14772. (org-with-limited-levels (org-back-to-heading t) (point)))))
  14773. (end (org-with-limited-levels (org-entry-end-position))))
  14774. (message "Creating LaTeX previews in section...")
  14775. (org--latex-preview-region beg end)
  14776. (message "Creating LaTeX previews in section... done.")))))
  14777. (defun org-format-latex
  14778. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  14779. "Replace LaTeX fragments with links to an image.
  14780. The function takes care of creating the replacement image.
  14781. Only consider fragments between BEG and END when those are
  14782. provided.
  14783. When optional argument OVERLAYS is non-nil, display the image on
  14784. top of the fragment instead of replacing it.
  14785. PROCESSING-TYPE is the conversion method to use, as a symbol.
  14786. Some of the options can be changed using the variable
  14787. `org-format-latex-options', which see."
  14788. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  14789. (unless (eq processing-type 'verbatim)
  14790. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  14791. (cnt 0)
  14792. checkdir-flag)
  14793. (goto-char (or beg (point-min)))
  14794. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  14795. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  14796. (overlay-recenter (or end (point-max))))
  14797. (while (re-search-forward math-regexp end t)
  14798. (unless (and overlays
  14799. (eq (get-char-property (point) 'org-overlay-type)
  14800. 'org-latex-overlay))
  14801. (let* ((context (org-element-context))
  14802. (type (org-element-type context)))
  14803. (when (memq type '(latex-environment latex-fragment))
  14804. (let ((block-type (eq type 'latex-environment))
  14805. (value (org-element-property :value context))
  14806. (beg (org-element-property :begin context))
  14807. (end (save-excursion
  14808. (goto-char (org-element-property :end context))
  14809. (skip-chars-backward " \r\t\n")
  14810. (point))))
  14811. (cond
  14812. ((eq processing-type 'mathjax)
  14813. ;; Prepare for MathJax processing.
  14814. (if (not (string-match "\\`\\$\\$?" value))
  14815. (goto-char end)
  14816. (delete-region beg end)
  14817. (if (string= (match-string 0 value) "$$")
  14818. (insert "\\[" (substring value 2 -2) "\\]")
  14819. (insert "\\(" (substring value 1 -1) "\\)"))))
  14820. ((eq processing-type 'html)
  14821. (goto-char beg)
  14822. (delete-region beg end)
  14823. (insert (org-format-latex-as-html value)))
  14824. ((assq processing-type org-preview-latex-process-alist)
  14825. ;; Process to an image.
  14826. (cl-incf cnt)
  14827. (goto-char beg)
  14828. (let* ((processing-info
  14829. (cdr (assq processing-type org-preview-latex-process-alist)))
  14830. (face (face-at-point))
  14831. ;; Get the colors from the face at point.
  14832. (fg
  14833. (let ((color (plist-get org-format-latex-options
  14834. :foreground)))
  14835. (if forbuffer
  14836. (cond
  14837. ((eq color 'auto)
  14838. (face-attribute face :foreground nil 'default))
  14839. ((eq color 'default)
  14840. (face-attribute 'default :foreground nil))
  14841. (t color))
  14842. color)))
  14843. (bg
  14844. (let ((color (plist-get org-format-latex-options
  14845. :background)))
  14846. (if forbuffer
  14847. (cond
  14848. ((eq color 'auto)
  14849. (face-attribute face :background nil 'default))
  14850. ((eq color 'default)
  14851. (face-attribute 'default :background nil))
  14852. (t color))
  14853. color)))
  14854. (hash (sha1 (prin1-to-string
  14855. (list org-format-latex-header
  14856. org-latex-default-packages-alist
  14857. org-latex-packages-alist
  14858. org-format-latex-options
  14859. forbuffer value fg bg))))
  14860. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  14861. (absprefix (expand-file-name prefix dir))
  14862. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  14863. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  14864. (sep (and block-type "\n\n"))
  14865. (link (concat sep "[[file:" linkfile "]]" sep))
  14866. (options
  14867. (org-combine-plists
  14868. org-format-latex-options
  14869. `(:foreground ,fg :background ,bg))))
  14870. (when msg (message msg cnt))
  14871. (unless checkdir-flag ; Ensure the directory exists.
  14872. (setq checkdir-flag t)
  14873. (let ((todir (file-name-directory absprefix)))
  14874. (unless (file-directory-p todir)
  14875. (make-directory todir t))))
  14876. (unless (file-exists-p movefile)
  14877. (org-create-formula-image
  14878. value movefile options forbuffer processing-type))
  14879. (if overlays
  14880. (progn
  14881. (dolist (o (overlays-in beg end))
  14882. (when (eq (overlay-get o 'org-overlay-type)
  14883. 'org-latex-overlay)
  14884. (delete-overlay o)))
  14885. (org--make-preview-overlay beg end movefile imagetype)
  14886. (goto-char end))
  14887. (delete-region beg end)
  14888. (insert
  14889. (org-add-props link
  14890. (list 'org-latex-src
  14891. (replace-regexp-in-string "\"" "" value)
  14892. 'org-latex-src-embed-type
  14893. (if block-type 'paragraph 'character)))))))
  14894. ((eq processing-type 'mathml)
  14895. ;; Process to MathML.
  14896. (unless (org-format-latex-mathml-available-p)
  14897. (user-error "LaTeX to MathML converter not configured"))
  14898. (cl-incf cnt)
  14899. (when msg (message msg cnt))
  14900. (goto-char beg)
  14901. (delete-region beg end)
  14902. (insert (org-format-latex-as-mathml
  14903. value block-type prefix dir)))
  14904. (t
  14905. (error "Unknown conversion process %s for LaTeX fragments"
  14906. processing-type)))))))))))
  14907. (defun org-create-math-formula (latex-frag &optional mathml-file)
  14908. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  14909. Use `org-latex-to-mathml-convert-command'. If the conversion is
  14910. successful, return the portion between \"<math...> </math>\"
  14911. elements otherwise return nil. When MATHML-FILE is specified,
  14912. write the results in to that file. When invoked as an
  14913. interactive command, prompt for LATEX-FRAG, with initial value
  14914. set to the current active region and echo the results for user
  14915. inspection."
  14916. (interactive (list (let ((frag (when (org-region-active-p)
  14917. (buffer-substring-no-properties
  14918. (region-beginning) (region-end)))))
  14919. (read-string "LaTeX Fragment: " frag nil frag))))
  14920. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  14921. (let* ((tmp-in-file
  14922. (let ((file (file-relative-name
  14923. (make-temp-name (expand-file-name "ltxmathml-in")))))
  14924. (write-region latex-frag nil file)
  14925. file))
  14926. (tmp-out-file (file-relative-name
  14927. (make-temp-name (expand-file-name "ltxmathml-out"))))
  14928. (cmd (format-spec
  14929. org-latex-to-mathml-convert-command
  14930. `((?j . ,(and org-latex-to-mathml-jar-file
  14931. (shell-quote-argument
  14932. (expand-file-name
  14933. org-latex-to-mathml-jar-file))))
  14934. (?I . ,(shell-quote-argument tmp-in-file))
  14935. (?i . ,latex-frag)
  14936. (?o . ,(shell-quote-argument tmp-out-file)))))
  14937. mathml shell-command-output)
  14938. (when (called-interactively-p 'any)
  14939. (unless (org-format-latex-mathml-available-p)
  14940. (user-error "LaTeX to MathML converter not configured")))
  14941. (message "Running %s" cmd)
  14942. (setq shell-command-output (shell-command-to-string cmd))
  14943. (setq mathml
  14944. (when (file-readable-p tmp-out-file)
  14945. (with-current-buffer (find-file-noselect tmp-out-file t)
  14946. (goto-char (point-min))
  14947. (when (re-search-forward
  14948. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  14949. (regexp-quote
  14950. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  14951. nil t)
  14952. (prog1 (match-string 0) (kill-buffer))))))
  14953. (cond
  14954. (mathml
  14955. (setq mathml
  14956. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  14957. (when mathml-file
  14958. (write-region mathml nil mathml-file))
  14959. (when (called-interactively-p 'any)
  14960. (message mathml)))
  14961. ((warn "LaTeX to MathML conversion failed")
  14962. (message shell-command-output)))
  14963. (delete-file tmp-in-file)
  14964. (when (file-exists-p tmp-out-file)
  14965. (delete-file tmp-out-file))
  14966. mathml))
  14967. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  14968. prefix &optional dir)
  14969. "Use `org-create-math-formula' but check local cache first."
  14970. (let* ((absprefix (expand-file-name prefix dir))
  14971. (print-length nil) (print-level nil)
  14972. (formula-id (concat
  14973. "formula-"
  14974. (sha1
  14975. (prin1-to-string
  14976. (list latex-frag
  14977. org-latex-to-mathml-convert-command)))))
  14978. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  14979. (formula-cache-dir (file-name-directory formula-cache)))
  14980. (unless (file-directory-p formula-cache-dir)
  14981. (make-directory formula-cache-dir t))
  14982. (unless (file-exists-p formula-cache)
  14983. (org-create-math-formula latex-frag formula-cache))
  14984. (if (file-exists-p formula-cache)
  14985. ;; Successful conversion. Return the link to MathML file.
  14986. (org-add-props
  14987. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  14988. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  14989. 'org-latex-src-embed-type (if latex-frag-type
  14990. 'paragraph 'character)))
  14991. ;; Failed conversion. Return the LaTeX fragment verbatim
  14992. latex-frag)))
  14993. (defun org-format-latex-as-html (latex-fragment)
  14994. "Convert LATEX-FRAGMENT to HTML.
  14995. This uses `org-latex-to-html-convert-command', which see."
  14996. (let ((cmd (format-spec org-latex-to-html-convert-command
  14997. `((?i . ,latex-fragment)))))
  14998. (message "Running %s" cmd)
  14999. (shell-command-to-string cmd)))
  15000. (defun org--get-display-dpi ()
  15001. "Get the DPI of the display.
  15002. The function assumes that the display has the same pixel width in
  15003. the horizontal and vertical directions."
  15004. (if (display-graphic-p)
  15005. (round (/ (display-pixel-height)
  15006. (/ (display-mm-height) 25.4)))
  15007. (error "Attempt to calculate the dpi of a non-graphic display")))
  15008. (defun org-create-formula-image
  15009. (string tofile options buffer &optional processing-type)
  15010. "Create an image from LaTeX source using external processes.
  15011. The LaTeX STRING is saved to a temporary LaTeX file, then
  15012. converted to an image file by process PROCESSING-TYPE defined in
  15013. `org-preview-latex-process-alist'. A nil value defaults to
  15014. `org-preview-latex-default-process'.
  15015. The generated image file is eventually moved to TOFILE.
  15016. The OPTIONS argument controls the size, foreground color and
  15017. background color of the generated image.
  15018. When BUFFER non-nil, this function is used for LaTeX previewing.
  15019. Otherwise, it is used to deal with LaTeX snippets showed in
  15020. a HTML file."
  15021. (let* ((processing-type (or processing-type
  15022. org-preview-latex-default-process))
  15023. (processing-info
  15024. (cdr (assq processing-type org-preview-latex-process-alist)))
  15025. (programs (plist-get processing-info :programs))
  15026. (error-message (or (plist-get processing-info :message) ""))
  15027. (image-input-type (plist-get processing-info :image-input-type))
  15028. (image-output-type (plist-get processing-info :image-output-type))
  15029. (post-clean (or (plist-get processing-info :post-clean)
  15030. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  15031. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  15032. (latex-header
  15033. (or (plist-get processing-info :latex-header)
  15034. (org-latex-make-preamble
  15035. (org-export-get-environment (org-export-get-backend 'latex))
  15036. org-format-latex-header
  15037. 'snippet)))
  15038. (latex-compiler (plist-get processing-info :latex-compiler))
  15039. (tmpdir temporary-file-directory)
  15040. (texfilebase (make-temp-name
  15041. (expand-file-name "orgtex" tmpdir)))
  15042. (texfile (concat texfilebase ".tex"))
  15043. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  15044. '(1.0 . 1.0)))
  15045. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  15046. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  15047. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  15048. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  15049. "Black"))
  15050. (bg (or (plist-get options (if buffer :background :html-background))
  15051. "Transparent"))
  15052. (image-converter
  15053. (or (and (string= bg "Transparent")
  15054. (plist-get processing-info :transparent-image-converter))
  15055. (plist-get processing-info :image-converter)))
  15056. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  15057. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  15058. (dolist (program programs)
  15059. (org-check-external-command program error-message))
  15060. (if (eq fg 'default)
  15061. (setq fg (org-latex-color :foreground))
  15062. (setq fg (org-latex-color-format fg)))
  15063. (setq bg (cond
  15064. ((eq bg 'default) (org-latex-color :background))
  15065. ((string= bg "Transparent") nil)
  15066. (t (org-latex-color-format bg))))
  15067. ;; Remove TeX \par at end of snippet to avoid trailing space.
  15068. (if (string-suffix-p string "\n")
  15069. (aset string (1- (length string)) ?%)
  15070. (setq string (concat string "%")))
  15071. (with-temp-file texfile
  15072. (insert latex-header)
  15073. (insert "\n\\begin{document}\n"
  15074. "\\definecolor{fg}{rgb}{" fg "}%\n"
  15075. (if bg
  15076. (concat "\\definecolor{bg}{rgb}{" bg "}%\n"
  15077. "\n\\pagecolor{bg}%\n")
  15078. "")
  15079. "\n{\\color{fg}\n"
  15080. string
  15081. "\n}\n"
  15082. "\n\\end{document}\n"))
  15083. (let* ((err-msg (format "Please adjust `%s' part of \
  15084. `org-preview-latex-process-alist'."
  15085. processing-type))
  15086. (image-input-file
  15087. (org-compile-file
  15088. texfile latex-compiler image-input-type err-msg log-buf))
  15089. (image-output-file
  15090. (org-compile-file
  15091. image-input-file image-converter image-output-type err-msg log-buf
  15092. `((?D . ,(shell-quote-argument (format "%s" dpi)))
  15093. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  15094. (copy-file image-output-file tofile 'replace)
  15095. (dolist (e post-clean)
  15096. (when (file-exists-p (concat texfilebase e))
  15097. (delete-file (concat texfilebase e))))
  15098. image-output-file)))
  15099. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  15100. "Fill a LaTeX header template TPL.
  15101. In the template, the following place holders will be recognized:
  15102. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  15103. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  15104. [PACKAGES] \\usepackage statements for PKG
  15105. [NO-PACKAGES] do not include PKG
  15106. [EXTRA] the string EXTRA
  15107. [NO-EXTRA] do not include EXTRA
  15108. For backward compatibility, if both the positive and the negative place
  15109. holder is missing, the positive one (without the \"NO-\") will be
  15110. assumed to be present at the end of the template.
  15111. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  15112. EXTRA is a string.
  15113. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  15114. (let (rpl (end ""))
  15115. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  15116. (setq rpl (if (or (match-end 1) (not def-pkg))
  15117. "" (org-latex-packages-to-string def-pkg snippets-p t))
  15118. tpl (replace-match rpl t t tpl))
  15119. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  15120. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  15121. (setq rpl (if (or (match-end 1) (not pkg))
  15122. "" (org-latex-packages-to-string pkg snippets-p t))
  15123. tpl (replace-match rpl t t tpl))
  15124. (when pkg (setq end
  15125. (concat end "\n"
  15126. (org-latex-packages-to-string pkg snippets-p)))))
  15127. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  15128. (setq rpl (if (or (match-end 1) (not extra))
  15129. "" (concat extra "\n"))
  15130. tpl (replace-match rpl t t tpl))
  15131. (when (and extra (string-match "\\S-" extra))
  15132. (setq end (concat end "\n" extra))))
  15133. (if (string-match "\\S-" end)
  15134. (concat tpl "\n" end)
  15135. tpl)))
  15136. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  15137. "Turn an alist of packages into a string with the \\usepackage macros."
  15138. (setq pkg (mapconcat (lambda(p)
  15139. (cond
  15140. ((stringp p) p)
  15141. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  15142. (format "%% Package %s omitted" (cadr p)))
  15143. ((equal "" (car p))
  15144. (format "\\usepackage{%s}" (cadr p)))
  15145. (t
  15146. (format "\\usepackage[%s]{%s}"
  15147. (car p) (cadr p)))))
  15148. pkg
  15149. "\n"))
  15150. (if newline (concat pkg "\n") pkg))
  15151. (defun org-dvipng-color (attr)
  15152. "Return a RGB color specification for dvipng."
  15153. (org-dvipng-color-format (face-attribute 'default attr nil)))
  15154. (defun org-dvipng-color-format (color-name)
  15155. "Convert COLOR-NAME to a RGB color value for dvipng."
  15156. (apply #'format "rgb %s %s %s"
  15157. (mapcar 'org-normalize-color
  15158. (color-values color-name))))
  15159. (defun org-latex-color (attr)
  15160. "Return a RGB color for the LaTeX color package."
  15161. (org-latex-color-format (face-attribute 'default attr nil)))
  15162. (defun org-latex-color-format (color-name)
  15163. "Convert COLOR-NAME to a RGB color value."
  15164. (apply #'format "%s,%s,%s"
  15165. (mapcar 'org-normalize-color
  15166. (color-values color-name))))
  15167. (defun org-normalize-color (value)
  15168. "Return string to be used as color value for an RGB component."
  15169. (format "%g" (/ value 65535.0)))
  15170. ;; Image display
  15171. (defvar-local org-inline-image-overlays nil)
  15172. (defun org-toggle-inline-images (&optional include-linked)
  15173. "Toggle the display of inline images.
  15174. INCLUDE-LINKED is passed to `org-display-inline-images'."
  15175. (interactive "P")
  15176. (if org-inline-image-overlays
  15177. (progn
  15178. (org-remove-inline-images)
  15179. (when (called-interactively-p 'interactive)
  15180. (message "Inline image display turned off")))
  15181. (org-display-inline-images include-linked)
  15182. (when (called-interactively-p 'interactive)
  15183. (message (if org-inline-image-overlays
  15184. (format "%d images displayed inline"
  15185. (length org-inline-image-overlays))
  15186. "No images to display inline")))))
  15187. (defun org-redisplay-inline-images ()
  15188. "Assure display of inline images and refresh them."
  15189. (interactive)
  15190. (org-toggle-inline-images)
  15191. (unless org-inline-image-overlays
  15192. (org-toggle-inline-images)))
  15193. ;; For without-x builds.
  15194. (declare-function image-refresh "image" (spec &optional frame))
  15195. (defcustom org-display-remote-inline-images 'skip
  15196. "How to display remote inline images.
  15197. Possible values of this option are:
  15198. skip Don't display remote images.
  15199. download Always download and display remote images.
  15200. cache Display remote images, and open them in separate buffers
  15201. for caching. Silently update the image buffer when a file
  15202. change is detected."
  15203. :group 'org-appearance
  15204. :package-version '(Org . "9.4")
  15205. :type '(choice
  15206. (const :tag "Ignore remote images" skip)
  15207. (const :tag "Always display remote images" download)
  15208. (const :tag "Display and silently update remote images" cache))
  15209. :safe #'symbolp)
  15210. (defun org--create-inline-image (file width)
  15211. "Create image located at FILE, or return nil.
  15212. WIDTH is the width of the image. The image may not be created
  15213. according to the value of `org-display-remote-inline-images'."
  15214. (let* ((remote? (file-remote-p file))
  15215. (file-or-data
  15216. (pcase org-display-remote-inline-images
  15217. ((guard (not remote?)) file)
  15218. (`download (with-temp-buffer
  15219. (set-buffer-multibyte nil)
  15220. (insert-file-contents-literally file)
  15221. (buffer-string)))
  15222. (`cache (let ((revert-without-query '(".")))
  15223. (with-current-buffer (find-file-noselect file)
  15224. (buffer-string))))
  15225. (`skip nil)
  15226. (other
  15227. (message "Invalid value of `org-display-remote-inline-images': %S"
  15228. other)
  15229. nil))))
  15230. (when file-or-data
  15231. (create-image file-or-data
  15232. (and (image-type-available-p 'imagemagick)
  15233. width
  15234. 'imagemagick)
  15235. remote?
  15236. :width width))))
  15237. (defun org-display-inline-images (&optional include-linked refresh beg end)
  15238. "Display inline images.
  15239. An inline image is a link which follows either of these
  15240. conventions:
  15241. 1. Its path is a file with an extension matching return value
  15242. from `image-file-name-regexp' and it has no contents.
  15243. 2. Its description consists in a single link of the previous
  15244. type. In this case, that link must be a well-formed plain
  15245. or angle link, i.e., it must have an explicit \"file\" type.
  15246. Equip each image with the key-map `image-map'.
  15247. When optional argument INCLUDE-LINKED is non-nil, also links with
  15248. a text description part will be inlined. This can be nice for
  15249. a quick look at those images, but it does not reflect what
  15250. exported files will look like.
  15251. When optional argument REFRESH is non-nil, refresh existing
  15252. images between BEG and END. This will create new image displays
  15253. only if necessary.
  15254. BEG and END define the considered part. They default to the
  15255. buffer boundaries with possible narrowing."
  15256. (interactive "P")
  15257. (when (display-graphic-p)
  15258. (unless refresh
  15259. (org-remove-inline-images)
  15260. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  15261. (let ((end (or end (point-max))))
  15262. (org-with-point-at (or beg (point-min))
  15263. (let* ((case-fold-search t)
  15264. (file-extension-re (image-file-name-regexp))
  15265. (link-abbrevs (mapcar #'car
  15266. (append org-link-abbrev-alist-local
  15267. org-link-abbrev-alist)))
  15268. ;; Check absolute, relative file names and explicit
  15269. ;; "file:" links. Also check link abbreviations since
  15270. ;; some might expand to "file" links.
  15271. (file-types-re
  15272. (format "\\[\\[\\(?:file%s:\\|attachment:\\|[./~]\\)\\|\\]\\[\\(<?file:\\)"
  15273. (if (not link-abbrevs) ""
  15274. (concat "\\|" (regexp-opt link-abbrevs))))))
  15275. (while (re-search-forward file-types-re end t)
  15276. (let* ((link (org-element-lineage
  15277. (save-match-data (org-element-context))
  15278. '(link) t))
  15279. (linktype (org-element-property :type link))
  15280. (inner-start (match-beginning 1))
  15281. (path
  15282. (cond
  15283. ;; No link at point; no inline image.
  15284. ((not link) nil)
  15285. ;; File link without a description. Also handle
  15286. ;; INCLUDE-LINKED here since it should have
  15287. ;; precedence over the next case. I.e., if link
  15288. ;; contains filenames in both the path and the
  15289. ;; description, prioritize the path only when
  15290. ;; INCLUDE-LINKED is non-nil.
  15291. ((or (not (org-element-property :contents-begin link))
  15292. include-linked)
  15293. (and (or (equal "file" linktype)
  15294. (equal "attachment" linktype))
  15295. (org-element-property :path link)))
  15296. ;; Link with a description. Check if description
  15297. ;; is a filename. Even if Org doesn't have syntax
  15298. ;; for those -- clickable image -- constructs, fake
  15299. ;; them, as in `org-export-insert-image-links'.
  15300. ((not inner-start) nil)
  15301. (t
  15302. (org-with-point-at inner-start
  15303. (and (looking-at
  15304. (if (char-equal ?< (char-after inner-start))
  15305. org-link-angle-re
  15306. org-link-plain-re))
  15307. ;; File name must fill the whole
  15308. ;; description.
  15309. (= (org-element-property :contents-end link)
  15310. (match-end 0))
  15311. (match-string 2)))))))
  15312. (when (and path (string-match-p file-extension-re path))
  15313. (let ((file (if (equal "attachment" linktype)
  15314. (progn
  15315. (require 'org-attach)
  15316. (ignore-errors (org-attach-expand path)))
  15317. (expand-file-name path))))
  15318. (when (and file (file-exists-p file))
  15319. (let ((width (org-display-inline-image--width link))
  15320. (old (get-char-property-and-overlay
  15321. (org-element-property :begin link)
  15322. 'org-image-overlay)))
  15323. (if (and (car-safe old) refresh)
  15324. (image-refresh (overlay-get (cdr old) 'display))
  15325. (let ((image (org--create-inline-image file width)))
  15326. (when image
  15327. (let ((ov (make-overlay
  15328. (org-element-property :begin link)
  15329. (progn
  15330. (goto-char
  15331. (org-element-property :end link))
  15332. (skip-chars-backward " \t")
  15333. (point)))))
  15334. (overlay-put ov 'display image)
  15335. (overlay-put ov 'face 'default)
  15336. (overlay-put ov 'org-image-overlay t)
  15337. (overlay-put
  15338. ov 'modification-hooks
  15339. (list 'org-display-inline-remove-overlay))
  15340. (when (boundp 'image-map)
  15341. (overlay-put ov 'keymap image-map))
  15342. (push ov org-inline-image-overlays))))))))))))))))
  15343. (defvar visual-fill-column-width) ; Silence compiler warning
  15344. (defun org-display-inline-image--width (link)
  15345. "Determine the display width of the image LINK, in pixels.
  15346. - When `org-image-actual-width' is t, the image's pixel width is used.
  15347. - When `org-image-actual-width' is a number, that value will is used.
  15348. - When `org-image-actual-width' is nil or a list, the first :width attribute
  15349. set (if it exists) is used to set the image width. A width of X% is
  15350. divided by 100.
  15351. If no :width attribute is given and `org-image-actual-width' is a list with
  15352. a number as the car, then that number is used as the default value.
  15353. If the value is a float between 0 and 2, it interpreted as that proportion
  15354. of the text width in the buffer."
  15355. ;; Apply `org-image-actual-width' specifications.
  15356. (cond
  15357. ((eq org-image-actual-width t) nil)
  15358. ((listp org-image-actual-width)
  15359. (let* ((case-fold-search t)
  15360. (par (org-element-lineage link '(paragraph)))
  15361. (attr-re "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)")
  15362. (par-end (org-element-property :post-affiliated par))
  15363. ;; Try to find an attribute providing a :width.
  15364. (attr-width
  15365. (when (and par (org-with-point-at
  15366. (org-element-property :begin par)
  15367. (re-search-forward attr-re par-end t)))
  15368. (match-string 1)))
  15369. (attr-width-val
  15370. (cond
  15371. ((null attr-width) nil)
  15372. ((string-match-p "\\`[0-9.]+%" attr-width)
  15373. (/ (string-to-number attr-width) 100.0))
  15374. (t (string-to-number attr-width))))
  15375. ;; Fallback to `org-image-actual-width' if no explicit width is given.
  15376. (width (or attr-width-val (car org-image-actual-width))))
  15377. (if (and (floatp width) (<= 0.0 width 2.0))
  15378. ;; A float in [0,2] should be interpereted as this portion of
  15379. ;; the text width in the window. This works well with cases like
  15380. ;; #+attr_latex: :width 0.X\{line,page,column,etc.}width,
  15381. ;; as the "0.X" is pulled out as a float. We use 2 as the upper
  15382. ;; bound as cases such as 1.2\linewidth are feasible.
  15383. (round (* width
  15384. (window-pixel-width)
  15385. (/ (or (and (bound-and-true-p visual-fill-column-mode)
  15386. (or visual-fill-column-width auto-fill-function))
  15387. (when auto-fill-function fill-column)
  15388. (- (window-text-width) display-line-numbers-width))
  15389. (float (window-total-width)))))
  15390. width)))
  15391. ((numberp org-image-actual-width)
  15392. org-image-actual-width)
  15393. (t nil)))
  15394. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  15395. "Remove inline-display overlay if a corresponding region is modified."
  15396. (let ((inhibit-modification-hooks t))
  15397. (when (and ov after)
  15398. (delete ov org-inline-image-overlays)
  15399. (delete-overlay ov))))
  15400. (defun org-remove-inline-images ()
  15401. "Remove inline display of images."
  15402. (interactive)
  15403. (mapc #'delete-overlay org-inline-image-overlays)
  15404. (setq org-inline-image-overlays nil))
  15405. (defvar org-self-insert-command-undo-counter 0)
  15406. (defvar org-speed-command nil)
  15407. (defun org-self-insert-command (N)
  15408. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  15409. If the cursor is in a table looking at whitespace, the whitespace is
  15410. overwritten, and the table is not marked as requiring realignment."
  15411. (interactive "p")
  15412. (org-check-before-invisible-edit 'insert)
  15413. (cond
  15414. ((and org-use-speed-commands
  15415. (let ((kv (this-command-keys-vector)))
  15416. (setq org-speed-command
  15417. (run-hook-with-args-until-success
  15418. 'org-speed-command-hook
  15419. (make-string 1 (aref kv (1- (length kv))))))))
  15420. (cond
  15421. ((commandp org-speed-command)
  15422. (setq this-command org-speed-command)
  15423. (call-interactively org-speed-command))
  15424. ((functionp org-speed-command)
  15425. (funcall org-speed-command))
  15426. ((and org-speed-command (listp org-speed-command))
  15427. (eval org-speed-command))
  15428. (t (let (org-use-speed-commands)
  15429. (call-interactively 'org-self-insert-command)))))
  15430. ((and
  15431. (= N 1)
  15432. (not (org-region-active-p))
  15433. (org-at-table-p)
  15434. (progn
  15435. ;; Check if we blank the field, and if that triggers align.
  15436. (and (featurep 'org-table)
  15437. org-table-auto-blank-field
  15438. (memq last-command
  15439. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  15440. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  15441. ;; Got extra space, this field does not determine
  15442. ;; column width.
  15443. (let (org-table-may-need-update) (org-table-blank-field))
  15444. ;; No extra space, this field may determine column
  15445. ;; width.
  15446. (org-table-blank-field)))
  15447. t)
  15448. (looking-at "[^|\n]* |"))
  15449. ;; There is room for insertion without re-aligning the table.
  15450. (self-insert-command N)
  15451. (org-table-with-shrunk-field
  15452. (save-excursion
  15453. (skip-chars-forward "^|")
  15454. ;; Do not delete last space, which is
  15455. ;; `org-table-separator-space', but the regular space before
  15456. ;; it.
  15457. (delete-region (- (point) 2) (1- (point))))))
  15458. (t
  15459. (setq org-table-may-need-update t)
  15460. (self-insert-command N)
  15461. (org-fix-tags-on-the-fly)
  15462. (when org-self-insert-cluster-for-undo
  15463. (if (not (eq last-command 'org-self-insert-command))
  15464. (setq org-self-insert-command-undo-counter 1)
  15465. (if (>= org-self-insert-command-undo-counter 20)
  15466. (setq org-self-insert-command-undo-counter 1)
  15467. (and (> org-self-insert-command-undo-counter 0)
  15468. buffer-undo-list (listp buffer-undo-list)
  15469. (not (cadr buffer-undo-list)) ; remove nil entry
  15470. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  15471. (setq org-self-insert-command-undo-counter
  15472. (1+ org-self-insert-command-undo-counter))))))))
  15473. (defun org-check-before-invisible-edit (kind)
  15474. "Check if editing kind KIND would be dangerous with invisible text around.
  15475. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  15476. ;; First, try to get out of here as quickly as possible, to reduce overhead
  15477. (when (and org-catch-invisible-edits
  15478. (or (not (boundp 'visible-mode)) (not visible-mode))
  15479. (or (get-char-property (point) 'invisible)
  15480. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  15481. ;; OK, we need to take a closer look. Do not consider
  15482. ;; invisibility obtained through text properties (e.g., link
  15483. ;; fontification), as it cannot be toggled.
  15484. (let* ((invisible-at-point
  15485. (pcase (get-char-property-and-overlay (point) 'invisible)
  15486. (`(,_ . ,(and (pred overlayp) o)) o)))
  15487. ;; Assume that point cannot land in the middle of an
  15488. ;; overlay, or between two overlays.
  15489. (invisible-before-point
  15490. (and (not invisible-at-point)
  15491. (not (bobp))
  15492. (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  15493. (`(,_ . ,(and (pred overlayp) o)) o))))
  15494. (border-and-ok-direction
  15495. (or
  15496. ;; Check if we are acting predictably before invisible
  15497. ;; text.
  15498. (and invisible-at-point
  15499. (memq kind '(insert delete-backward)))
  15500. ;; Check if we are acting predictably after invisible text
  15501. ;; This works not well, and I have turned it off. It seems
  15502. ;; better to always show and stop after invisible text.
  15503. ;; (and (not invisible-at-point) invisible-before-point
  15504. ;; (memq kind '(insert delete)))
  15505. )))
  15506. (when (or invisible-at-point invisible-before-point)
  15507. (when (eq org-catch-invisible-edits 'error)
  15508. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  15509. (if (and org-custom-properties-overlays
  15510. (y-or-n-p "Display invisible properties in this buffer? "))
  15511. (org-toggle-custom-properties-visibility)
  15512. ;; Make the area visible
  15513. (save-excursion
  15514. (when invisible-before-point
  15515. (goto-char
  15516. (previous-single-char-property-change (point) 'invisible)))
  15517. ;; Remove whatever overlay is currently making yet-to-be
  15518. ;; edited text invisible. Also remove nested invisibility
  15519. ;; related overlays.
  15520. (delete-overlay (or invisible-at-point invisible-before-point))
  15521. (let ((origin (if invisible-at-point (point) (1- (point)))))
  15522. (while (pcase (get-char-property-and-overlay origin 'invisible)
  15523. (`(,_ . ,(and (pred overlayp) o))
  15524. (delete-overlay o)
  15525. t)))))
  15526. (cond
  15527. ((eq org-catch-invisible-edits 'show)
  15528. ;; That's it, we do the edit after showing
  15529. (message
  15530. "Unfolding invisible region around point before editing")
  15531. (sit-for 1))
  15532. ((and (eq org-catch-invisible-edits 'smart)
  15533. border-and-ok-direction)
  15534. (message "Unfolding invisible region around point before editing"))
  15535. (t
  15536. ;; Don't do the edit, make the user repeat it in full visibility
  15537. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  15538. (defun org-fix-tags-on-the-fly ()
  15539. "Align tags in headline at point.
  15540. Unlike `org-align-tags', this function does nothing if point is
  15541. either not currently on a tagged headline or on a tag."
  15542. (when (and (org-match-line org-tag-line-re)
  15543. (< (point) (match-beginning 1)))
  15544. (org-align-tags)))
  15545. (defun org-delete-backward-char (N)
  15546. "Like `delete-backward-char', insert whitespace at field end in tables.
  15547. When deleting backwards, in tables this function will insert whitespace in
  15548. front of the next \"|\" separator, to keep the table aligned. The table will
  15549. still be marked for re-alignment if the field did fill the entire column,
  15550. because, in this case the deletion might narrow the column."
  15551. (interactive "p")
  15552. (save-match-data
  15553. (org-check-before-invisible-edit 'delete-backward)
  15554. (if (and (= N 1)
  15555. (not overwrite-mode)
  15556. (not (org-region-active-p))
  15557. (not (eq (char-before) ?|))
  15558. (save-excursion (skip-chars-backward " \t") (not (bolp)))
  15559. (looking-at-p ".*?|")
  15560. (org-at-table-p))
  15561. (progn (forward-char -1) (org-delete-char 1))
  15562. (backward-delete-char N)
  15563. (org-fix-tags-on-the-fly))))
  15564. (defun org-delete-char (N)
  15565. "Like `delete-char', but insert whitespace at field end in tables.
  15566. When deleting characters, in tables this function will insert whitespace in
  15567. front of the next \"|\" separator, to keep the table aligned. The table will
  15568. still be marked for re-alignment if the field did fill the entire column,
  15569. because, in this case the deletion might narrow the column."
  15570. (interactive "p")
  15571. (save-match-data
  15572. (org-check-before-invisible-edit 'delete)
  15573. (cond
  15574. ((or (/= N 1)
  15575. (eq (char-after) ?|)
  15576. (save-excursion (skip-chars-backward " \t") (bolp))
  15577. (not (org-at-table-p)))
  15578. (delete-char N)
  15579. (org-fix-tags-on-the-fly))
  15580. ((looking-at ".\\(.*?\\)|")
  15581. (let* ((update? org-table-may-need-update)
  15582. (noalign (looking-at-p ".*? |")))
  15583. (delete-char 1)
  15584. (org-table-with-shrunk-field
  15585. (save-excursion
  15586. ;; Last space is `org-table-separator-space', so insert
  15587. ;; a regular one before it instead.
  15588. (goto-char (- (match-end 0) 2))
  15589. (insert " ")))
  15590. ;; If there were two spaces at the end, this field does not
  15591. ;; determine the width of the column.
  15592. (when noalign (setq org-table-may-need-update update?))))
  15593. (t
  15594. (delete-char N)))))
  15595. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  15596. (put 'org-self-insert-command 'delete-selection
  15597. (lambda ()
  15598. (not (run-hook-with-args-until-success
  15599. 'self-insert-uses-region-functions))))
  15600. (put 'orgtbl-self-insert-command 'delete-selection
  15601. (lambda ()
  15602. (not (run-hook-with-args-until-success
  15603. 'self-insert-uses-region-functions))))
  15604. (put 'org-delete-char 'delete-selection 'supersede)
  15605. (put 'org-delete-backward-char 'delete-selection 'supersede)
  15606. (put 'org-yank 'delete-selection 'yank)
  15607. (put 'org-return 'delete-selection t)
  15608. ;; Make `flyspell-mode' delay after some commands
  15609. (put 'org-self-insert-command 'flyspell-delayed t)
  15610. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  15611. (put 'org-delete-char 'flyspell-delayed t)
  15612. (put 'org-delete-backward-char 'flyspell-delayed t)
  15613. ;; Make pabbrev-mode expand after Org mode commands
  15614. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  15615. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  15616. (defun org-transpose-words ()
  15617. "Transpose words for Org.
  15618. This uses the `org-mode-transpose-word-syntax-table' syntax
  15619. table, which interprets characters in `org-emphasis-alist' as
  15620. word constituents."
  15621. (interactive)
  15622. (with-syntax-table org-mode-transpose-word-syntax-table
  15623. (call-interactively 'transpose-words)))
  15624. (defvar org-ctrl-c-ctrl-c-hook nil
  15625. "Hook for functions attaching themselves to `C-c C-c'.
  15626. This can be used to add additional functionality to the `C-c C-c'
  15627. key which executes context-dependent commands. This hook is run
  15628. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  15629. run after the last test.
  15630. Each function will be called with no arguments. The function
  15631. must check if the context is appropriate for it to act. If yes,
  15632. it should do its thing and then return a non-nil value. If the
  15633. context is wrong, just do nothing and return nil.")
  15634. (defvar org-ctrl-c-ctrl-c-final-hook nil
  15635. "Hook for functions attaching themselves to `C-c C-c'.
  15636. This can be used to add additional functionality to the `C-c C-c'
  15637. key which executes context-dependent commands. This hook is run
  15638. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  15639. before the first test.
  15640. Each function will be called with no arguments. The function
  15641. must check if the context is appropriate for it to act. If yes,
  15642. it should do its thing and then return a non-nil value. If the
  15643. context is wrong, just do nothing and return nil.")
  15644. (defvar org-tab-first-hook nil
  15645. "Hook for functions to attach themselves to TAB.
  15646. See `org-ctrl-c-ctrl-c-hook' for more information.
  15647. This hook runs as the first action when TAB is pressed, even before
  15648. `org-cycle' messes around with the `outline-regexp' to cater for
  15649. inline tasks and plain list item folding.
  15650. If any function in this hook returns t, any other actions that
  15651. would have been caused by TAB (such as table field motion or visibility
  15652. cycling) will not occur.")
  15653. (defvar org-tab-after-check-for-table-hook nil
  15654. "Hook for functions to attach themselves to TAB.
  15655. See `org-ctrl-c-ctrl-c-hook' for more information.
  15656. This hook runs after it has been established that the cursor is not in a
  15657. table, but before checking if the cursor is in a headline or if global cycling
  15658. should be done.
  15659. If any function in this hook returns t, not other actions like visibility
  15660. cycling will be done.")
  15661. (defvar org-tab-after-check-for-cycling-hook nil
  15662. "Hook for functions to attach themselves to TAB.
  15663. See `org-ctrl-c-ctrl-c-hook' for more information.
  15664. This hook runs after it has been established that not table field motion and
  15665. not visibility should be done because of current context. This is probably
  15666. the place where a package like yasnippets can hook in.")
  15667. (defvar org-tab-before-tab-emulation-hook nil
  15668. "Hook for functions to attach themselves to TAB.
  15669. See `org-ctrl-c-ctrl-c-hook' for more information.
  15670. This hook runs after every other options for TAB have been exhausted, but
  15671. before indentation and \t insertion takes place.")
  15672. (defvar org-metaleft-hook nil
  15673. "Hook for functions attaching themselves to `M-left'.
  15674. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15675. (defvar org-metaright-hook nil
  15676. "Hook for functions attaching themselves to `M-right'.
  15677. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15678. (defvar org-metaup-hook nil
  15679. "Hook for functions attaching themselves to `M-up'.
  15680. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15681. (defvar org-metadown-hook nil
  15682. "Hook for functions attaching themselves to `M-down'.
  15683. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15684. (defvar org-shiftmetaleft-hook nil
  15685. "Hook for functions attaching themselves to `M-S-left'.
  15686. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15687. (defvar org-shiftmetaright-hook nil
  15688. "Hook for functions attaching themselves to `M-S-right'.
  15689. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15690. (defvar org-shiftmetaup-hook nil
  15691. "Hook for functions attaching themselves to `M-S-up'.
  15692. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15693. (defvar org-shiftmetadown-hook nil
  15694. "Hook for functions attaching themselves to `M-S-down'.
  15695. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15696. (defvar org-metareturn-hook nil
  15697. "Hook for functions attaching themselves to `M-RET'.
  15698. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15699. (defvar org-shiftup-hook nil
  15700. "Hook for functions attaching themselves to `S-up'.
  15701. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15702. (defvar org-shiftup-final-hook nil
  15703. "Hook for functions attaching themselves to `S-up'.
  15704. This one runs after all other options except shift-select have been excluded.
  15705. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15706. (defvar org-shiftdown-hook nil
  15707. "Hook for functions attaching themselves to `S-down'.
  15708. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15709. (defvar org-shiftdown-final-hook nil
  15710. "Hook for functions attaching themselves to `S-down'.
  15711. This one runs after all other options except shift-select have been excluded.
  15712. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15713. (defvar org-shiftleft-hook nil
  15714. "Hook for functions attaching themselves to `S-left'.
  15715. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15716. (defvar org-shiftleft-final-hook nil
  15717. "Hook for functions attaching themselves to `S-left'.
  15718. This one runs after all other options except shift-select have been excluded.
  15719. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15720. (defvar org-shiftright-hook nil
  15721. "Hook for functions attaching themselves to `S-right'.
  15722. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15723. (defvar org-shiftright-final-hook nil
  15724. "Hook for functions attaching themselves to `S-right'.
  15725. This one runs after all other options except shift-select have been excluded.
  15726. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15727. (defun org-modifier-cursor-error ()
  15728. "Throw an error, a modified cursor command was applied in wrong context."
  15729. (user-error "This command is active in special context like tables, headlines or items"))
  15730. (defun org-shiftselect-error ()
  15731. "Throw an error because Shift-Cursor command was applied in wrong context."
  15732. (if (and (boundp 'shift-select-mode) shift-select-mode)
  15733. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  15734. (user-error "This command works only in special context like headlines or timestamps")))
  15735. (defun org-call-for-shift-select (cmd)
  15736. (let ((this-command-keys-shift-translated t))
  15737. (call-interactively cmd)))
  15738. (defun org-shifttab (&optional arg)
  15739. "Global visibility cycling or move to previous table field.
  15740. Call `org-table-previous-field' within a table.
  15741. When ARG is nil, cycle globally through visibility states.
  15742. When ARG is a numeric prefix, show contents of this level."
  15743. (interactive "P")
  15744. (cond
  15745. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  15746. ((integerp arg)
  15747. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  15748. (message "Content view to level: %d" arg)
  15749. (org-content (prefix-numeric-value arg2))
  15750. (org-cycle-show-empty-lines t)
  15751. (setq org-cycle-global-status 'overview)
  15752. (run-hook-with-args 'org-cycle-hook 'overview)))
  15753. (t (call-interactively 'org-global-cycle))))
  15754. (defun org-shiftmetaleft ()
  15755. "Promote subtree or delete table column.
  15756. Calls `org-promote-subtree', `org-outdent-item-tree', or
  15757. `org-table-delete-column', depending on context. See the
  15758. individual commands for more information."
  15759. (interactive)
  15760. (cond
  15761. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  15762. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  15763. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  15764. ((if (not (org-region-active-p)) (org-at-item-p)
  15765. (save-excursion (goto-char (region-beginning))
  15766. (org-at-item-p)))
  15767. (call-interactively 'org-outdent-item-tree))
  15768. (t (org-modifier-cursor-error))))
  15769. (defun org-shiftmetaright ()
  15770. "Demote subtree or insert table column.
  15771. Calls `org-demote-subtree', `org-indent-item-tree', or
  15772. `org-table-insert-column', depending on context. See the
  15773. individual commands for more information."
  15774. (interactive)
  15775. (cond
  15776. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  15777. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  15778. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  15779. ((if (not (org-region-active-p)) (org-at-item-p)
  15780. (save-excursion (goto-char (region-beginning))
  15781. (org-at-item-p)))
  15782. (call-interactively 'org-indent-item-tree))
  15783. (t (org-modifier-cursor-error))))
  15784. (defun org-shiftmetaup (&optional _arg)
  15785. "Drag the line at point up.
  15786. In a table, kill the current row.
  15787. On a clock timestamp, update the value of the timestamp like `S-<up>'
  15788. but also adjust the previous clocked item in the clock history.
  15789. Everywhere else, drag the line at point up."
  15790. (interactive "P")
  15791. (cond
  15792. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  15793. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  15794. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15795. (call-interactively 'org-timestamp-up)))
  15796. (t (call-interactively 'org-drag-line-backward))))
  15797. (defun org-shiftmetadown (&optional _arg)
  15798. "Drag the line at point down.
  15799. In a table, insert an empty row at the current line.
  15800. On a clock timestamp, update the value of the timestamp like `S-<down>'
  15801. but also adjust the previous clocked item in the clock history.
  15802. Everywhere else, drag the line at point down."
  15803. (interactive "P")
  15804. (cond
  15805. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  15806. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  15807. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15808. (call-interactively 'org-timestamp-down)))
  15809. (t (call-interactively 'org-drag-line-forward))))
  15810. (defsubst org-hidden-tree-error ()
  15811. (user-error
  15812. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  15813. (defun org-metaleft (&optional _arg)
  15814. "Promote heading, list item at point or move table column left.
  15815. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  15816. depending on context. With no specific context, calls the Emacs
  15817. default `backward-word'. See the individual commands for more
  15818. information.
  15819. This function runs the hook `org-metaleft-hook' as a first step,
  15820. and returns at first non-nil value."
  15821. (interactive "P")
  15822. (cond
  15823. ((run-hook-with-args-until-success 'org-metaleft-hook))
  15824. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  15825. ((org-with-limited-levels
  15826. (or (org-at-heading-p)
  15827. (and (org-region-active-p)
  15828. (save-excursion
  15829. (goto-char (region-beginning))
  15830. (org-at-heading-p)))))
  15831. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15832. (call-interactively 'org-do-promote))
  15833. ;; At an inline task.
  15834. ((org-at-heading-p)
  15835. (call-interactively 'org-inlinetask-promote))
  15836. ((or (org-at-item-p)
  15837. (and (org-region-active-p)
  15838. (save-excursion
  15839. (goto-char (region-beginning))
  15840. (org-at-item-p))))
  15841. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15842. (call-interactively 'org-outdent-item))
  15843. (t (call-interactively 'backward-word))))
  15844. (defun org-metaright (&optional _arg)
  15845. "Demote heading, list item at point or move table column right.
  15846. In front of a drawer or a block keyword, indent it correctly.
  15847. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  15848. `org-indent-drawer' or `org-indent-block' depending on context.
  15849. With no specific context, calls the Emacs default `forward-word'.
  15850. See the individual commands for more information.
  15851. This function runs the hook `org-metaright-hook' as a first step,
  15852. and returns at first non-nil value."
  15853. (interactive "P")
  15854. (cond
  15855. ((run-hook-with-args-until-success 'org-metaright-hook))
  15856. ((org-at-table-p) (call-interactively 'org-table-move-column))
  15857. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  15858. ((org-at-block-p) (call-interactively 'org-indent-block))
  15859. ((org-with-limited-levels
  15860. (or (org-at-heading-p)
  15861. (and (org-region-active-p)
  15862. (save-excursion
  15863. (goto-char (region-beginning))
  15864. (org-at-heading-p)))))
  15865. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15866. (call-interactively 'org-do-demote))
  15867. ;; At an inline task.
  15868. ((org-at-heading-p)
  15869. (call-interactively 'org-inlinetask-demote))
  15870. ((or (org-at-item-p)
  15871. (and (org-region-active-p)
  15872. (save-excursion
  15873. (goto-char (region-beginning))
  15874. (org-at-item-p))))
  15875. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15876. (call-interactively 'org-indent-item))
  15877. (t (call-interactively 'forward-word))))
  15878. (defun org-check-for-hidden (what)
  15879. "Check if there are hidden headlines/items in the current visual line.
  15880. WHAT can be either `headlines' or `items'. If the current line is
  15881. an outline or item heading and it has a folded subtree below it,
  15882. this function returns t, nil otherwise."
  15883. (let ((re (cond
  15884. ((eq what 'headlines) org-outline-regexp-bol)
  15885. ((eq what 'items) (org-item-beginning-re))
  15886. (t (error "This should not happen"))))
  15887. beg end)
  15888. (save-excursion
  15889. (catch 'exit
  15890. (unless (org-region-active-p)
  15891. (setq beg (point-at-bol))
  15892. (beginning-of-line 2)
  15893. (while (and (not (eobp)) ;; this is like `next-line'
  15894. (get-char-property (1- (point)) 'invisible))
  15895. (beginning-of-line 2))
  15896. (setq end (point))
  15897. (goto-char beg)
  15898. (goto-char (point-at-eol))
  15899. (setq end (max end (point)))
  15900. (while (re-search-forward re end t)
  15901. (when (get-char-property (match-beginning 0) 'invisible)
  15902. (throw 'exit t))))
  15903. nil))))
  15904. (defun org-metaup (&optional _arg)
  15905. "Move subtree up or move table row up.
  15906. Calls `org-move-subtree-up' or `org-table-move-row' or
  15907. `org-move-item-up', depending on context. See the individual commands
  15908. for more information."
  15909. (interactive "P")
  15910. (cond
  15911. ((run-hook-with-args-until-success 'org-metaup-hook))
  15912. ((org-region-active-p)
  15913. (let* ((a (save-excursion
  15914. (goto-char (min (region-beginning) (region-end)))
  15915. (line-beginning-position)))
  15916. (b (save-excursion
  15917. (goto-char (max (region-beginning) (region-end)))
  15918. (if (bolp) (1- (point)) (line-end-position))))
  15919. (c (save-excursion
  15920. (goto-char a)
  15921. (move-beginning-of-line 0)
  15922. (point)))
  15923. (d (save-excursion
  15924. (goto-char a)
  15925. (move-end-of-line 0)
  15926. (point))))
  15927. (transpose-regions a b c d)
  15928. (goto-char c)))
  15929. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  15930. ((and (featurep 'org-inlinetask)
  15931. (org-inlinetask-in-task-p))
  15932. (org-drag-element-backward))
  15933. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  15934. ((org-at-item-p) (call-interactively 'org-move-item-up))
  15935. (t (org-drag-element-backward))))
  15936. (defun org-metadown (&optional _arg)
  15937. "Move subtree down or move table row down.
  15938. Calls `org-move-subtree-down' or `org-table-move-row' or
  15939. `org-move-item-down', depending on context. See the individual
  15940. commands for more information."
  15941. (interactive "P")
  15942. (cond
  15943. ((run-hook-with-args-until-success 'org-metadown-hook))
  15944. ((org-region-active-p)
  15945. (let* ((a (save-excursion
  15946. (goto-char (min (region-beginning) (region-end)))
  15947. (line-beginning-position)))
  15948. (b (save-excursion
  15949. (goto-char (max (region-beginning) (region-end)))
  15950. (if (bolp) (1- (point)) (line-end-position))))
  15951. (c (save-excursion
  15952. (goto-char b)
  15953. (move-beginning-of-line (if (bolp) 1 2))
  15954. (point)))
  15955. (d (save-excursion
  15956. (goto-char b)
  15957. (move-end-of-line (if (bolp) 1 2))
  15958. (point))))
  15959. (transpose-regions a b c d)
  15960. (goto-char d)))
  15961. ((org-at-table-p) (call-interactively 'org-table-move-row))
  15962. ((and (featurep 'org-inlinetask)
  15963. (org-inlinetask-in-task-p))
  15964. (org-drag-element-forward))
  15965. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  15966. ((org-at-item-p) (call-interactively 'org-move-item-down))
  15967. (t (org-drag-element-forward))))
  15968. (defun org-shiftup (&optional arg)
  15969. "Act on current element according to context.
  15970. Call `org-timestamp-up' or `org-priority-up', or
  15971. `org-previous-item', or `org-table-move-cell-up'. See the
  15972. individual commands for more information."
  15973. (interactive "P")
  15974. (cond
  15975. ((run-hook-with-args-until-success 'org-shiftup-hook))
  15976. ((and org-support-shift-select (org-region-active-p))
  15977. (org-call-for-shift-select 'previous-line))
  15978. ((org-at-timestamp-p 'lax)
  15979. (call-interactively (if org-edit-timestamp-down-means-later
  15980. 'org-timestamp-down 'org-timestamp-up)))
  15981. ((and (not (eq org-support-shift-select 'always))
  15982. org-priority-enable-commands
  15983. (org-at-heading-p))
  15984. (call-interactively 'org-priority-up))
  15985. ((and (not org-support-shift-select) (org-at-item-p))
  15986. (call-interactively 'org-previous-item))
  15987. ((org-clocktable-try-shift 'up arg))
  15988. ((and (not (eq org-support-shift-select 'always))
  15989. (org-at-table-p))
  15990. (org-table-move-cell-up))
  15991. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  15992. (org-support-shift-select
  15993. (org-call-for-shift-select 'previous-line))
  15994. (t (org-shiftselect-error))))
  15995. (defun org-shiftdown (&optional arg)
  15996. "Act on current element according to context.
  15997. Call `org-timestamp-down' or `org-priority-down', or
  15998. `org-next-item', or `org-table-move-cell-down'. See the
  15999. individual commands for more information."
  16000. (interactive "P")
  16001. (cond
  16002. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  16003. ((and org-support-shift-select (org-region-active-p))
  16004. (org-call-for-shift-select 'next-line))
  16005. ((org-at-timestamp-p 'lax)
  16006. (call-interactively (if org-edit-timestamp-down-means-later
  16007. 'org-timestamp-up 'org-timestamp-down)))
  16008. ((and (not (eq org-support-shift-select 'always))
  16009. org-priority-enable-commands
  16010. (org-at-heading-p))
  16011. (call-interactively 'org-priority-down))
  16012. ((and (not org-support-shift-select) (org-at-item-p))
  16013. (call-interactively 'org-next-item))
  16014. ((org-clocktable-try-shift 'down arg))
  16015. ((and (not (eq org-support-shift-select 'always))
  16016. (org-at-table-p))
  16017. (org-table-move-cell-down))
  16018. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  16019. (org-support-shift-select
  16020. (org-call-for-shift-select 'next-line))
  16021. (t (org-shiftselect-error))))
  16022. (defun org-shiftright (&optional arg)
  16023. "Act on the current element according to context.
  16024. This does one of the following:
  16025. - switch a timestamp at point one day into the future
  16026. - on a headline, switch to the next TODO keyword
  16027. - on an item, switch entire list to the next bullet type
  16028. - on a property line, switch to the next allowed value
  16029. - on a clocktable definition line, move time block into the future
  16030. - in a table, move a single cell right"
  16031. (interactive "P")
  16032. (cond
  16033. ((run-hook-with-args-until-success 'org-shiftright-hook))
  16034. ((and org-support-shift-select (org-region-active-p))
  16035. (org-call-for-shift-select 'forward-char))
  16036. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  16037. ((and (not (eq org-support-shift-select 'always))
  16038. (org-at-heading-p))
  16039. (let ((org-inhibit-logging
  16040. (not org-treat-S-cursor-todo-selection-as-state-change))
  16041. (org-inhibit-blocking
  16042. (not org-treat-S-cursor-todo-selection-as-state-change)))
  16043. (org-call-with-arg 'org-todo 'right)))
  16044. ((or (and org-support-shift-select
  16045. (not (eq org-support-shift-select 'always))
  16046. (org-at-item-bullet-p))
  16047. (and (not org-support-shift-select) (org-at-item-p)))
  16048. (org-call-with-arg 'org-cycle-list-bullet nil))
  16049. ((and (not (eq org-support-shift-select 'always))
  16050. (org-at-property-p))
  16051. (call-interactively 'org-property-next-allowed-value))
  16052. ((org-clocktable-try-shift 'right arg))
  16053. ((and (not (eq org-support-shift-select 'always))
  16054. (org-at-table-p))
  16055. (org-table-move-cell-right))
  16056. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  16057. (org-support-shift-select
  16058. (org-call-for-shift-select 'forward-char))
  16059. (t (org-shiftselect-error))))
  16060. (defun org-shiftleft (&optional arg)
  16061. "Act on current element according to context.
  16062. This does one of the following:
  16063. - switch a timestamp at point one day into the past
  16064. - on a headline, switch to the previous TODO keyword.
  16065. - on an item, switch entire list to the previous bullet type
  16066. - on a property line, switch to the previous allowed value
  16067. - on a clocktable definition line, move time block into the past
  16068. - in a table, move a single cell left"
  16069. (interactive "P")
  16070. (cond
  16071. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  16072. ((and org-support-shift-select (org-region-active-p))
  16073. (org-call-for-shift-select 'backward-char))
  16074. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  16075. ((and (not (eq org-support-shift-select 'always))
  16076. (org-at-heading-p))
  16077. (let ((org-inhibit-logging
  16078. (not org-treat-S-cursor-todo-selection-as-state-change))
  16079. (org-inhibit-blocking
  16080. (not org-treat-S-cursor-todo-selection-as-state-change)))
  16081. (org-call-with-arg 'org-todo 'left)))
  16082. ((or (and org-support-shift-select
  16083. (not (eq org-support-shift-select 'always))
  16084. (org-at-item-bullet-p))
  16085. (and (not org-support-shift-select) (org-at-item-p)))
  16086. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  16087. ((and (not (eq org-support-shift-select 'always))
  16088. (org-at-property-p))
  16089. (call-interactively 'org-property-previous-allowed-value))
  16090. ((org-clocktable-try-shift 'left arg))
  16091. ((and (not (eq org-support-shift-select 'always))
  16092. (org-at-table-p))
  16093. (org-table-move-cell-left))
  16094. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  16095. (org-support-shift-select
  16096. (org-call-for-shift-select 'backward-char))
  16097. (t (org-shiftselect-error))))
  16098. (defun org-shiftcontrolright ()
  16099. "Switch to next TODO set."
  16100. (interactive)
  16101. (cond
  16102. ((and org-support-shift-select (org-region-active-p))
  16103. (org-call-for-shift-select 'forward-word))
  16104. ((and (not (eq org-support-shift-select 'always))
  16105. (org-at-heading-p))
  16106. (org-call-with-arg 'org-todo 'nextset))
  16107. (org-support-shift-select
  16108. (org-call-for-shift-select 'forward-word))
  16109. (t (org-shiftselect-error))))
  16110. (defun org-shiftcontrolleft ()
  16111. "Switch to previous TODO set."
  16112. (interactive)
  16113. (cond
  16114. ((and org-support-shift-select (org-region-active-p))
  16115. (org-call-for-shift-select 'backward-word))
  16116. ((and (not (eq org-support-shift-select 'always))
  16117. (org-at-heading-p))
  16118. (org-call-with-arg 'org-todo 'previousset))
  16119. (org-support-shift-select
  16120. (org-call-for-shift-select 'backward-word))
  16121. (t (org-shiftselect-error))))
  16122. (defun org-shiftcontrolup (&optional n)
  16123. "Change timestamps synchronously up in CLOCK log lines.
  16124. Optional argument N tells to change by that many units."
  16125. (interactive "P")
  16126. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  16127. (let (org-support-shift-select)
  16128. (org-clock-timestamps-up n))
  16129. (user-error "Not at a clock log")))
  16130. (defun org-shiftcontroldown (&optional n)
  16131. "Change timestamps synchronously down in CLOCK log lines.
  16132. Optional argument N tells to change by that many units."
  16133. (interactive "P")
  16134. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  16135. (let (org-support-shift-select)
  16136. (org-clock-timestamps-down n))
  16137. (user-error "Not at a clock log")))
  16138. (defun org-increase-number-at-point (&optional inc)
  16139. "Increment the number at point.
  16140. With an optional prefix numeric argument INC, increment using
  16141. this numeric value."
  16142. (interactive "p")
  16143. (if (not (number-at-point))
  16144. (user-error "Not on a number")
  16145. (unless inc (setq inc 1))
  16146. (let ((pos (point))
  16147. (beg (skip-chars-backward "-+^/*0-9eE."))
  16148. (end (skip-chars-forward "-+^/*0-9eE.")) nap)
  16149. (setq nap (buffer-substring-no-properties
  16150. (+ pos beg) (+ pos beg end)))
  16151. (delete-region (+ pos beg) (+ pos beg end))
  16152. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  16153. (when (org-at-table-p)
  16154. (org-table-align)
  16155. (org-table-end-of-field 1))))
  16156. (defun org-decrease-number-at-point (&optional inc)
  16157. "Decrement the number at point.
  16158. With an optional prefix numeric argument INC, decrement using
  16159. this numeric value."
  16160. (interactive "p")
  16161. (org-increase-number-at-point (- (or inc 1))))
  16162. (defun org-ctrl-c-ret ()
  16163. "Call `org-table-hline-and-move' or `org-insert-heading'."
  16164. (interactive)
  16165. (cond
  16166. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  16167. (t (call-interactively 'org-insert-heading))))
  16168. (defun org-copy-visible (beg end)
  16169. "Copy the visible parts of the region."
  16170. (interactive "r")
  16171. (let ((result ""))
  16172. (while (/= beg end)
  16173. (when (get-char-property beg 'invisible)
  16174. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  16175. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  16176. (setq result (concat result (buffer-substring beg next)))
  16177. (setq beg next)))
  16178. (setq deactivate-mark t)
  16179. (kill-new result)
  16180. (message "Visible strings have been copied to the kill ring.")))
  16181. (defun org-copy-special ()
  16182. "Copy region in table or copy current subtree.
  16183. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  16184. context. See the individual commands for more information."
  16185. (interactive)
  16186. (call-interactively
  16187. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  16188. (defun org-cut-special ()
  16189. "Cut region in table or cut current subtree.
  16190. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  16191. context. See the individual commands for more information."
  16192. (interactive)
  16193. (call-interactively
  16194. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  16195. (defun org-paste-special (arg)
  16196. "Paste rectangular region into table, or past subtree relative to level.
  16197. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  16198. See the individual commands for more information."
  16199. (interactive "P")
  16200. (if (org-at-table-p)
  16201. (org-table-paste-rectangle)
  16202. (org-paste-subtree arg)))
  16203. (defun org-edit-special (&optional arg)
  16204. "Call a special editor for the element at point.
  16205. When at a table, call the formula editor with `org-table-edit-formulas'.
  16206. When in a source code block, call `org-edit-src-code'.
  16207. When in a fixed-width region, call `org-edit-fixed-width-region'.
  16208. When in an export block, call `org-edit-export-block'.
  16209. When in a LaTeX environment, call `org-edit-latex-environment'.
  16210. When at an INCLUDE, SETUPFILE or BIBLIOGRAPHY keyword, visit the included file.
  16211. When at a footnote reference, call `org-edit-footnote-reference'.
  16212. When at a planning line call, `org-deadline' and/or `org-schedule'.
  16213. When at an active timestamp, call `org-time-stamp'.
  16214. When at an inactive timestamp, call `org-time-stamp-inactive'.
  16215. On a link, call `ffap' to visit the link at point.
  16216. Otherwise, return a user error."
  16217. (interactive "P")
  16218. (let ((element (org-element-at-point)))
  16219. (barf-if-buffer-read-only)
  16220. (pcase (org-element-type element)
  16221. (`src-block
  16222. (if (not arg) (org-edit-src-code)
  16223. (let* ((info (org-babel-get-src-block-info))
  16224. (lang (nth 0 info))
  16225. (params (nth 2 info))
  16226. (session (cdr (assq :session params))))
  16227. (if (not session) (org-edit-src-code)
  16228. ;; At a source block with a session and function called
  16229. ;; with an ARG: switch to the buffer related to the
  16230. ;; inferior process.
  16231. (switch-to-buffer
  16232. (funcall (intern (concat "org-babel-prep-session:" lang))
  16233. session params))))))
  16234. (`keyword
  16235. (unless (member (org-element-property :key element)
  16236. '("BIBLIOGRAPHY" "INCLUDE" "SETUPFILE"))
  16237. (user-error "No special environment to edit here"))
  16238. (let ((value (org-element-property :value element)))
  16239. (unless (org-string-nw-p value) (user-error "No file to edit"))
  16240. (let ((file (and (string-match "\\`\"\\(.*?\\)\"\\|\\S-+" value)
  16241. (or (match-string 1 value)
  16242. (match-string 0 value)))))
  16243. (when (org-url-p file)
  16244. (user-error "Files located with a URL cannot be edited"))
  16245. (org-link-open-from-string
  16246. (format "[[%s]]" (expand-file-name file))))))
  16247. (`table
  16248. (if (eq (org-element-property :type element) 'table.el)
  16249. (org-edit-table.el)
  16250. (call-interactively 'org-table-edit-formulas)))
  16251. ;; Only Org tables contain `table-row' type elements.
  16252. (`table-row (call-interactively 'org-table-edit-formulas))
  16253. (`example-block (org-edit-src-code))
  16254. (`export-block (org-edit-export-block))
  16255. (`fixed-width (org-edit-fixed-width-region))
  16256. (`latex-environment (org-edit-latex-environment))
  16257. (`planning
  16258. (let ((proplist (cadr element)))
  16259. (mapc #'call-interactively
  16260. (remq nil
  16261. (list
  16262. (when (plist-get proplist :deadline) #'org-deadline)
  16263. (when (plist-get proplist :scheduled) #'org-schedule))))))
  16264. (_
  16265. ;; No notable element at point. Though, we may be at a link or
  16266. ;; a footnote reference, which are objects. Thus, scan deeper.
  16267. (let ((context (org-element-context element)))
  16268. (pcase (org-element-type context)
  16269. (`footnote-reference (org-edit-footnote-reference))
  16270. (`inline-src-block (org-edit-inline-src-code))
  16271. (`latex-fragment (org-edit-latex-fragment))
  16272. (`timestamp (if (eq 'inactive (org-element-property :type context))
  16273. (call-interactively #'org-time-stamp-inactive)
  16274. (call-interactively #'org-time-stamp)))
  16275. (`link (call-interactively #'ffap))
  16276. (_ (user-error "No special environment to edit here"))))))))
  16277. (defun org-ctrl-c-ctrl-c (&optional arg)
  16278. "Set tags in headline, or update according to changed information at point.
  16279. This command does many different things, depending on context:
  16280. - If column view is active, in agenda or org buffers, quit it.
  16281. - If there are highlights, remove them.
  16282. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  16283. this is what we do.
  16284. - If the cursor is on a statistics cookie, update it.
  16285. - If the cursor is in a headline, in an agenda or an org buffer,
  16286. prompt for tags and insert them into the current line, aligned
  16287. to `org-tags-column'. When called with prefix arg, realign all
  16288. tags in the current buffer.
  16289. - If the cursor is in one of the special #+KEYWORD lines, this
  16290. triggers scanning the buffer for these lines and updating the
  16291. information.
  16292. - If the cursor is inside a table, realign the table. This command
  16293. works even if the automatic table editor has been turned off.
  16294. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  16295. the entire table.
  16296. - If the cursor is at a footnote reference or definition, jump to
  16297. the corresponding definition or references, respectively.
  16298. - If the cursor is a the beginning of a dynamic block, update it.
  16299. - If the current buffer is a capture buffer, close note and file it.
  16300. - If the cursor is on a <<<target>>>, update radio targets and
  16301. corresponding links in this buffer.
  16302. - If the cursor is on a numbered item in a plain list, renumber the
  16303. ordered list.
  16304. - If the cursor is on a checkbox, toggle it.
  16305. - If the cursor is on a code block, evaluate it. The variable
  16306. `org-confirm-babel-evaluate' can be used to control prompting
  16307. before code block evaluation, by default every code block
  16308. evaluation requires confirmation. Code block evaluation can be
  16309. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  16310. (interactive "P")
  16311. (cond
  16312. ((bound-and-true-p org-columns-overlays) (org-columns-quit))
  16313. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  16314. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  16315. (org-remove-occur-highlights)
  16316. (message "Temporary highlights/overlays removed from current buffer"))
  16317. ((and (local-variable-p 'org-finish-function)
  16318. (fboundp org-finish-function))
  16319. (funcall org-finish-function))
  16320. ((org-babel-hash-at-point))
  16321. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  16322. (t
  16323. (let* ((context
  16324. (org-element-lineage
  16325. (org-element-context)
  16326. ;; Limit to supported contexts.
  16327. '(babel-call clock dynamic-block footnote-definition
  16328. footnote-reference inline-babel-call inline-src-block
  16329. inlinetask item keyword node-property paragraph
  16330. plain-list planning property-drawer radio-target
  16331. src-block statistics-cookie table table-cell table-row
  16332. timestamp)
  16333. t))
  16334. (radio-list-p (org-at-radio-list-p))
  16335. (type (org-element-type context)))
  16336. ;; For convenience: at the first line of a paragraph on the same
  16337. ;; line as an item, apply function on that item instead.
  16338. (when (eq type 'paragraph)
  16339. (let ((parent (org-element-property :parent context)))
  16340. (when (and (eq (org-element-type parent) 'item)
  16341. (= (line-beginning-position)
  16342. (org-element-property :begin parent)))
  16343. (setq context parent)
  16344. (setq type 'item))))
  16345. ;; Act according to type of element or object at point.
  16346. ;;
  16347. ;; Do nothing on a blank line, except if it is contained in
  16348. ;; a source block. Hence, we first check if point is in such
  16349. ;; a block and then if it is at a blank line.
  16350. (pcase type
  16351. ((or `inline-src-block `src-block)
  16352. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  16353. (org-babel-eval-wipe-error-buffer)
  16354. (org-babel-execute-src-block
  16355. current-prefix-arg (org-babel-get-src-block-info nil context))))
  16356. ((guard (org-match-line "[ \t]*$"))
  16357. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  16358. (user-error
  16359. (substitute-command-keys
  16360. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  16361. ((or `babel-call `inline-babel-call)
  16362. (let ((info (org-babel-lob-get-info context)))
  16363. (when info (org-babel-execute-src-block nil info))))
  16364. (`clock (org-clock-update-time-maybe))
  16365. (`dynamic-block
  16366. (save-excursion
  16367. (goto-char (org-element-property :post-affiliated context))
  16368. (org-update-dblock)))
  16369. (`footnote-definition
  16370. (goto-char (org-element-property :post-affiliated context))
  16371. (call-interactively 'org-footnote-action))
  16372. (`footnote-reference (call-interactively #'org-footnote-action))
  16373. ((or `headline `inlinetask)
  16374. (save-excursion (goto-char (org-element-property :begin context))
  16375. (call-interactively #'org-set-tags-command)))
  16376. (`item
  16377. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  16378. ;; unconditionally, whereas `C-u' will toggle its presence.
  16379. ;; Without a universal argument, if the item has a checkbox,
  16380. ;; toggle it. Otherwise repair the list.
  16381. (if (or radio-list-p
  16382. (and (boundp org-list-checkbox-radio-mode)
  16383. org-list-checkbox-radio-mode))
  16384. (org-toggle-radio-button arg)
  16385. (let* ((box (org-element-property :checkbox context))
  16386. (struct (org-element-property :structure context))
  16387. (old-struct (copy-tree struct))
  16388. (parents (org-list-parents-alist struct))
  16389. (prevs (org-list-prevs-alist struct))
  16390. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  16391. (org-list-set-checkbox
  16392. (org-element-property :begin context) struct
  16393. (cond ((equal arg '(16)) "[-]")
  16394. ((and (not box) (equal arg '(4))) "[ ]")
  16395. ((or (not box) (equal arg '(4))) nil)
  16396. ((eq box 'on) "[ ]")
  16397. (t "[X]")))
  16398. ;; Mimic `org-list-write-struct' but with grabbing a return
  16399. ;; value from `org-list-struct-fix-box'.
  16400. (org-list-struct-fix-ind struct parents 2)
  16401. (org-list-struct-fix-item-end struct)
  16402. (org-list-struct-fix-bul struct prevs)
  16403. (org-list-struct-fix-ind struct parents)
  16404. (let ((block-item
  16405. (org-list-struct-fix-box struct parents prevs orderedp)))
  16406. (if (and box (equal struct old-struct))
  16407. (if (equal arg '(16))
  16408. (message "Checkboxes already reset")
  16409. (user-error "Cannot toggle this checkbox: %s"
  16410. (if (eq box 'on)
  16411. "all subitems checked"
  16412. "unchecked subitems")))
  16413. (org-list-struct-apply-struct struct old-struct)
  16414. (org-update-checkbox-count-maybe))
  16415. (when block-item
  16416. (message "Checkboxes were removed due to empty box at line %d"
  16417. (org-current-line block-item)))))))
  16418. (`plain-list
  16419. ;; At a plain list, with a double C-u argument, set
  16420. ;; checkboxes of each item to "[-]", whereas a single one
  16421. ;; will toggle their presence according to the state of the
  16422. ;; first item in the list. Without an argument, repair the
  16423. ;; list.
  16424. (if (or radio-list-p
  16425. (and (boundp org-list-checkbox-radio-mode)
  16426. org-list-checkbox-radio-mode))
  16427. (org-toggle-radio-button arg)
  16428. (let* ((begin (org-element-property :contents-begin context))
  16429. (struct (org-element-property :structure context))
  16430. (old-struct (copy-tree struct))
  16431. (first-box (save-excursion
  16432. (goto-char begin)
  16433. (looking-at org-list-full-item-re)
  16434. (match-string-no-properties 3)))
  16435. (new-box (cond ((equal arg '(16)) "[-]")
  16436. ((equal arg '(4)) (unless first-box "[ ]"))
  16437. ((equal first-box "[X]") "[ ]")
  16438. (t "[X]"))))
  16439. (cond
  16440. (arg
  16441. (dolist (pos
  16442. (org-list-get-all-items
  16443. begin struct (org-list-prevs-alist struct)))
  16444. (org-list-set-checkbox pos struct new-box)))
  16445. ((and first-box (eq (point) begin))
  16446. ;; For convenience, when point is at bol on the first
  16447. ;; item of the list and no argument is provided, simply
  16448. ;; toggle checkbox of that item, if any.
  16449. (org-list-set-checkbox begin struct new-box)))
  16450. (when (equal
  16451. (org-list-write-struct
  16452. struct (org-list-parents-alist struct) old-struct)
  16453. old-struct)
  16454. (message "Cannot update this checkbox"))
  16455. (org-update-checkbox-count-maybe))))
  16456. (`keyword
  16457. (let ((org-inhibit-startup-visibility-stuff t)
  16458. (org-startup-align-all-tables nil))
  16459. (when (boundp 'org-table-coordinate-overlays)
  16460. (mapc #'delete-overlay org-table-coordinate-overlays)
  16461. (setq org-table-coordinate-overlays nil))
  16462. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  16463. (message "Local setup has been refreshed"))
  16464. ((or `property-drawer `node-property)
  16465. (call-interactively #'org-property-action))
  16466. (`radio-target
  16467. (call-interactively #'org-update-radio-target-regexp))
  16468. (`statistics-cookie
  16469. (call-interactively #'org-update-statistics-cookies))
  16470. ((or `table `table-cell `table-row)
  16471. ;; At a table, generate a plot if on the #+plot line,
  16472. ;; recalculate every field and align it otherwise. Also
  16473. ;; send the table if necessary.
  16474. (cond
  16475. ((and (org-match-line "[ \t]*#\\+plot:")
  16476. (< (point) (org-element-property :post-affiliated context)))
  16477. (org-plot/gnuplot))
  16478. ;; If the table has a `table.el' type, just give up.
  16479. ((eq (org-element-property :type context) 'table.el)
  16480. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  16481. Use `\\[org-edit-special]' to edit table.el tables")))
  16482. ;; At a table row or cell, maybe recalculate line but always
  16483. ;; align table.
  16484. ((or (eq type 'table)
  16485. ;; Check if point is at a TBLFM line.
  16486. (and (eq type 'table-row)
  16487. (= (point) (org-element-property :end context))))
  16488. (save-excursion
  16489. (if (org-at-TBLFM-p)
  16490. (progn (require 'org-table)
  16491. (org-table-calc-current-TBLFM))
  16492. (goto-char (org-element-property :contents-begin context))
  16493. (org-call-with-arg 'org-table-recalculate (or arg t))
  16494. (orgtbl-send-table 'maybe))))
  16495. (t
  16496. (org-table-maybe-eval-formula)
  16497. (cond (arg (call-interactively #'org-table-recalculate))
  16498. ((org-table-maybe-recalculate-line))
  16499. (t (org-table-align))))))
  16500. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  16501. (org-timestamp-change 0 'day))
  16502. ((and `nil (guard (org-at-heading-p)))
  16503. ;; When point is on an unsupported object type, we can miss
  16504. ;; the fact that it also is at a heading. Handle it here.
  16505. (call-interactively #'org-set-tags-command))
  16506. ((guard
  16507. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  16508. (_
  16509. (user-error
  16510. (substitute-command-keys
  16511. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  16512. (defun org-mode-restart ()
  16513. "Restart `org-mode'."
  16514. (interactive)
  16515. (let ((indent-status (bound-and-true-p org-indent-mode)))
  16516. (funcall major-mode)
  16517. (hack-local-variables)
  16518. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  16519. (org-indent-mode -1))
  16520. (org-reset-file-cache))
  16521. (message "%s restarted" major-mode))
  16522. (defun org-flag-above-first-heading (&optional arg)
  16523. "Hide from bob up to the first heading.
  16524. Move point to the beginning of first heading or end of buffer."
  16525. (goto-char (point-min))
  16526. (unless (org-at-heading-p)
  16527. (outline-next-heading))
  16528. (unless (bobp)
  16529. (org-flag-region 1 (1- (point)) (not arg) 'outline)))
  16530. (defun org-show-branches-buffer ()
  16531. "Show all branches in the buffer."
  16532. (org-flag-above-first-heading)
  16533. (outline-hide-sublevels 1)
  16534. (unless (eobp)
  16535. (outline-show-branches)
  16536. (while (outline-get-next-sibling)
  16537. (outline-show-branches)))
  16538. (goto-char (point-min)))
  16539. (defun org-kill-note-or-show-branches ()
  16540. "Abort storing current note, or show just branches."
  16541. (interactive)
  16542. (cond (org-finish-function
  16543. (let ((org-note-abort t)) (funcall org-finish-function)))
  16544. ((org-before-first-heading-p)
  16545. (org-show-branches-buffer)
  16546. (org-hide-archived-subtrees (point-min) (point-max)))
  16547. (t
  16548. (let ((beg (progn (org-back-to-heading) (point)))
  16549. (end (save-excursion (org-end-of-subtree t t) (point))))
  16550. (outline-hide-subtree)
  16551. (outline-show-branches)
  16552. (org-hide-archived-subtrees beg end)))))
  16553. (defun org-delete-indentation (&optional arg)
  16554. "Join current line to previous and fix whitespace at join.
  16555. If previous line is a headline add to headline title. Otherwise
  16556. the function calls `delete-indentation'.
  16557. I.e. with a non-nil optional argument, join the line with the
  16558. following one. If there is a region then join the lines in that
  16559. region."
  16560. (interactive "*P")
  16561. (if (save-excursion
  16562. (beginning-of-line (if arg 1 0))
  16563. (let ((case-fold-search nil))
  16564. (looking-at org-complex-heading-regexp)))
  16565. ;; At headline.
  16566. (let ((tags-column (when (match-beginning 5)
  16567. (save-excursion (goto-char (match-beginning 5))
  16568. (current-column))))
  16569. (string (concat " " (progn (when arg (forward-line 1))
  16570. (org-trim (delete-and-extract-region
  16571. (line-beginning-position)
  16572. (line-end-position)))))))
  16573. (unless (bobp) (delete-region (point) (1- (point))))
  16574. (goto-char (or (match-end 4)
  16575. (match-beginning 5)
  16576. (match-end 0)))
  16577. (skip-chars-backward " \t")
  16578. (save-excursion (insert string))
  16579. ;; Adjust alignment of tags.
  16580. (cond
  16581. ((not tags-column)) ;no tags
  16582. (org-auto-align-tags (org-align-tags))
  16583. (t (org--align-tags-here tags-column)))) ;preserve tags column
  16584. (let ((current-prefix-arg arg))
  16585. (call-interactively #'delete-indentation))))
  16586. (defun org-open-line (n)
  16587. "Insert a new row in tables, call `open-line' elsewhere.
  16588. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  16589. As a special case, when a document starts with a table, allow to
  16590. call `open-line' on the very first character."
  16591. (interactive "*p")
  16592. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  16593. (org-table-insert-row)
  16594. (open-line n)))
  16595. (defun org--newline (indent arg interactive)
  16596. "Call `newline-and-indent' or just `newline'.
  16597. If INDENT is non-nil, call `newline-and-indent' with ARG to
  16598. indent unconditionally; otherwise, call `newline' with ARG and
  16599. INTERACTIVE, which can trigger indentation if
  16600. `electric-indent-mode' is enabled."
  16601. (if indent
  16602. (org-newline-and-indent arg)
  16603. (newline arg interactive)))
  16604. (defun org-return (&optional indent arg interactive)
  16605. "Goto next table row or insert a newline.
  16606. Calls `org-table-next-row' or `newline', depending on context.
  16607. When optional INDENT argument is non-nil, call
  16608. `newline-and-indent' with ARG, otherwise call `newline' with ARG
  16609. and INTERACTIVE.
  16610. When `org-return-follows-link' is non-nil and point is on
  16611. a timestamp or a link, call `org-open-at-point'. However, it
  16612. will not happen if point is in a table or on a \"dead\"
  16613. object (e.g., within a comment). In these case, you need to use
  16614. `org-open-at-point' directly."
  16615. (interactive "i\nP\np")
  16616. (let* ((context (if org-return-follows-link (org-element-context)
  16617. (org-element-at-point)))
  16618. (element-type (org-element-type context)))
  16619. (cond
  16620. ;; In a table, call `org-table-next-row'. However, before first
  16621. ;; column or after last one, split the table.
  16622. ((or (and (eq 'table element-type)
  16623. (not (eq 'table.el (org-element-property :type context)))
  16624. (>= (point) (org-element-property :contents-begin context))
  16625. (< (point) (org-element-property :contents-end context)))
  16626. (org-element-lineage context '(table-row table-cell) t))
  16627. (if (or (looking-at-p "[ \t]*$")
  16628. (save-excursion (skip-chars-backward " \t") (bolp)))
  16629. (insert "\n")
  16630. (org-table-justify-field-maybe)
  16631. (call-interactively #'org-table-next-row)))
  16632. ;; On a link or a timestamp, call `org-open-at-point' if
  16633. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  16634. ;; locations, e.g., in a comment, as `org-open-at-point'.
  16635. ((and org-return-follows-link
  16636. (or (and (eq 'link element-type)
  16637. ;; Ensure point is not on the white spaces after
  16638. ;; the link.
  16639. (let ((origin (point)))
  16640. (org-with-point-at (org-element-property :end context)
  16641. (skip-chars-backward " \t")
  16642. (> (point) origin))))
  16643. (org-in-regexp org-ts-regexp-both nil t)
  16644. (org-in-regexp org-tsr-regexp-both nil t)
  16645. (org-in-regexp org-link-any-re nil t)))
  16646. (call-interactively #'org-open-at-point))
  16647. ;; Insert newline in heading, but preserve tags.
  16648. ((and (not (bolp))
  16649. (let ((case-fold-search nil))
  16650. (org-match-line org-complex-heading-regexp)))
  16651. ;; At headline. Split line. However, if point is on keyword,
  16652. ;; priority cookie or tags, do not break any of them: add
  16653. ;; a newline after the headline instead.
  16654. (let ((tags-column (and (match-beginning 5)
  16655. (save-excursion (goto-char (match-beginning 5))
  16656. (current-column))))
  16657. (string
  16658. (when (and (match-end 4) (org-point-in-group (point) 4))
  16659. (delete-and-extract-region (point) (match-end 4)))))
  16660. ;; Adjust tag alignment.
  16661. (cond
  16662. ((not (and tags-column string)))
  16663. (org-auto-align-tags (org-align-tags))
  16664. (t (org--align-tags-here tags-column))) ;preserve tags column
  16665. (end-of-line)
  16666. (org-show-entry)
  16667. (org--newline indent arg interactive)
  16668. (when string (save-excursion (insert (org-trim string))))))
  16669. ;; In a list, make sure indenting keeps trailing text within.
  16670. ((and (not (eolp))
  16671. (org-element-lineage context '(item)))
  16672. (let ((trailing-data
  16673. (delete-and-extract-region (point) (line-end-position))))
  16674. (org--newline indent arg interactive)
  16675. (save-excursion (insert trailing-data))))
  16676. (t
  16677. ;; Do not auto-fill when point is in an Org property drawer.
  16678. (let ((auto-fill-function (and (not (org-at-property-p))
  16679. auto-fill-function)))
  16680. (org--newline indent arg interactive))))))
  16681. (defun org-return-and-maybe-indent ()
  16682. "Goto next table row, or insert a newline, maybe indented.
  16683. Call `org-table-next-row' or `org-return', depending on context.
  16684. See the individual commands for more information.
  16685. When inserting a newline, if `org-adapt-indentation' is t:
  16686. indent the line if `electric-indent-mode' is disabled, don't
  16687. indent it if it is enabled."
  16688. (interactive)
  16689. (org-return (not electric-indent-mode)))
  16690. (defun org-ctrl-c-tab (&optional arg)
  16691. "Toggle columns width in a table, or show children.
  16692. Call `org-table-toggle-column-width' if point is in a table.
  16693. Otherwise provide a compact view of the children. ARG is the
  16694. level to hide."
  16695. (interactive "p")
  16696. (cond
  16697. ((org-at-table-p)
  16698. (call-interactively #'org-table-toggle-column-width))
  16699. ((org-before-first-heading-p)
  16700. (save-excursion
  16701. (org-flag-above-first-heading)
  16702. (outline-hide-sublevels (or arg 1))))
  16703. (t
  16704. (outline-hide-subtree)
  16705. (org-show-children arg))))
  16706. (defun org-ctrl-c-star ()
  16707. "Compute table, or change heading status of lines.
  16708. Calls `org-table-recalculate' or `org-toggle-heading',
  16709. depending on context."
  16710. (interactive)
  16711. (cond
  16712. ((org-at-table-p)
  16713. (call-interactively 'org-table-recalculate))
  16714. (t
  16715. ;; Convert all lines in region to list items
  16716. (call-interactively 'org-toggle-heading))))
  16717. (defun org-ctrl-c-minus ()
  16718. "Insert separator line in table or modify bullet status of line.
  16719. Also turns a plain line or a region of lines into list items.
  16720. Calls `org-table-insert-hline', `org-toggle-item', or
  16721. `org-cycle-list-bullet', depending on context."
  16722. (interactive)
  16723. (cond
  16724. ((org-at-table-p)
  16725. (call-interactively 'org-table-insert-hline))
  16726. ((org-region-active-p)
  16727. (call-interactively 'org-toggle-item))
  16728. ((org-in-item-p)
  16729. (call-interactively 'org-cycle-list-bullet))
  16730. (t
  16731. (call-interactively 'org-toggle-item))))
  16732. (defun org-toggle-heading (&optional nstars)
  16733. "Convert headings to normal text, or items or text to headings.
  16734. If there is no active region, only convert the current line.
  16735. With a `\\[universal-argument]' prefix, convert the whole list at
  16736. point into heading.
  16737. In a region:
  16738. - If the first non blank line is a headline, remove the stars
  16739. from all headlines in the region.
  16740. - If it is a normal line, turn each and every normal line (i.e.,
  16741. not an heading or an item) in the region into headings. If you
  16742. want to convert only the first line of this region, use one
  16743. universal prefix argument.
  16744. - If it is a plain list item, turn all plain list items into headings.
  16745. When converting a line into a heading, the number of stars is chosen
  16746. such that the lines become children of the current entry. However,
  16747. when a numeric prefix argument is given, its value determines the
  16748. number of stars to add."
  16749. (interactive "P")
  16750. (let ((skip-blanks
  16751. ;; Return beginning of first non-blank line, starting from
  16752. ;; line at POS.
  16753. (lambda (pos)
  16754. (save-excursion
  16755. (goto-char pos)
  16756. (while (org-at-comment-p) (forward-line))
  16757. (skip-chars-forward " \r\t\n")
  16758. (point-at-bol))))
  16759. beg end toggled)
  16760. ;; Determine boundaries of changes. If a universal prefix has
  16761. ;; been given, put the list in a region. If region ends at a bol,
  16762. ;; do not consider the last line to be in the region.
  16763. (when (and current-prefix-arg (org-at-item-p))
  16764. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  16765. (org-mark-element))
  16766. (if (org-region-active-p)
  16767. (setq beg (funcall skip-blanks (region-beginning))
  16768. end (copy-marker (save-excursion
  16769. (goto-char (region-end))
  16770. (if (bolp) (point) (point-at-eol)))))
  16771. (setq beg (funcall skip-blanks (point-at-bol))
  16772. end (copy-marker (point-at-eol))))
  16773. ;; Ensure inline tasks don't count as headings.
  16774. (org-with-limited-levels
  16775. (save-excursion
  16776. (goto-char beg)
  16777. (cond
  16778. ;; Case 1. Started at an heading: de-star headings.
  16779. ((org-at-heading-p)
  16780. (while (< (point) end)
  16781. (when (org-at-heading-p t)
  16782. (looking-at org-outline-regexp) (replace-match "")
  16783. (setq toggled t))
  16784. (forward-line)))
  16785. ;; Case 2. Started at an item: change items into headlines.
  16786. ;; One star will be added by `org-list-to-subtree'.
  16787. ((org-at-item-p)
  16788. (while (< (point) end)
  16789. (when (org-at-item-p)
  16790. ;; Pay attention to cases when region ends before list.
  16791. (let* ((struct (org-list-struct))
  16792. (list-end
  16793. (min (org-list-get-bottom-point struct) (1+ end))))
  16794. (save-restriction
  16795. (narrow-to-region (point) list-end)
  16796. (insert (org-list-to-subtree
  16797. (org-list-to-lisp t)
  16798. (pcase (org-current-level)
  16799. (`nil 1)
  16800. (l (1+ (org-reduced-level l)))))
  16801. "\n")))
  16802. (setq toggled t))
  16803. (forward-line)))
  16804. ;; Case 3. Started at normal text: make every line an heading,
  16805. ;; skipping headlines and items.
  16806. (t (let* ((stars
  16807. (make-string
  16808. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  16809. (add-stars
  16810. (cond (nstars "") ; stars from prefix only
  16811. ((equal stars "") "*") ; before first heading
  16812. (org-odd-levels-only "**") ; inside heading, odd
  16813. (t "*"))) ; inside heading, oddeven
  16814. (rpl (concat stars add-stars " "))
  16815. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  16816. (while (< (point) (if (equal nstars '(4)) lend end))
  16817. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  16818. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  16819. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  16820. (forward-line)))))))
  16821. (unless toggled (message "Cannot toggle heading from here"))))
  16822. (defun org-meta-return (&optional arg)
  16823. "Insert a new heading or wrap a region in a table.
  16824. Calls `org-insert-heading', `org-insert-item' or
  16825. `org-table-wrap-region', depending on context. When called with
  16826. an argument, unconditionally call `org-insert-heading'."
  16827. (interactive "P")
  16828. (org-check-before-invisible-edit 'insert)
  16829. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  16830. (call-interactively (cond (arg #'org-insert-heading)
  16831. ((org-at-table-p) #'org-table-wrap-region)
  16832. ((org-in-item-p) #'org-insert-item)
  16833. (t #'org-insert-heading)))))
  16834. ;;; Menu entries
  16835. (defsubst org-in-subtree-not-table-p ()
  16836. "Are we in a subtree and not in a table?"
  16837. (and (not (org-before-first-heading-p))
  16838. (not (org-at-table-p))))
  16839. ;; Define the Org mode menus
  16840. (easy-menu-define org-org-menu org-mode-map "Org menu."
  16841. `("Org"
  16842. ("Show/Hide"
  16843. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  16844. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  16845. ["Sparse Tree..." org-sparse-tree t]
  16846. ["Reveal Context" org-reveal t]
  16847. ["Show All" org-show-all t]
  16848. "--"
  16849. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  16850. "--"
  16851. ["New Heading" org-insert-heading t]
  16852. ("Navigate Headings"
  16853. ["Up" outline-up-heading t]
  16854. ["Next" outline-next-visible-heading t]
  16855. ["Previous" outline-previous-visible-heading t]
  16856. ["Next Same Level" outline-forward-same-level t]
  16857. ["Previous Same Level" outline-backward-same-level t]
  16858. "--"
  16859. ["Jump" org-goto t])
  16860. ("Edit Structure"
  16861. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  16862. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  16863. "--"
  16864. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  16865. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  16866. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  16867. "--"
  16868. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  16869. "--"
  16870. ["Copy visible text" org-copy-visible t]
  16871. "--"
  16872. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  16873. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  16874. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  16875. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  16876. "--"
  16877. ["Sort Region/Children" org-sort t]
  16878. "--"
  16879. ["Convert to odd levels" org-convert-to-odd-levels t]
  16880. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  16881. ("Editing"
  16882. ["Emphasis..." org-emphasize t]
  16883. ["Add block structure" org-insert-structure-template t]
  16884. ["Edit Source Example" org-edit-special t]
  16885. "--"
  16886. ["Footnote new/jump" org-footnote-action t]
  16887. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  16888. ("Archive"
  16889. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  16890. "--"
  16891. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  16892. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  16893. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)])
  16894. "--"
  16895. ("Hyperlinks"
  16896. ["Store Link (Global)" org-store-link t]
  16897. ["Find existing link to here" org-occur-link-in-agenda-files t]
  16898. ["Insert Link" org-insert-link t]
  16899. ["Follow Link" org-open-at-point t]
  16900. "--"
  16901. ["Next link" org-next-link t]
  16902. ["Previous link" org-previous-link t]
  16903. "--"
  16904. ["Descriptive Links"
  16905. org-toggle-link-display
  16906. :style radio
  16907. :selected org-descriptive-links
  16908. ]
  16909. ["Literal Links"
  16910. org-toggle-link-display
  16911. :style radio
  16912. :selected (not org-descriptive-links)])
  16913. "--"
  16914. ("TODO Lists"
  16915. ["TODO/DONE/-" org-todo t]
  16916. ("Select keyword"
  16917. ["Next keyword" org-shiftright (org-at-heading-p)]
  16918. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  16919. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  16920. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  16921. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  16922. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  16923. ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  16924. "--"
  16925. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  16926. :selected org-enforce-todo-dependencies :style toggle :active t]
  16927. "Settings for tree at point"
  16928. ["Do Children sequentially" org-toggle-ordered-property :style radio
  16929. :selected (org-entry-get nil "ORDERED")
  16930. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16931. ["Do Children parallel" org-toggle-ordered-property :style radio
  16932. :selected (not (org-entry-get nil "ORDERED"))
  16933. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16934. "--"
  16935. ["Set Priority" org-priority t]
  16936. ["Priority Up" org-shiftup t]
  16937. ["Priority Down" org-shiftdown t]
  16938. "--"
  16939. ["Get news from all feeds" org-feed-update-all t]
  16940. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  16941. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  16942. ("TAGS and Properties"
  16943. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  16944. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  16945. "--"
  16946. ["Set property" org-set-property (not (org-before-first-heading-p))]
  16947. ["Column view of properties" org-columns t]
  16948. ["Insert Column View DBlock" org-columns-insert-dblock t])
  16949. ("Dates and Scheduling"
  16950. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  16951. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  16952. ("Change Date"
  16953. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  16954. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  16955. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  16956. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  16957. ["Compute Time Range" org-evaluate-time-range t]
  16958. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  16959. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  16960. "--"
  16961. ["Custom time format" org-toggle-time-stamp-overlays
  16962. :style radio :selected org-display-custom-times]
  16963. "--"
  16964. ["Goto Calendar" org-goto-calendar t]
  16965. ["Date from Calendar" org-date-from-calendar t]
  16966. "--"
  16967. ["Start/Restart Timer" org-timer-start t]
  16968. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  16969. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  16970. ["Insert Timer String" org-timer t]
  16971. ["Insert Timer Item" org-timer-item t])
  16972. ("Logging work"
  16973. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  16974. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  16975. ["Clock out" org-clock-out t]
  16976. ["Clock cancel" org-clock-cancel t]
  16977. "--"
  16978. ["Mark as default task" org-clock-mark-default-task t]
  16979. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  16980. ["Goto running clock" org-clock-goto t]
  16981. "--"
  16982. ["Display times" org-clock-display t]
  16983. ["Create clock table" org-clock-report t]
  16984. "--"
  16985. ["Record DONE time"
  16986. (progn (setq org-log-done (not org-log-done))
  16987. (message "Switching to %s will %s record a timestamp"
  16988. (car org-done-keywords)
  16989. (if org-log-done "automatically" "not")))
  16990. :style toggle :selected org-log-done])
  16991. "--"
  16992. ["Agenda Command..." org-agenda t]
  16993. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  16994. ("File List for Agenda")
  16995. ("Special views current file"
  16996. ["TODO Tree" org-show-todo-tree t]
  16997. ["Check Deadlines" org-check-deadlines t]
  16998. ["Tags/Property tree" org-match-sparse-tree t])
  16999. "--"
  17000. ["Export/Publish..." org-export-dispatch t]
  17001. ("LaTeX"
  17002. ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  17003. :style toggle :selected org-cdlatex-mode]
  17004. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  17005. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  17006. ["Modify math symbol" org-cdlatex-math-modify
  17007. (org-inside-LaTeX-fragment-p)]
  17008. ["Insert citation" org-reftex-citation t])
  17009. "--"
  17010. ("Documentation"
  17011. ["Show Version" org-version t]
  17012. ["Info Documentation" org-info t]
  17013. ["Browse Org News" org-browse-news t])
  17014. ("Customize"
  17015. ["Browse Org Group" org-customize t]
  17016. "--"
  17017. ["Expand This Menu" org-create-customize-menu t])
  17018. ["Send bug report" org-submit-bug-report t]
  17019. "--"
  17020. ("Refresh/Reload"
  17021. ["Refresh setup current buffer" org-mode-restart t]
  17022. ["Reload Org (after update)" org-reload t]
  17023. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])))
  17024. (easy-menu-define org-tbl-menu org-mode-map "Org Table menu."
  17025. '("Table"
  17026. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  17027. ["Next Field" org-cycle (org-at-table-p)]
  17028. ["Previous Field" org-shifttab (org-at-table-p)]
  17029. ["Next Row" org-return (org-at-table-p)]
  17030. "--"
  17031. ["Blank Field" org-table-blank-field (org-at-table-p)]
  17032. ["Edit Field" org-table-edit-field (org-at-table-p)]
  17033. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  17034. "--"
  17035. ("Column"
  17036. ["Move Column Left" org-metaleft (org-at-table-p)]
  17037. ["Move Column Right" org-metaright (org-at-table-p)]
  17038. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  17039. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  17040. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  17041. ("Row"
  17042. ["Move Row Up" org-metaup (org-at-table-p)]
  17043. ["Move Row Down" org-metadown (org-at-table-p)]
  17044. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  17045. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  17046. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  17047. "--"
  17048. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  17049. ("Rectangle"
  17050. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  17051. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  17052. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  17053. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  17054. "--"
  17055. ("Calculate"
  17056. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  17057. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  17058. ["Edit Formulas" org-edit-special (org-at-table-p)]
  17059. "--"
  17060. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  17061. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  17062. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  17063. "--"
  17064. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  17065. "--"
  17066. ["Sum Column/Rectangle" org-table-sum
  17067. (or (org-at-table-p) (org-region-active-p))]
  17068. ["Which Column?" org-table-current-column (org-at-table-p)])
  17069. ["Debug Formulas"
  17070. org-table-toggle-formula-debugger
  17071. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  17072. ["Show Col/Row Numbers"
  17073. org-table-toggle-coordinate-overlays
  17074. :style toggle
  17075. :selected (bound-and-true-p org-table-overlay-coordinates)]
  17076. "--"
  17077. ["Create" org-table-create (not (org-at-table-p))]
  17078. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  17079. ["Import from File" org-table-import (not (org-at-table-p))]
  17080. ["Export to File" org-table-export (org-at-table-p)]
  17081. "--"
  17082. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  17083. "--"
  17084. ("Plot"
  17085. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  17086. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  17087. (defun org-info (&optional node)
  17088. "Read documentation for Org in the info system.
  17089. With optional NODE, go directly to that node."
  17090. (interactive)
  17091. (info (format "(org)%s" (or node ""))))
  17092. (defun org-browse-news ()
  17093. "Browse the news for the latest major release."
  17094. (interactive)
  17095. (browse-url "https://orgmode.org/Changes.html"))
  17096. ;;;###autoload
  17097. (defun org-submit-bug-report ()
  17098. "Submit a bug report on Org via mail.
  17099. Don't hesitate to report any problems or inaccurate documentation.
  17100. If you don't have setup sending mail from (X)Emacs, please copy the
  17101. output buffer into your mail program, as it gives us important
  17102. information about your Org version and configuration."
  17103. (interactive)
  17104. (require 'reporter)
  17105. (defvar reporter-prompt-for-summary-p)
  17106. (org-load-modules-maybe)
  17107. (org-require-autoloaded-modules)
  17108. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  17109. (reporter-submit-bug-report
  17110. "emacs-orgmode@gnu.org"
  17111. (org-version nil 'full)
  17112. (let (list)
  17113. (save-window-excursion
  17114. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  17115. (delete-other-windows)
  17116. (erase-buffer)
  17117. (insert "You are about to submit a bug report to the Org mailing list.
  17118. If your report is about Org installation, please read this section:
  17119. https://orgmode.org/org.html#Installation
  17120. Please read https://orgmode.org/org.html#Feedback on how to make
  17121. a good report, it will help Org contributors fixing your problem.
  17122. Search https://lists.gnu.org/archive/html/emacs-orgmode/ to see
  17123. if the issue you are about to raise has already been dealt with.
  17124. We also would like to add your full Org and Outline configuration
  17125. to the bug report. It will help us debugging the issue.
  17126. *HOWEVER*, some variables you have customized may contain private
  17127. information. The names of customers, colleagues, or friends, might
  17128. appear in the form of file names, tags, todo states or search strings.
  17129. If you answer \"yes\" to the prompt, you might want to check and remove
  17130. such private information before sending the email.")
  17131. (add-text-properties (point-min) (point-max) '(face org-warning))
  17132. (when (yes-or-no-p "Include your Org configuration ")
  17133. (mapatoms
  17134. (lambda (v)
  17135. (and (boundp v)
  17136. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  17137. (or (and (symbol-value v)
  17138. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  17139. (and
  17140. (get v 'custom-type) (get v 'standard-value)
  17141. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  17142. (push v list)))))
  17143. (kill-buffer (get-buffer "*Warn about privacy*"))
  17144. list))
  17145. nil nil
  17146. "Remember to cover the basics, that is, what you expected to happen and
  17147. what in fact did happen. You don't know how to make a good report? See
  17148. https://orgmode.org/manual/Feedback.html#Feedback
  17149. Your bug report will be posted to the Org mailing list.
  17150. ------------------------------------------------------------------------")
  17151. (save-excursion
  17152. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  17153. (replace-match "\\1[BUG] \\3 [\\2]")))))
  17154. (defun org-install-agenda-files-menu ()
  17155. "Install agenda file menu."
  17156. (let ((bl (buffer-list)))
  17157. (save-excursion
  17158. (while bl
  17159. (set-buffer (pop bl))
  17160. (when (derived-mode-p 'org-mode) (setq bl nil)))
  17161. (when (derived-mode-p 'org-mode)
  17162. (easy-menu-change
  17163. '("Org") "File List for Agenda"
  17164. (append
  17165. (list
  17166. ["Edit File List" (org-edit-agenda-file-list) t]
  17167. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  17168. ["Remove Current File from List" org-remove-file t]
  17169. ["Cycle through agenda files" org-cycle-agenda-files t]
  17170. ["Occur in all agenda files" org-occur-in-agenda-files t]
  17171. "--")
  17172. (mapcar 'org-file-menu-entry
  17173. ;; Prevent initialization from failing.
  17174. (ignore-errors (org-agenda-files t)))))))))
  17175. ;;;; Documentation
  17176. (defun org-require-autoloaded-modules ()
  17177. (interactive)
  17178. (mapc #'require
  17179. '(org-agenda org-archive org-attach org-clock org-colview org-id
  17180. org-table org-timer)))
  17181. ;;;###autoload
  17182. (defun org-reload (&optional uncompiled)
  17183. "Reload all Org Lisp files.
  17184. With prefix arg UNCOMPILED, load the uncompiled versions."
  17185. (interactive "P")
  17186. (require 'loadhist)
  17187. (let* ((org-dir (org-find-library-dir "org"))
  17188. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  17189. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  17190. (remove-re (format "\\`%s\\'"
  17191. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  17192. (feats (delete-dups
  17193. (mapcar 'file-name-sans-extension
  17194. (mapcar 'file-name-nondirectory
  17195. (delq nil
  17196. (mapcar 'feature-file
  17197. features))))))
  17198. (lfeat (append
  17199. (sort
  17200. (setq feats
  17201. (delq nil (mapcar
  17202. (lambda (f)
  17203. (if (and (string-match feature-re f)
  17204. (not (string-match remove-re f)))
  17205. f nil))
  17206. feats)))
  17207. 'string-lessp)
  17208. (list "org-version" "org")))
  17209. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  17210. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  17211. load-uncore load-misses)
  17212. (setq load-misses
  17213. (delq 't
  17214. (mapcar (lambda (f)
  17215. (or (org-load-noerror-mustsuffix (concat org-dir f))
  17216. (and (string= org-dir contrib-dir)
  17217. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  17218. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  17219. (push f load-uncore)
  17220. 't)
  17221. f))
  17222. lfeat)))
  17223. (when load-uncore
  17224. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  17225. (if (> (length load-uncore) 1) "s were" " was")
  17226. (reverse load-uncore)))
  17227. (if load-misses
  17228. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  17229. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  17230. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  17231. ;;;###autoload
  17232. (defun org-customize ()
  17233. "Call the customize function with org as argument."
  17234. (interactive)
  17235. (org-load-modules-maybe)
  17236. (org-require-autoloaded-modules)
  17237. (customize-browse 'org))
  17238. (defun org-create-customize-menu ()
  17239. "Create a full customization menu for Org mode, insert it into the menu."
  17240. (interactive)
  17241. (org-load-modules-maybe)
  17242. (org-require-autoloaded-modules)
  17243. (easy-menu-change
  17244. '("Org") "Customize"
  17245. `(["Browse Org group" org-customize t]
  17246. "--"
  17247. ,(customize-menu-create 'org)
  17248. ["Set" Custom-set t]
  17249. ["Save" Custom-save t]
  17250. ["Reset to Current" Custom-reset-current t]
  17251. ["Reset to Saved" Custom-reset-saved t]
  17252. ["Reset to Standard Settings" Custom-reset-standard t]))
  17253. (message "\"Org\"-menu now contains full customization menu"))
  17254. ;;;; Miscellaneous stuff
  17255. ;;; Generally useful functions
  17256. (defun org-in-clocktable-p ()
  17257. "Check if the cursor is in a clocktable."
  17258. (let ((pos (point)) start)
  17259. (save-excursion
  17260. (end-of-line 1)
  17261. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  17262. (setq start (match-beginning 0))
  17263. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  17264. (>= (match-end 0) pos)
  17265. start))))
  17266. (defun org-in-verbatim-emphasis ()
  17267. (save-match-data
  17268. (and (org-in-regexp org-verbatim-re 2)
  17269. (>= (point) (match-beginning 3))
  17270. (<= (point) (match-end 4)))))
  17271. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  17272. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  17273. (if (and marker (marker-buffer marker)
  17274. (buffer-live-p (marker-buffer marker)))
  17275. (progn
  17276. (pop-to-buffer-same-window (marker-buffer marker))
  17277. (when (or (> marker (point-max)) (< marker (point-min)))
  17278. (widen))
  17279. (goto-char marker)
  17280. (org-show-context 'org-goto))
  17281. (if bookmark
  17282. (bookmark-jump bookmark)
  17283. (error "Cannot find location"))))
  17284. (defun org-quote-csv-field (s)
  17285. "Quote field for inclusion in CSV material."
  17286. (if (string-match "[\",]" s)
  17287. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  17288. s))
  17289. (defun org-force-self-insert (N)
  17290. "Needed to enforce self-insert under remapping."
  17291. (interactive "p")
  17292. (self-insert-command N))
  17293. (defun org-quote-vert (s)
  17294. "Replace \"|\" with \"\\vert\"."
  17295. (while (string-match "|" s)
  17296. (setq s (replace-match "\\vert" t t s)))
  17297. s)
  17298. (defun org-uuidgen-p (s)
  17299. "Is S an ID created by UUIDGEN?"
  17300. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  17301. (defun org-in-src-block-p (&optional inside)
  17302. "Whether point is in a code source block.
  17303. When INSIDE is non-nil, don't consider we are within a source
  17304. block when point is at #+BEGIN_SRC or #+END_SRC."
  17305. (let ((case-fold-search t))
  17306. (or (and (eq (get-char-property (point) 'src-block) t))
  17307. (and (not inside)
  17308. (save-match-data
  17309. (save-excursion
  17310. (beginning-of-line)
  17311. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  17312. (defun org-context ()
  17313. "Return a list of contexts of the current cursor position.
  17314. If several contexts apply, all are returned.
  17315. Each context entry is a list with a symbol naming the context, and
  17316. two positions indicating start and end of the context. Possible
  17317. contexts are:
  17318. :headline anywhere in a headline
  17319. :headline-stars on the leading stars in a headline
  17320. :todo-keyword on a TODO keyword (including DONE) in a headline
  17321. :tags on the TAGS in a headline
  17322. :priority on the priority cookie in a headline
  17323. :item on the first line of a plain list item
  17324. :item-bullet on the bullet/number of a plain list item
  17325. :checkbox on the checkbox in a plain list item
  17326. :table in an Org table
  17327. :table-special on a special filed in a table
  17328. :table-table in a table.el table
  17329. :clocktable in a clocktable
  17330. :src-block in a source block
  17331. :link on a hyperlink
  17332. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  17333. :latex-fragment on a LaTeX fragment
  17334. :latex-preview on a LaTeX fragment with overlaid preview image
  17335. This function expects the position to be visible because it uses font-lock
  17336. faces as a help to recognize the following contexts: :table-special, :link,
  17337. and :keyword."
  17338. (let* ((f (get-text-property (point) 'face))
  17339. (faces (if (listp f) f (list f)))
  17340. (case-fold-search t)
  17341. (p (point)) clist o)
  17342. ;; First the large context
  17343. (cond
  17344. ((org-at-heading-p t)
  17345. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  17346. (when (progn
  17347. (beginning-of-line 1)
  17348. (looking-at org-todo-line-tags-regexp))
  17349. (push (org-point-in-group p 1 :headline-stars) clist)
  17350. (push (org-point-in-group p 2 :todo-keyword) clist)
  17351. (push (org-point-in-group p 4 :tags) clist))
  17352. (goto-char p)
  17353. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  17354. (when (looking-at "\\[#[A-Z0-9]\\]")
  17355. (push (org-point-in-group p 0 :priority) clist)))
  17356. ((org-at-item-p)
  17357. (push (org-point-in-group p 2 :item-bullet) clist)
  17358. (push (list :item (point-at-bol)
  17359. (save-excursion (org-end-of-item) (point)))
  17360. clist)
  17361. (and (org-at-item-checkbox-p)
  17362. (push (org-point-in-group p 0 :checkbox) clist)))
  17363. ((org-at-table-p)
  17364. (push (list :table (org-table-begin) (org-table-end)) clist)
  17365. (when (memq 'org-formula faces)
  17366. (push (list :table-special
  17367. (previous-single-property-change p 'face)
  17368. (next-single-property-change p 'face))
  17369. clist)))
  17370. ((org-at-table-p 'any)
  17371. (push (list :table-table) clist)))
  17372. (goto-char p)
  17373. (let ((case-fold-search t))
  17374. ;; New the "medium" contexts: clocktables, source blocks
  17375. (cond ((org-in-clocktable-p)
  17376. (push (list :clocktable
  17377. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  17378. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  17379. (match-beginning 1))
  17380. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  17381. (match-end 0)))
  17382. clist))
  17383. ((org-in-src-block-p)
  17384. (push (list :src-block
  17385. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  17386. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  17387. (match-beginning 1))
  17388. (and (search-forward "#+END_SRC" nil t)
  17389. (match-beginning 0)))
  17390. clist))))
  17391. (goto-char p)
  17392. ;; Now the small context
  17393. (cond
  17394. ((org-at-timestamp-p)
  17395. (push (org-point-in-group p 0 :timestamp) clist))
  17396. ((memq 'org-link faces)
  17397. (push (list :link
  17398. (previous-single-property-change p 'face)
  17399. (next-single-property-change p 'face))
  17400. clist))
  17401. ((memq 'org-special-keyword faces)
  17402. (push (list :keyword
  17403. (previous-single-property-change p 'face)
  17404. (next-single-property-change p 'face))
  17405. clist))
  17406. ((setq o (cl-some
  17407. (lambda (o)
  17408. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  17409. o))
  17410. (overlays-at (point))))
  17411. (push (list :latex-fragment
  17412. (overlay-start o) (overlay-end o))
  17413. clist)
  17414. (push (list :latex-preview
  17415. (overlay-start o) (overlay-end o))
  17416. clist))
  17417. ((org-inside-LaTeX-fragment-p)
  17418. ;; FIXME: positions wrong.
  17419. (push (list :latex-fragment (point) (point)) clist)))
  17420. (setq clist (nreverse (delq nil clist)))
  17421. clist))
  17422. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  17423. "Non-nil when point is between matches of START-RE and END-RE.
  17424. Also return a non-nil value when point is on one of the matches.
  17425. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  17426. buffer positions. Default values are the positions of headlines
  17427. surrounding the point.
  17428. The functions returns a cons cell whose car (resp. cdr) is the
  17429. position before START-RE (resp. after END-RE)."
  17430. (save-match-data
  17431. (let ((pos (point))
  17432. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  17433. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  17434. beg end)
  17435. (save-excursion
  17436. ;; Point is on a block when on START-RE or if START-RE can be
  17437. ;; found before it...
  17438. (and (or (org-in-regexp start-re)
  17439. (re-search-backward start-re limit-up t))
  17440. (setq beg (match-beginning 0))
  17441. ;; ... and END-RE after it...
  17442. (goto-char (match-end 0))
  17443. (re-search-forward end-re limit-down t)
  17444. (> (setq end (match-end 0)) pos)
  17445. ;; ... without another START-RE in-between.
  17446. (goto-char (match-beginning 0))
  17447. (not (re-search-backward start-re (1+ beg) t))
  17448. ;; Return value.
  17449. (cons beg end))))))
  17450. (defun org-in-block-p (names)
  17451. "Non-nil when point belongs to a block whose name belongs to NAMES.
  17452. NAMES is a list of strings containing names of blocks.
  17453. Return first block name matched, or nil. Beware that in case of
  17454. nested blocks, the returned name may not belong to the closest
  17455. block from point."
  17456. (save-match-data
  17457. (catch 'exit
  17458. (let ((case-fold-search t)
  17459. (lim-up (save-excursion (outline-previous-heading)))
  17460. (lim-down (save-excursion (outline-next-heading))))
  17461. (dolist (name names)
  17462. (let ((n (regexp-quote name)))
  17463. (when (org-between-regexps-p
  17464. (concat "^[ \t]*#\\+begin_" n)
  17465. (concat "^[ \t]*#\\+end_" n)
  17466. lim-up lim-down)
  17467. (throw 'exit n)))))
  17468. nil)))
  17469. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  17470. "Call `multi-occur' with buffers for all agenda files."
  17471. (interactive "sOrg-files matching: ")
  17472. (let* ((files (org-agenda-files))
  17473. (tnames (mapcar #'file-truename files))
  17474. (extra org-agenda-text-search-extra-files))
  17475. (when (eq (car extra) 'agenda-archives)
  17476. (setq extra (cdr extra))
  17477. (setq files (org-add-archive-files files)))
  17478. (dolist (f extra)
  17479. (unless (member (file-truename f) tnames)
  17480. (unless (member f files) (setq files (append files (list f))))
  17481. (setq tnames (append tnames (list (file-truename f))))))
  17482. (multi-occur
  17483. (mapcar (lambda (x)
  17484. (with-current-buffer
  17485. ;; FIXME: Why not just (find-file-noselect x)?
  17486. ;; Is it to avoid the "revert buffer" prompt?
  17487. (or (get-file-buffer x) (find-file-noselect x))
  17488. (widen)
  17489. (current-buffer)))
  17490. files)
  17491. regexp)))
  17492. (add-hook 'occur-mode-find-occurrence-hook
  17493. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  17494. (defun org-occur-link-in-agenda-files ()
  17495. "Create a link and search for it in the agendas.
  17496. The link is not stored in `org-stored-links', it is just created
  17497. for the search purpose."
  17498. (interactive)
  17499. (let ((link (condition-case nil
  17500. (org-store-link nil)
  17501. (error "Unable to create a link to here"))))
  17502. (org-occur-in-agenda-files (regexp-quote link))))
  17503. (defun org-back-over-empty-lines ()
  17504. "Move backwards over whitespace, to the beginning of the first empty line.
  17505. Returns the number of empty lines passed."
  17506. (let ((pos (point)))
  17507. (if (cdr (assq 'heading org-blank-before-new-entry))
  17508. (skip-chars-backward " \t\n\r")
  17509. (unless (eobp)
  17510. (forward-line -1)))
  17511. (beginning-of-line 2)
  17512. (goto-char (min (point) pos))
  17513. (count-lines (point) pos)))
  17514. ;;; TODO: Only called once, from ox-odt which should probably use
  17515. ;;; org-export-inline-image-p or something.
  17516. (defun org-file-image-p (file)
  17517. "Return non-nil if FILE is an image."
  17518. (save-match-data
  17519. (string-match (image-file-name-regexp) file)))
  17520. (defun org-get-cursor-date (&optional with-time)
  17521. "Return the date at cursor in as a time.
  17522. This works in the calendar and in the agenda, anywhere else it just
  17523. returns the current time.
  17524. If WITH-TIME is non-nil, returns the time of the event at point (in
  17525. the agenda) or the current time of the day; otherwise returns the
  17526. earliest time on the cursor date that Org treats as that date
  17527. (bearing in mind `org-extend-today-until')."
  17528. (let (date day defd tp hod mod)
  17529. (when with-time
  17530. (setq tp (get-text-property (point) 'time))
  17531. (when (and tp (string-match "\\([0-2]?[0-9]\\):\\([0-5][0-9]\\)" tp))
  17532. (setq hod (string-to-number (match-string 1 tp))
  17533. mod (string-to-number (match-string 2 tp))))
  17534. (or tp (let ((now (decode-time)))
  17535. (setq hod (nth 2 now)
  17536. mod (nth 1 now)))))
  17537. (cond
  17538. ((eq major-mode 'calendar-mode)
  17539. (setq date (calendar-cursor-to-date)
  17540. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  17541. (nth 1 date) (nth 0 date) (nth 2 date))))
  17542. ((eq major-mode 'org-agenda-mode)
  17543. (setq day (get-text-property (point) 'day))
  17544. (when day
  17545. (setq date (calendar-gregorian-from-absolute day)
  17546. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  17547. (nth 1 date) (nth 0 date) (nth 2 date))))))
  17548. (or defd (current-time))))
  17549. (defun org-mark-subtree (&optional up)
  17550. "Mark the current subtree.
  17551. This puts point at the start of the current subtree, and mark at
  17552. the end. If a numeric prefix UP is given, move up into the
  17553. hierarchy of headlines by UP levels before marking the subtree."
  17554. (interactive "P")
  17555. (org-with-limited-levels
  17556. (cond ((org-at-heading-p) (beginning-of-line))
  17557. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  17558. (t (outline-previous-visible-heading 1))))
  17559. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  17560. (if (called-interactively-p 'any)
  17561. (call-interactively 'org-mark-element)
  17562. (org-mark-element)))
  17563. ;;; Indentation
  17564. (defvar org-element-greater-elements)
  17565. (defun org--get-expected-indentation (element contentsp)
  17566. "Expected indentation column for current line, according to ELEMENT.
  17567. ELEMENT is an element containing point. CONTENTSP is non-nil
  17568. when indentation is to be computed according to contents of
  17569. ELEMENT."
  17570. (let ((type (org-element-type element))
  17571. (start (org-element-property :begin element))
  17572. (post-affiliated (org-element-property :post-affiliated element)))
  17573. (org-with-wide-buffer
  17574. (cond
  17575. (contentsp
  17576. (cl-case type
  17577. ((diary-sexp footnote-definition) 0)
  17578. ((headline inlinetask nil)
  17579. (if (not org-adapt-indentation) 0
  17580. (let ((level (org-current-level)))
  17581. (if level (1+ level) 0))))
  17582. ((item plain-list) (org-list-item-body-column post-affiliated))
  17583. (t
  17584. (goto-char start)
  17585. (current-indentation))))
  17586. ((memq type '(headline inlinetask nil))
  17587. (if (org-match-line "[ \t]*$")
  17588. (org--get-expected-indentation element t)
  17589. 0))
  17590. ((memq type '(diary-sexp footnote-definition)) 0)
  17591. ;; First paragraph of a footnote definition or an item.
  17592. ;; Indent like parent.
  17593. ((< (line-beginning-position) start)
  17594. (org--get-expected-indentation
  17595. (org-element-property :parent element) t))
  17596. ;; At first line: indent according to previous sibling, if any,
  17597. ;; ignoring footnote definitions and inline tasks, or parent's
  17598. ;; contents.
  17599. ((and ( = (line-beginning-position) start)
  17600. (eq org-adapt-indentation t))
  17601. (catch 'exit
  17602. (while t
  17603. (if (= (point-min) start) (throw 'exit 0)
  17604. (goto-char (1- start))
  17605. (let* ((previous (org-element-at-point))
  17606. (parent previous))
  17607. (while (and parent (<= (org-element-property :end parent) start))
  17608. (setq previous parent
  17609. parent (org-element-property :parent parent)))
  17610. (cond
  17611. ((not previous) (throw 'exit 0))
  17612. ((> (org-element-property :end previous) start)
  17613. (throw 'exit (org--get-expected-indentation previous t)))
  17614. ((memq (org-element-type previous)
  17615. '(footnote-definition inlinetask))
  17616. (setq start (org-element-property :begin previous)))
  17617. (t (goto-char (org-element-property :begin previous))
  17618. (throw 'exit
  17619. (if (bolp) (current-indentation)
  17620. ;; At first paragraph in an item or
  17621. ;; a footnote definition.
  17622. (org--get-expected-indentation
  17623. (org-element-property :parent previous) t))))))))))
  17624. ;; Otherwise, move to the first non-blank line above.
  17625. (t
  17626. (beginning-of-line)
  17627. (let ((pos (point)))
  17628. (skip-chars-backward " \r\t\n")
  17629. (cond
  17630. ;; Two blank lines end a footnote definition or a plain
  17631. ;; list. When we indent an empty line after them, the
  17632. ;; containing list or footnote definition is over, so it
  17633. ;; qualifies as a previous sibling. Therefore, we indent
  17634. ;; like its first line.
  17635. ((and (memq type '(footnote-definition plain-list))
  17636. (> (count-lines (point) pos) 2))
  17637. (goto-char start)
  17638. (current-indentation))
  17639. ;; Line above is the first one of a paragraph at the
  17640. ;; beginning of an item or a footnote definition. Indent
  17641. ;; like parent.
  17642. ((< (line-beginning-position) start)
  17643. (org--get-expected-indentation
  17644. (org-element-property :parent element) t))
  17645. ;; Line above is the beginning of an element, i.e., point
  17646. ;; was originally on the blank lines between element's start
  17647. ;; and contents.
  17648. ((= (line-beginning-position) post-affiliated)
  17649. (org--get-expected-indentation element t))
  17650. ;; POS is after contents in a greater element. Indent like
  17651. ;; the beginning of the element.
  17652. ((and (memq type org-element-greater-elements)
  17653. (let ((cend (org-element-property :contents-end element)))
  17654. (and cend (<= cend pos))))
  17655. ;; As a special case, if point is at the end of a footnote
  17656. ;; definition or an item, indent like the very last element
  17657. ;; within. If that last element is an item, indent like
  17658. ;; its contents.
  17659. (if (memq type '(footnote-definition item plain-list))
  17660. (let ((last (org-element-at-point)))
  17661. (goto-char pos)
  17662. (org--get-expected-indentation
  17663. last (eq (org-element-type last) 'item)))
  17664. (goto-char start)
  17665. (current-indentation)))
  17666. ;; In any other case, indent like the current line.
  17667. (t (current-indentation)))))
  17668. ;; Finally, no indentation is needed, fall back to 0.
  17669. (t (current-indentation))))))
  17670. (defun org--align-node-property ()
  17671. "Align node property at point.
  17672. Alignment is done according to `org-property-format', which see."
  17673. (when (save-excursion
  17674. (beginning-of-line)
  17675. (looking-at org-property-re))
  17676. (combine-change-calls (match-beginning 0) (match-end 0)
  17677. (let ((newtext (concat (match-string 4)
  17678. (org-trim
  17679. (format org-property-format (match-string 1) (match-string 3))))))
  17680. (setf (buffer-substring (match-beginning 0) (match-end 0)) newtext)))))
  17681. (defun org-indent-line ()
  17682. "Indent line depending on context.
  17683. Indentation is done according to the following rules:
  17684. - Footnote definitions, diary sexps, headlines and inline tasks
  17685. have to start at column 0.
  17686. - On the very first line of an element, consider, in order, the
  17687. next rules until one matches:
  17688. 1. If there's a sibling element before, ignoring footnote
  17689. definitions and inline tasks, indent like its first line.
  17690. 2. If element has a parent, indent like its contents. More
  17691. precisely, if parent is an item, indent after the bullet.
  17692. Else, indent like parent's first line.
  17693. 3. Otherwise, indent relatively to current level, if
  17694. `org-adapt-indentation' is t, or to left margin.
  17695. - On a blank line at the end of an element, indent according to
  17696. the type of the element. More precisely
  17697. 1. If element is a plain list, an item, or a footnote
  17698. definition, indent like the very last element within.
  17699. 2. If element is a paragraph, indent like its last non blank
  17700. line.
  17701. 3. Otherwise, indent like its very first line.
  17702. - In the code part of a source block, use language major mode
  17703. to indent current line if `org-src-tab-acts-natively' is
  17704. non-nil. If it is nil, do nothing.
  17705. - Otherwise, indent like the first non-blank line above.
  17706. The function doesn't indent an item as it could break the whole
  17707. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  17708. `\\[org-shiftmetaright]'.
  17709. Also align node properties according to `org-property-format'."
  17710. (interactive)
  17711. (unless (or (org-at-heading-p)
  17712. (and (eq org-adapt-indentation 'headline-data)
  17713. (not (or (org-at-clock-log-p)
  17714. (org-at-planning-p)))
  17715. (save-excursion
  17716. (beginning-of-line 1)
  17717. (skip-chars-backward "\n")
  17718. (or (org-at-heading-p)
  17719. (looking-back ":END:.*" (point-at-bol))))))
  17720. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point-no-context)))
  17721. (type (org-element-type element)))
  17722. (cond ((and (memq type '(plain-list item))
  17723. (= (line-beginning-position)
  17724. (org-element-property :post-affiliated element)))
  17725. nil)
  17726. ((and (eq type 'latex-environment)
  17727. (>= (point) (org-element-property :post-affiliated element))
  17728. (< (point)
  17729. (org-with-point-at (org-element-property :end element)
  17730. (skip-chars-backward " \t\n")
  17731. (line-beginning-position 2))))
  17732. nil)
  17733. ((and (eq type 'src-block)
  17734. org-src-tab-acts-natively
  17735. (> (line-beginning-position)
  17736. (org-element-property :post-affiliated element))
  17737. (< (line-beginning-position)
  17738. (org-with-point-at (org-element-property :end element)
  17739. (skip-chars-backward " \t\n")
  17740. (line-beginning-position))))
  17741. ;; At the beginning of a blank line, do some preindentation. This
  17742. ;; signals org-src--edit-element to preserve the indentation on exit
  17743. (when (and (looking-at-p "^[[:space:]]*$")
  17744. (not org-src-preserve-indentation))
  17745. (let ((element (org-element-at-point))
  17746. block-content-ind some-ind)
  17747. (org-with-point-at (org-element-property :begin element)
  17748. (setq block-content-ind (+ (current-indentation)
  17749. org-edit-src-content-indentation))
  17750. (forward-line)
  17751. (save-match-data (re-search-forward "^[ \t]*\\S-" nil t))
  17752. (backward-char)
  17753. (setq some-ind (if (looking-at-p "#\\+end_src")
  17754. block-content-ind (current-indentation))))
  17755. (indent-line-to (min block-content-ind some-ind))))
  17756. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  17757. (t
  17758. (let ((column (org--get-expected-indentation element nil)))
  17759. ;; Preserve current column.
  17760. (if (<= (current-column) (current-indentation))
  17761. (indent-line-to column)
  17762. (save-excursion (indent-line-to column))))
  17763. ;; Align node property. Also preserve current column.
  17764. (when (eq type 'node-property)
  17765. (let ((column (current-column)))
  17766. (org--align-node-property)
  17767. (org-move-to-column column))))))))
  17768. (defun org-indent-region (start end)
  17769. "Indent each non-blank line in the region.
  17770. Called from a program, START and END specify the region to
  17771. indent. The function will not indent contents of example blocks,
  17772. verse blocks and export blocks as leading white spaces are
  17773. assumed to be significant there."
  17774. (interactive "r")
  17775. (save-excursion
  17776. (goto-char start)
  17777. (skip-chars-forward " \r\t\n")
  17778. (unless (eobp) (beginning-of-line))
  17779. (let ((indent-to
  17780. (lambda (ind pos)
  17781. ;; Set IND as indentation for all lines between point and
  17782. ;; POS. Blank lines are ignored. Leave point after POS
  17783. ;; once done.
  17784. (let ((limit (copy-marker pos)))
  17785. (while (< (point) limit)
  17786. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  17787. (forward-line))
  17788. (set-marker limit nil))))
  17789. (end (copy-marker end)))
  17790. (while (< (point) end)
  17791. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  17792. (let* ((element (org-element-at-point-no-context))
  17793. (type (org-element-type element))
  17794. (element-end (copy-marker (org-element-property :end element)))
  17795. (ind (org--get-expected-indentation element nil)))
  17796. (cond
  17797. ;; Element indented as a single block. Example blocks
  17798. ;; preserving indentation are a special case since the
  17799. ;; "contents" must not be indented whereas the block
  17800. ;; boundaries can.
  17801. ((or (memq type '(export-block latex-environment))
  17802. (and (eq type 'example-block)
  17803. (not
  17804. (or org-src-preserve-indentation
  17805. (org-element-property :preserve-indent element)))))
  17806. (let ((offset (- ind (current-indentation))))
  17807. (unless (zerop offset)
  17808. (indent-rigidly (org-element-property :begin element)
  17809. (org-element-property :end element)
  17810. offset)))
  17811. (goto-char element-end))
  17812. ;; Elements indented line wise. Be sure to exclude
  17813. ;; example blocks (preserving indentation) and source
  17814. ;; blocks from this category as they are treated
  17815. ;; specially later.
  17816. ((or (memq type '(paragraph table table-row))
  17817. (not (or (org-element-property :contents-begin element)
  17818. (memq type '(example-block src-block)))))
  17819. (when (eq type 'node-property)
  17820. (org--align-node-property)
  17821. (beginning-of-line))
  17822. (funcall indent-to ind (min element-end end)))
  17823. ;; Elements consisting of three parts: before the
  17824. ;; contents, the contents, and after the contents. The
  17825. ;; contents are treated specially, according to the
  17826. ;; element type, or not indented at all. Other parts are
  17827. ;; indented as a single block.
  17828. (t
  17829. (let* ((post (copy-marker
  17830. (org-element-property :post-affiliated element)))
  17831. (cbeg
  17832. (copy-marker
  17833. (cond
  17834. ((not (org-element-property :contents-begin element))
  17835. ;; Fake contents for source blocks.
  17836. (org-with-wide-buffer
  17837. (goto-char post)
  17838. (line-beginning-position 2)))
  17839. ((memq type '(footnote-definition item plain-list))
  17840. ;; Contents in these elements could start on
  17841. ;; the same line as the beginning of the
  17842. ;; element. Make sure we start indenting
  17843. ;; from the second line.
  17844. (org-with-wide-buffer
  17845. (goto-char post)
  17846. (end-of-line)
  17847. (skip-chars-forward " \r\t\n")
  17848. (if (eobp) (point) (line-beginning-position))))
  17849. (t (org-element-property :contents-begin element)))))
  17850. (cend (copy-marker
  17851. (or (org-element-property :contents-end element)
  17852. ;; Fake contents for source blocks.
  17853. (org-with-wide-buffer
  17854. (goto-char element-end)
  17855. (skip-chars-backward " \r\t\n")
  17856. (line-beginning-position)))
  17857. t)))
  17858. ;; Do not change items indentation individually as it
  17859. ;; might break the list as a whole. On the other
  17860. ;; hand, when at a plain list, indent it as a whole.
  17861. (cond ((eq type 'plain-list)
  17862. (let ((offset (- ind (current-indentation))))
  17863. (unless (zerop offset)
  17864. (indent-rigidly (org-element-property :begin element)
  17865. (org-element-property :end element)
  17866. offset))
  17867. (goto-char cbeg)))
  17868. ((eq type 'item) (goto-char cbeg))
  17869. (t (funcall indent-to ind (min cbeg end))))
  17870. (when (< (point) end)
  17871. (cl-case type
  17872. ((example-block verse-block))
  17873. (src-block
  17874. ;; In a source block, indent source code
  17875. ;; according to language major mode, but only if
  17876. ;; `org-src-tab-acts-natively' is non-nil.
  17877. (when (and (< (point) end) org-src-tab-acts-natively)
  17878. (ignore-errors
  17879. (org-babel-do-in-edit-buffer
  17880. (indent-region (point-min) (point-max))))))
  17881. (t (org-indent-region (point) (min cend end))))
  17882. (goto-char (min cend end))
  17883. (when (< (point) end)
  17884. (funcall indent-to ind (min element-end end))))
  17885. (set-marker post nil)
  17886. (set-marker cbeg nil)
  17887. (set-marker cend nil))))
  17888. (set-marker element-end nil))))
  17889. (set-marker end nil))))
  17890. (defun org-indent-drawer ()
  17891. "Indent the drawer at point."
  17892. (interactive)
  17893. (unless (save-excursion
  17894. (beginning-of-line)
  17895. (looking-at-p org-drawer-regexp))
  17896. (user-error "Not at a drawer"))
  17897. (let ((element (org-element-at-point-no-context)))
  17898. (unless (memq (org-element-type element) '(drawer property-drawer))
  17899. (user-error "Not at a drawer"))
  17900. (org-with-wide-buffer
  17901. (org-indent-region (org-element-property :begin element)
  17902. (org-element-property :end element))))
  17903. (message "Drawer at point indented"))
  17904. (defun org-indent-block ()
  17905. "Indent the block at point."
  17906. (interactive)
  17907. (unless (save-excursion
  17908. (beginning-of-line)
  17909. (let ((case-fold-search t))
  17910. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  17911. (user-error "Not at a block"))
  17912. (let ((element (org-element-at-point-no-context)))
  17913. (unless (memq (org-element-type element)
  17914. '(comment-block center-block dynamic-block example-block
  17915. export-block quote-block special-block
  17916. src-block verse-block))
  17917. (user-error "Not at a block"))
  17918. (org-with-wide-buffer
  17919. (org-indent-region (org-element-property :begin element)
  17920. (org-element-property :end element))))
  17921. (message "Block at point indented"))
  17922. ;;; Filling
  17923. ;; We use our own fill-paragraph and auto-fill functions.
  17924. ;; `org-fill-paragraph' relies on adaptive filling and context
  17925. ;; checking. Appropriate `fill-prefix' is computed with
  17926. ;; `org-adaptive-fill-function'.
  17927. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  17928. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  17929. ;; `org-adaptive-fill-function' value. Internally,
  17930. ;; `org-comment-line-break-function' breaks the line.
  17931. ;; `org-setup-filling' installs filling and auto-filling related
  17932. ;; variables during `org-mode' initialization.
  17933. (defun org-setup-filling ()
  17934. (require 'org-element)
  17935. ;; Prevent auto-fill from inserting unwanted new items.
  17936. (when (boundp 'fill-nobreak-predicate)
  17937. (setq-local
  17938. fill-nobreak-predicate
  17939. (org-uniquify
  17940. (append fill-nobreak-predicate
  17941. '(org-fill-line-break-nobreak-p
  17942. org-fill-n-macro-as-item-nobreak-p
  17943. org-fill-paragraph-with-timestamp-nobreak-p)))))
  17944. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  17945. (setq-local paragraph-start paragraph-ending)
  17946. (setq-local paragraph-separate paragraph-ending))
  17947. (setq-local fill-paragraph-function 'org-fill-paragraph)
  17948. (setq-local auto-fill-inhibit-regexp nil)
  17949. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  17950. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  17951. (setq-local comment-line-break-function 'org-comment-line-break-function))
  17952. (defun org-fill-line-break-nobreak-p ()
  17953. "Non-nil when a new line at point would create an Org line break."
  17954. (save-excursion
  17955. (skip-chars-backward " \t")
  17956. (skip-chars-backward "\\\\")
  17957. (looking-at "\\\\\\\\\\($\\|[^\\]\\)")))
  17958. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  17959. "Non-nil when a new line at point would split a timestamp."
  17960. (and (org-at-timestamp-p 'lax)
  17961. (not (looking-at org-ts-regexp-both))))
  17962. (defun org-fill-n-macro-as-item-nobreak-p ()
  17963. "Non-nil when a new line at point would create a new list."
  17964. ;; During export, a "n" macro followed by a dot or a closing
  17965. ;; parenthesis can end up being parsed as a new list item.
  17966. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  17967. (defun org-adaptive-fill-function ()
  17968. "Compute a fill prefix for the current line.
  17969. Return fill prefix, as a string, or nil if current line isn't
  17970. meant to be filled. For convenience, if `adaptive-fill-regexp'
  17971. matches in paragraphs or comments, use it."
  17972. (org-with-wide-buffer
  17973. (unless (org-at-heading-p)
  17974. (let* ((p (line-beginning-position))
  17975. (element (save-excursion
  17976. (beginning-of-line)
  17977. (org-element-at-point)))
  17978. (type (org-element-type element))
  17979. (post-affiliated (org-element-property :post-affiliated element)))
  17980. (unless (< p post-affiliated)
  17981. (cl-case type
  17982. (comment
  17983. (save-excursion
  17984. (beginning-of-line)
  17985. (looking-at "[ \t]*")
  17986. (concat (match-string 0) "# ")))
  17987. (footnote-definition "")
  17988. ((item plain-list)
  17989. (make-string (org-list-item-body-column post-affiliated) ?\s))
  17990. (paragraph
  17991. ;; Fill prefix is usually the same as the current line,
  17992. ;; unless the paragraph is at the beginning of an item.
  17993. (let ((parent (org-element-property :parent element)))
  17994. (save-excursion
  17995. (beginning-of-line)
  17996. (cond ((eq (org-element-type parent) 'item)
  17997. (make-string (org-list-item-body-column
  17998. (org-element-property :begin parent))
  17999. ?\s))
  18000. ((and adaptive-fill-regexp
  18001. ;; Locally disable
  18002. ;; `adaptive-fill-function' to let
  18003. ;; `fill-context-prefix' handle
  18004. ;; `adaptive-fill-regexp' variable.
  18005. (let (adaptive-fill-function)
  18006. (fill-context-prefix
  18007. post-affiliated
  18008. (org-element-property :end element)))))
  18009. ((looking-at "[ \t]+") (match-string 0))
  18010. (t "")))))
  18011. (comment-block
  18012. ;; Only fill contents if P is within block boundaries.
  18013. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  18014. (forward-line)
  18015. (point)))
  18016. (cend (save-excursion
  18017. (goto-char (org-element-property :end element))
  18018. (skip-chars-backward " \r\t\n")
  18019. (line-beginning-position))))
  18020. (when (and (>= p cbeg) (< p cend))
  18021. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  18022. (match-string 0)
  18023. ""))))))))))
  18024. (defun org-fill-element (&optional justify)
  18025. "Fill element at point, when applicable.
  18026. This function only applies to comment blocks, comments, example
  18027. blocks and paragraphs. Also, as a special case, re-align table
  18028. when point is at one.
  18029. If JUSTIFY is non-nil (interactively, with prefix argument),
  18030. justify as well. If `sentence-end-double-space' is non-nil, then
  18031. period followed by one space does not end a sentence, so don't
  18032. break a line there. The variable `fill-column' controls the
  18033. width for filling.
  18034. For convenience, when point is at a plain list, an item or
  18035. a footnote definition, try to fill the first paragraph within."
  18036. (with-syntax-table org-mode-transpose-word-syntax-table
  18037. ;; Move to end of line in order to get the first paragraph within
  18038. ;; a plain list or a footnote definition.
  18039. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  18040. ;; First check if point is in a blank line at the beginning of
  18041. ;; the buffer. In that case, ignore filling.
  18042. (cl-case (org-element-type element)
  18043. ;; Use major mode filling function is source blocks.
  18044. (src-block (org-babel-do-in-edit-buffer
  18045. (push-mark (point-min))
  18046. (goto-char (point-max))
  18047. (setq mark-active t)
  18048. (funcall-interactively #'fill-paragraph justify 'region)))
  18049. ;; Align Org tables, leave table.el tables as-is.
  18050. (table-row (org-table-align) t)
  18051. (table
  18052. (when (eq (org-element-property :type element) 'org)
  18053. (save-excursion
  18054. (goto-char (org-element-property :post-affiliated element))
  18055. (org-table-align)))
  18056. t)
  18057. (paragraph
  18058. ;; Paragraphs may contain `line-break' type objects.
  18059. (let ((beg (max (point-min)
  18060. (org-element-property :contents-begin element)))
  18061. (end (min (point-max)
  18062. (org-element-property :contents-end element))))
  18063. ;; Do nothing if point is at an affiliated keyword.
  18064. (if (< (line-end-position) beg) t
  18065. ;; Fill paragraph, taking line breaks into account.
  18066. (save-excursion
  18067. (goto-char beg)
  18068. (let ((cuts (list beg)))
  18069. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  18070. (when (eq 'line-break
  18071. (org-element-type
  18072. (save-excursion (backward-char)
  18073. (org-element-context))))
  18074. (push (point) cuts)))
  18075. (dolist (c (delq end cuts))
  18076. (fill-region-as-paragraph c end justify)
  18077. (setq end c))))
  18078. t)))
  18079. ;; Contents of `comment-block' type elements should be
  18080. ;; filled as plain text, but only if point is within block
  18081. ;; markers.
  18082. (comment-block
  18083. (let* ((case-fold-search t)
  18084. (beg (save-excursion
  18085. (goto-char (org-element-property :begin element))
  18086. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  18087. (forward-line)
  18088. (point)))
  18089. (end (save-excursion
  18090. (goto-char (org-element-property :end element))
  18091. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  18092. (line-beginning-position))))
  18093. (if (or (< (point) beg) (> (point) end)) t
  18094. (fill-region-as-paragraph
  18095. (save-excursion (end-of-line)
  18096. (re-search-backward "^[ \t]*$" beg 'move)
  18097. (line-beginning-position))
  18098. (save-excursion (beginning-of-line)
  18099. (re-search-forward "^[ \t]*$" end 'move)
  18100. (line-beginning-position))
  18101. justify))))
  18102. ;; Fill comments.
  18103. (comment
  18104. (let ((begin (org-element-property :post-affiliated element))
  18105. (end (org-element-property :end element)))
  18106. (when (and (>= (point) begin) (<= (point) end))
  18107. (let ((begin (save-excursion
  18108. (end-of-line)
  18109. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  18110. (progn (forward-line) (point))
  18111. begin)))
  18112. (end (save-excursion
  18113. (end-of-line)
  18114. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  18115. (1- (line-beginning-position))
  18116. (skip-chars-backward " \r\t\n")
  18117. (line-end-position)))))
  18118. ;; Do not fill comments when at a blank line.
  18119. (when (> end begin)
  18120. (let ((fill-prefix
  18121. (save-excursion
  18122. (beginning-of-line)
  18123. (looking-at "[ \t]*#")
  18124. (let ((comment-prefix (match-string 0)))
  18125. (goto-char (match-end 0))
  18126. (if (looking-at adaptive-fill-regexp)
  18127. (concat comment-prefix (match-string 0))
  18128. (concat comment-prefix " "))))))
  18129. (save-excursion
  18130. (fill-region-as-paragraph begin end justify))))))
  18131. t))
  18132. ;; Ignore every other element.
  18133. (otherwise t)))))
  18134. (defun org-fill-paragraph (&optional justify region)
  18135. "Fill element at point, when applicable.
  18136. This function only applies to comment blocks, comments, example
  18137. blocks and paragraphs. Also, as a special case, re-align table
  18138. when point is at one.
  18139. For convenience, when point is at a plain list, an item or
  18140. a footnote definition, try to fill the first paragraph within.
  18141. If JUSTIFY is non-nil (interactively, with prefix argument),
  18142. justify as well. If `sentence-end-double-space' is non-nil, then
  18143. period followed by one space does not end a sentence, so don't
  18144. break a line there. The variable `fill-column' controls the
  18145. width for filling.
  18146. The REGION argument is non-nil if called interactively; in that
  18147. case, if Transient Mark mode is enabled and the mark is active,
  18148. fill each of the elements in the active region, instead of just
  18149. filling the current element."
  18150. (interactive (progn
  18151. (barf-if-buffer-read-only)
  18152. (list (when current-prefix-arg 'full) t)))
  18153. (let ((hash (and (not (buffer-modified-p))
  18154. (org-buffer-hash))))
  18155. (cond
  18156. ((and region transient-mark-mode mark-active
  18157. (not (eq (region-beginning) (region-end))))
  18158. (let ((origin (point-marker))
  18159. (start (region-beginning)))
  18160. (unwind-protect
  18161. (progn
  18162. (goto-char (region-end))
  18163. (skip-chars-backward " \t\n")
  18164. (while (> (point) start)
  18165. (org-fill-element justify)
  18166. (org-backward-paragraph)))
  18167. (goto-char origin)
  18168. (set-marker origin nil))))
  18169. (t
  18170. (save-excursion
  18171. (when (org-match-line "[ \t]*$")
  18172. (skip-chars-forward " \t\n"))
  18173. (org-fill-element justify))))
  18174. ;; If we didn't change anything in the buffer (and the buffer was
  18175. ;; previously unmodified), then flip the modification status back
  18176. ;; to "unchanged".
  18177. (when (and hash (equal hash (org-buffer-hash)))
  18178. (set-buffer-modified-p nil))
  18179. ;; Return non-nil.
  18180. t))
  18181. (defun org-auto-fill-function ()
  18182. "Auto-fill function."
  18183. ;; Check if auto-filling is meaningful.
  18184. (let ((fc (current-fill-column)))
  18185. (when (and fc (> (current-column) fc))
  18186. (let* ((fill-prefix (org-adaptive-fill-function))
  18187. ;; Enforce empty fill prefix, if required. Otherwise, it
  18188. ;; will be computed again.
  18189. (adaptive-fill-mode (not (equal fill-prefix ""))))
  18190. (when fill-prefix (do-auto-fill))))))
  18191. (defun org-comment-line-break-function (&optional soft)
  18192. "Break line at point and indent, continuing comment if within one.
  18193. The inserted newline is marked hard if variable
  18194. `use-hard-newlines' is true, unless optional argument SOFT is
  18195. non-nil."
  18196. (if soft (insert-and-inherit ?\n) (newline 1))
  18197. (save-excursion (forward-char -1) (delete-horizontal-space))
  18198. (delete-horizontal-space)
  18199. (indent-to-left-margin)
  18200. (insert-before-markers-and-inherit fill-prefix))
  18201. ;;; Fixed Width Areas
  18202. (defun org-toggle-fixed-width ()
  18203. "Toggle fixed-width markup.
  18204. Add or remove fixed-width markup on current line, whenever it
  18205. makes sense. Return an error otherwise.
  18206. If a region is active and if it contains only fixed-width areas
  18207. or blank lines, remove all fixed-width markup in it. If the
  18208. region contains anything else, convert all non-fixed-width lines
  18209. to fixed-width ones.
  18210. Blank lines at the end of the region are ignored unless the
  18211. region only contains such lines."
  18212. (interactive)
  18213. (if (not (org-region-active-p))
  18214. ;; No region:
  18215. ;;
  18216. ;; Remove fixed width marker only in a fixed-with element.
  18217. ;;
  18218. ;; Add fixed width maker in paragraphs, in blank lines after
  18219. ;; elements or at the beginning of a headline or an inlinetask,
  18220. ;; and before any one-line elements (e.g., a clock).
  18221. (progn
  18222. (beginning-of-line)
  18223. (let* ((element (org-element-at-point))
  18224. (type (org-element-type element)))
  18225. (cond
  18226. ((and (eq type 'fixed-width)
  18227. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  18228. (replace-match
  18229. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  18230. ((and (memq type '(babel-call clock comment diary-sexp headline
  18231. horizontal-rule keyword paragraph
  18232. planning))
  18233. (<= (org-element-property :post-affiliated element) (point)))
  18234. (skip-chars-forward " \t")
  18235. (insert ": "))
  18236. ((and (looking-at-p "[ \t]*$")
  18237. (or (eq type 'inlinetask)
  18238. (save-excursion
  18239. (skip-chars-forward " \r\t\n")
  18240. (<= (org-element-property :end element) (point)))))
  18241. (delete-region (point) (line-end-position))
  18242. (org-indent-line)
  18243. (insert ": "))
  18244. (t (user-error "Cannot insert a fixed-width line here")))))
  18245. ;; Region active.
  18246. (let* ((begin (save-excursion
  18247. (goto-char (region-beginning))
  18248. (line-beginning-position)))
  18249. (end (copy-marker
  18250. (save-excursion
  18251. (goto-char (region-end))
  18252. (unless (eolp) (beginning-of-line))
  18253. (if (save-excursion (re-search-backward "\\S-" begin t))
  18254. (progn (skip-chars-backward " \r\t\n") (point))
  18255. (point)))))
  18256. (all-fixed-width-p
  18257. (catch 'not-all-p
  18258. (save-excursion
  18259. (goto-char begin)
  18260. (skip-chars-forward " \r\t\n")
  18261. (when (eobp) (throw 'not-all-p nil))
  18262. (while (< (point) end)
  18263. (let ((element (org-element-at-point)))
  18264. (if (eq (org-element-type element) 'fixed-width)
  18265. (goto-char (org-element-property :end element))
  18266. (throw 'not-all-p nil))))
  18267. t))))
  18268. (if all-fixed-width-p
  18269. (save-excursion
  18270. (goto-char begin)
  18271. (while (< (point) end)
  18272. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  18273. (replace-match
  18274. "" nil nil nil
  18275. (if (= (line-end-position) (match-end 0)) 0 1)))
  18276. (forward-line)))
  18277. (let ((min-ind (point-max)))
  18278. ;; Find minimum indentation across all lines.
  18279. (save-excursion
  18280. (goto-char begin)
  18281. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  18282. (setq min-ind 0)
  18283. (catch 'zerop
  18284. (while (< (point) end)
  18285. (unless (looking-at-p "[ \t]*$")
  18286. (let ((ind (current-indentation)))
  18287. (setq min-ind (min min-ind ind))
  18288. (when (zerop ind) (throw 'zerop t))))
  18289. (forward-line)))))
  18290. ;; Loop over all lines and add fixed-width markup everywhere
  18291. ;; but in fixed-width lines.
  18292. (save-excursion
  18293. (goto-char begin)
  18294. (while (< (point) end)
  18295. (cond
  18296. ((org-at-heading-p)
  18297. (insert ": ")
  18298. (forward-line)
  18299. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  18300. (insert ":")
  18301. (forward-line)))
  18302. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  18303. (let* ((element (org-element-at-point))
  18304. (element-end (org-element-property :end element)))
  18305. (if (eq (org-element-type element) 'fixed-width)
  18306. (progn (goto-char element-end)
  18307. (skip-chars-backward " \r\t\n")
  18308. (forward-line))
  18309. (let ((limit (min end element-end)))
  18310. (while (< (point) limit)
  18311. (org-move-to-column min-ind t)
  18312. (insert ": ")
  18313. (forward-line))))))
  18314. (t
  18315. (org-move-to-column min-ind t)
  18316. (insert ": ")
  18317. (forward-line)))))))
  18318. (set-marker end nil))))
  18319. ;;; Blocks
  18320. (defun org-block-map (function &optional start end)
  18321. "Call FUNCTION at the head of all source blocks in the current buffer.
  18322. Optional arguments START and END can be used to limit the range."
  18323. (let ((start (or start (point-min)))
  18324. (end (or end (point-max))))
  18325. (save-excursion
  18326. (goto-char start)
  18327. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  18328. (save-excursion
  18329. (save-match-data
  18330. (goto-char (match-beginning 0))
  18331. (funcall function)))))))
  18332. (defun org-next-block (arg &optional backward block-regexp)
  18333. "Jump to the next block.
  18334. With a prefix argument ARG, jump forward ARG many blocks.
  18335. When BACKWARD is non-nil, jump to the previous block.
  18336. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  18337. Match data is set according to this regexp when the function
  18338. returns.
  18339. Return point at beginning of the opening line of found block.
  18340. Throw an error if no block is found."
  18341. (interactive "p")
  18342. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  18343. (case-fold-search t)
  18344. (search-fn (if backward #'re-search-backward #'re-search-forward))
  18345. (count (or arg 1))
  18346. (origin (point))
  18347. last-element)
  18348. (if backward (beginning-of-line) (end-of-line))
  18349. (while (and (> count 0) (funcall search-fn re nil t))
  18350. (let ((element (save-excursion
  18351. (goto-char (match-beginning 0))
  18352. (save-match-data (org-element-at-point)))))
  18353. (when (and (memq (org-element-type element)
  18354. '(center-block comment-block dynamic-block
  18355. example-block export-block quote-block
  18356. special-block src-block verse-block))
  18357. (<= (match-beginning 0)
  18358. (org-element-property :post-affiliated element)))
  18359. (setq last-element element)
  18360. (cl-decf count))))
  18361. (if (= count 0)
  18362. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  18363. (save-match-data (org-show-context)))
  18364. (goto-char origin)
  18365. (user-error "No %s code blocks" (if backward "previous" "further")))))
  18366. (defun org-previous-block (arg &optional block-regexp)
  18367. "Jump to the previous block.
  18368. With a prefix argument ARG, jump backward ARG many source blocks.
  18369. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  18370. (interactive "p")
  18371. (org-next-block arg t block-regexp))
  18372. ;;; Comments
  18373. ;; Org comments syntax is quite complex. It requires the entire line
  18374. ;; to be just a comment. Also, even with the right syntax at the
  18375. ;; beginning of line, some elements (e.g., verse-block or
  18376. ;; example-block) don't accept comments. Usual Emacs comment commands
  18377. ;; cannot cope with those requirements. Therefore, Org replaces them.
  18378. ;; Org still relies on 'comment-dwim', but cannot trust
  18379. ;; 'comment-only-p'. So, 'comment-region-function' and
  18380. ;; 'uncomment-region-function' both point
  18381. ;; to 'org-comment-or-uncomment-region'. Eventually,
  18382. ;; 'org-insert-comment' takes care of insertion of comments at the
  18383. ;; beginning of line.
  18384. ;; 'org-setup-comments-handling' install comments related variables
  18385. ;; during 'org-mode' initialization.
  18386. (defun org-setup-comments-handling ()
  18387. (interactive)
  18388. (setq-local comment-use-syntax nil)
  18389. (setq-local comment-start "# ")
  18390. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  18391. (setq-local comment-insert-comment-function 'org-insert-comment)
  18392. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  18393. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  18394. (defun org-insert-comment ()
  18395. "Insert an empty comment above current line.
  18396. If the line is empty, insert comment at its beginning. When
  18397. point is within a source block, comment according to the related
  18398. major mode."
  18399. (if (let ((element (org-element-at-point)))
  18400. (and (eq (org-element-type element) 'src-block)
  18401. (< (save-excursion
  18402. (goto-char (org-element-property :post-affiliated element))
  18403. (line-end-position))
  18404. (point))
  18405. (> (save-excursion
  18406. (goto-char (org-element-property :end element))
  18407. (skip-chars-backward " \r\t\n")
  18408. (line-beginning-position))
  18409. (point))))
  18410. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  18411. (beginning-of-line)
  18412. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  18413. (open-line 1))
  18414. (org-indent-line)
  18415. (insert "# ")))
  18416. (defvar comment-empty-lines) ; From newcomment.el.
  18417. (defun org-comment-or-uncomment-region (beg end &rest _)
  18418. "Comment or uncomment each non-blank line in the region.
  18419. Uncomment each non-blank line between BEG and END if it only
  18420. contains commented lines. Otherwise, comment them. If region is
  18421. strictly within a source block, use appropriate comment syntax."
  18422. (if (let ((element (org-element-at-point)))
  18423. (and (eq (org-element-type element) 'src-block)
  18424. (< (save-excursion
  18425. (goto-char (org-element-property :post-affiliated element))
  18426. (line-end-position))
  18427. beg)
  18428. (>= (save-excursion
  18429. (goto-char (org-element-property :end element))
  18430. (skip-chars-backward " \r\t\n")
  18431. (line-beginning-position))
  18432. end)))
  18433. ;; Translate region boundaries for the Org buffer to the source
  18434. ;; buffer.
  18435. (let ((offset (- end beg)))
  18436. (save-excursion
  18437. (goto-char beg)
  18438. (org-babel-do-in-edit-buffer
  18439. (comment-or-uncomment-region (point) (+ offset (point))))))
  18440. (save-restriction
  18441. ;; Restrict region
  18442. (narrow-to-region (save-excursion (goto-char beg)
  18443. (skip-chars-forward " \r\t\n" end)
  18444. (line-beginning-position))
  18445. (save-excursion (goto-char end)
  18446. (skip-chars-backward " \r\t\n" beg)
  18447. (line-end-position)))
  18448. (let ((uncommentp
  18449. ;; UNCOMMENTP is non-nil when every non blank line between
  18450. ;; BEG and END is a comment.
  18451. (save-excursion
  18452. (goto-char (point-min))
  18453. (while (and (not (eobp))
  18454. (let ((element (org-element-at-point)))
  18455. (and (eq (org-element-type element) 'comment)
  18456. (goto-char (min (point-max)
  18457. (org-element-property
  18458. :end element)))))))
  18459. (eobp))))
  18460. (if uncommentp
  18461. ;; Only blank lines and comments in region: uncomment it.
  18462. (save-excursion
  18463. (goto-char (point-min))
  18464. (while (not (eobp))
  18465. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  18466. (replace-match "" nil nil nil 1))
  18467. (forward-line)))
  18468. ;; Comment each line in region.
  18469. (let ((min-indent (point-max)))
  18470. ;; First find the minimum indentation across all lines.
  18471. (save-excursion
  18472. (goto-char (point-min))
  18473. (while (and (not (eobp)) (not (zerop min-indent)))
  18474. (unless (looking-at "[ \t]*$")
  18475. (setq min-indent (min min-indent (current-indentation))))
  18476. (forward-line)))
  18477. ;; Then loop over all lines.
  18478. (save-excursion
  18479. (goto-char (point-min))
  18480. (while (not (eobp))
  18481. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  18482. ;; Don't get fooled by invisible text (e.g. link path)
  18483. ;; when moving to column MIN-INDENT.
  18484. (let ((buffer-invisibility-spec nil))
  18485. (org-move-to-column min-indent t))
  18486. (insert comment-start))
  18487. (forward-line)))))))))
  18488. (defun org-comment-dwim (_arg)
  18489. "Call the comment command you mean.
  18490. Call `org-toggle-comment' if on a heading, otherwise call
  18491. `comment-dwim', within a source edit buffer if needed."
  18492. (interactive "*P")
  18493. (cond ((org-at-heading-p)
  18494. (call-interactively #'org-toggle-comment))
  18495. ((org-in-src-block-p)
  18496. (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
  18497. (t (call-interactively #'comment-dwim))))
  18498. ;;; Timestamps API
  18499. ;; This section contains tools to operate on, or create, timestamp
  18500. ;; objects, as returned by, e.g. `org-element-context'.
  18501. (defun org-timestamp-from-string (s)
  18502. "Convert Org timestamp S, as a string, into a timestamp object.
  18503. Return nil if S is not a valid timestamp string."
  18504. (when (org-string-nw-p s)
  18505. (with-temp-buffer
  18506. (save-excursion (insert s))
  18507. (org-element-timestamp-parser))))
  18508. (defun org-timestamp-from-time (time &optional with-time inactive)
  18509. "Convert a time value into a timestamp object.
  18510. TIME is an Emacs internal time representation, as returned, e.g.,
  18511. by `current-time'.
  18512. When optional argument WITH-TIME is non-nil, return a timestamp
  18513. object with a time part, i.e., with hours and minutes.
  18514. Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
  18515. return an active timestamp."
  18516. (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
  18517. (org-element-create 'timestamp
  18518. (list :type (if inactive 'inactive 'active)
  18519. :year-start year
  18520. :month-start month
  18521. :day-start day
  18522. :hour-start (and with-time hour)
  18523. :minute-start (and with-time minute)))))
  18524. (defun org-timestamp-to-time (timestamp &optional end)
  18525. "Convert TIMESTAMP object into an Emacs internal time value.
  18526. Use end of date range or time range when END is non-nil.
  18527. Otherwise, use its start."
  18528. (apply #'encode-time 0
  18529. (mapcar
  18530. (lambda (prop) (or (org-element-property prop timestamp) 0))
  18531. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  18532. '(:minute-start :hour-start :day-start :month-start
  18533. :year-start)))))
  18534. (defun org-timestamp-has-time-p (timestamp)
  18535. "Non-nil when TIMESTAMP has a time specified."
  18536. (org-element-property :hour-start timestamp))
  18537. (defun org-timestamp-format (timestamp format &optional end utc)
  18538. "Format a TIMESTAMP object into a string.
  18539. FORMAT is a format specifier to be passed to
  18540. `format-time-string'.
  18541. When optional argument END is non-nil, use end of date-range or
  18542. time-range, if possible.
  18543. When optional argument UTC is non-nil, time is be expressed as
  18544. Universal Time."
  18545. (format-time-string format (org-timestamp-to-time timestamp end)
  18546. (and utc t)))
  18547. (defun org-timestamp-split-range (timestamp &optional end)
  18548. "Extract a TIMESTAMP object from a date or time range.
  18549. END, when non-nil, means extract the end of the range.
  18550. Otherwise, extract its start.
  18551. Return a new timestamp object."
  18552. (let ((type (org-element-property :type timestamp)))
  18553. (if (memq type '(active inactive diary)) timestamp
  18554. (let ((split-ts (org-element-copy timestamp)))
  18555. ;; Set new type.
  18556. (org-element-put-property
  18557. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  18558. ;; Copy start properties over end properties if END is
  18559. ;; non-nil. Otherwise, copy end properties over `start' ones.
  18560. (let ((p-alist '((:minute-start . :minute-end)
  18561. (:hour-start . :hour-end)
  18562. (:day-start . :day-end)
  18563. (:month-start . :month-end)
  18564. (:year-start . :year-end))))
  18565. (dolist (p-cell p-alist)
  18566. (org-element-put-property
  18567. split-ts
  18568. (funcall (if end #'car #'cdr) p-cell)
  18569. (org-element-property
  18570. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  18571. ;; Eventually refresh `:raw-value'.
  18572. (org-element-put-property split-ts :raw-value nil)
  18573. (org-element-put-property
  18574. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  18575. (defun org-timestamp-translate (timestamp &optional boundary)
  18576. "Translate TIMESTAMP object to custom format.
  18577. Format string is defined in `org-time-stamp-custom-formats',
  18578. which see.
  18579. When optional argument BOUNDARY is non-nil, it is either the
  18580. symbol `start' or `end'. In this case, only translate the
  18581. starting or ending part of TIMESTAMP if it is a date or time
  18582. range. Otherwise, translate both parts.
  18583. Return timestamp as-is if `org-display-custom-times' is nil or if
  18584. it has a `diary' type."
  18585. (let ((type (org-element-property :type timestamp)))
  18586. (if (or (not org-display-custom-times) (eq type 'diary))
  18587. (org-element-interpret-data timestamp)
  18588. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  18589. org-time-stamp-custom-formats)))
  18590. (if (and (not boundary) (memq type '(active-range inactive-range)))
  18591. (concat (org-timestamp-format timestamp fmt)
  18592. "--"
  18593. (org-timestamp-format timestamp fmt t))
  18594. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  18595. ;;; Other stuff
  18596. (defvar reftex-docstruct-symbol)
  18597. (defvar org--rds)
  18598. (defun org-reftex-citation ()
  18599. "Use `reftex-citation' to insert a citation into the buffer.
  18600. This looks for a line like
  18601. #+BIBLIOGRAPHY: foo plain option:-d
  18602. and derives from it that foo.bib is the bibliography file relevant
  18603. for this document. It then installs the necessary environment for RefTeX
  18604. to work in this buffer and calls `reftex-citation' to insert a citation
  18605. into the buffer.
  18606. Export of such citations to both LaTeX and HTML is handled by the contributed
  18607. package ox-bibtex by Taru Karttunen."
  18608. (interactive)
  18609. (let ((reftex-docstruct-symbol 'org--rds)
  18610. org--rds bib)
  18611. (org-with-wide-buffer
  18612. (let ((case-fold-search t)
  18613. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  18614. (if (not (save-excursion
  18615. (or (re-search-forward re nil t)
  18616. (re-search-backward re nil t))))
  18617. (user-error "No bibliography defined in file")
  18618. (setq bib (concat (match-string 1) ".bib")
  18619. org--rds (list (list 'bib bib))))))
  18620. (call-interactively 'reftex-citation)))
  18621. ;;;; Functions extending outline functionality
  18622. (defun org-beginning-of-line (&optional n)
  18623. "Go to the beginning of the current visible line.
  18624. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18625. symbol `reversed', on the first attempt move to where the
  18626. headline text starts, and only move to beginning of line when the
  18627. cursor is already before the start of the text of the headline.
  18628. If `org-special-ctrl-a/e' is symbol `reversed' then go to the
  18629. start of the text on the second attempt.
  18630. With argument N not nil or 1, move forward N - 1 lines first."
  18631. (interactive "^p")
  18632. (let ((origin (point))
  18633. (special (pcase org-special-ctrl-a/e
  18634. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  18635. deactivate-mark)
  18636. ;; First move to a visible line.
  18637. (if (bound-and-true-p visual-line-mode)
  18638. (beginning-of-visual-line n)
  18639. (move-beginning-of-line n)
  18640. ;; `move-beginning-of-line' may leave point after invisible
  18641. ;; characters if line starts with such of these (e.g., with
  18642. ;; a link at column 0). Really move to the beginning of the
  18643. ;; current visible line.
  18644. (beginning-of-line))
  18645. (cond
  18646. ;; No special behavior. Point is already at the beginning of
  18647. ;; a line, logical or visual.
  18648. ((not special))
  18649. ;; `beginning-of-visual-line' left point before logical beginning
  18650. ;; of line: point is at the beginning of a visual line. Bail
  18651. ;; out.
  18652. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  18653. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  18654. ;; At a headline, special position is before the title, but
  18655. ;; after any TODO keyword or priority cookie.
  18656. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  18657. (line-end-position)))
  18658. (bol (point)))
  18659. (if (eq special 'reversed)
  18660. (when (and (= origin bol) (eq last-command this-command))
  18661. (goto-char refpos))
  18662. (when (or (> origin refpos) (= origin bol))
  18663. (goto-char refpos)))))
  18664. ((and (looking-at org-list-full-item-re)
  18665. (memq (org-element-type (save-match-data (org-element-at-point)))
  18666. '(item plain-list)))
  18667. ;; Set special position at first white space character after
  18668. ;; bullet, and check-box, if any.
  18669. (let ((after-bullet
  18670. (let ((box (match-end 3)))
  18671. (cond ((not box) (match-end 1))
  18672. ((eq (char-after box) ?\s) (1+ box))
  18673. (t box)))))
  18674. (if (eq special 'reversed)
  18675. (when (and (= (point) origin) (eq last-command this-command))
  18676. (goto-char after-bullet))
  18677. (when (or (> origin after-bullet) (= (point) origin))
  18678. (goto-char after-bullet)))))
  18679. ;; No special context. Point is already at beginning of line.
  18680. (t nil))))
  18681. (defun org-end-of-line (&optional n)
  18682. "Go to the end of the line, but before ellipsis, if any.
  18683. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18684. symbol `reversed', ignore tags on the first attempt, and only
  18685. move to after the tags when the cursor is already beyond the end
  18686. of the headline.
  18687. If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
  18688. on the second attempt.
  18689. With argument N not nil or 1, move forward N - 1 lines first."
  18690. (interactive "^p")
  18691. (let ((origin (point))
  18692. (special (pcase org-special-ctrl-a/e
  18693. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  18694. deactivate-mark)
  18695. ;; First move to a visible line.
  18696. (if (bound-and-true-p visual-line-mode)
  18697. (beginning-of-visual-line n)
  18698. (move-beginning-of-line n))
  18699. (cond
  18700. ;; At a headline, with tags.
  18701. ((and special
  18702. (save-excursion
  18703. (beginning-of-line)
  18704. (let ((case-fold-search nil))
  18705. (looking-at org-complex-heading-regexp)))
  18706. (match-end 5))
  18707. (let ((tags (save-excursion
  18708. (goto-char (match-beginning 5))
  18709. (skip-chars-backward " \t")
  18710. (point)))
  18711. (visual-end (and (bound-and-true-p visual-line-mode)
  18712. (save-excursion
  18713. (end-of-visual-line)
  18714. (point)))))
  18715. ;; If `end-of-visual-line' brings us before end of line or
  18716. ;; even tags, i.e., the headline spans over multiple visual
  18717. ;; lines, move there.
  18718. (cond ((and visual-end
  18719. (< visual-end tags)
  18720. (<= origin visual-end))
  18721. (goto-char visual-end))
  18722. ((eq special 'reversed)
  18723. (if (and (= origin (line-end-position))
  18724. (eq this-command last-command))
  18725. (goto-char tags)
  18726. (end-of-line)))
  18727. (t
  18728. (if (or (< origin tags) (= origin (line-end-position)))
  18729. (goto-char tags)
  18730. (end-of-line))))))
  18731. ((bound-and-true-p visual-line-mode)
  18732. (let ((bol (line-beginning-position)))
  18733. (end-of-visual-line)
  18734. ;; If `end-of-visual-line' gets us past the ellipsis at the
  18735. ;; end of a line, backtrack and use `end-of-line' instead.
  18736. (when (/= bol (line-beginning-position))
  18737. (goto-char bol)
  18738. (end-of-line))))
  18739. (t (end-of-line)))))
  18740. (defun org-backward-sentence (&optional _arg)
  18741. "Go to beginning of sentence, or beginning of table field.
  18742. This will call `backward-sentence' or `org-table-beginning-of-field',
  18743. depending on context."
  18744. (interactive)
  18745. (let* ((element (org-element-at-point))
  18746. (contents-begin (org-element-property :contents-begin element))
  18747. (table (org-element-lineage element '(table) t)))
  18748. (if (and table
  18749. (> (point) contents-begin)
  18750. (<= (point) (org-element-property :contents-end table)))
  18751. (call-interactively #'org-table-beginning-of-field)
  18752. (save-restriction
  18753. (when (and contents-begin
  18754. (< (point-min) contents-begin)
  18755. (> (point) contents-begin))
  18756. (narrow-to-region contents-begin
  18757. (org-element-property :contents-end element)))
  18758. (call-interactively #'backward-sentence)))))
  18759. (defun org-forward-sentence (&optional _arg)
  18760. "Go to end of sentence, or end of table field.
  18761. This will call `forward-sentence' or `org-table-end-of-field',
  18762. depending on context."
  18763. (interactive)
  18764. (if (and (org-at-heading-p)
  18765. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  18766. (save-restriction
  18767. (narrow-to-region (line-beginning-position) (line-end-position))
  18768. (call-interactively #'forward-sentence))
  18769. (let* ((element (org-element-at-point))
  18770. (contents-end (org-element-property :contents-end element))
  18771. (table (org-element-lineage element '(table) t)))
  18772. (if (and table
  18773. (>= (point) (org-element-property :contents-begin table))
  18774. (< (point) contents-end))
  18775. (call-interactively #'org-table-end-of-field)
  18776. (save-restriction
  18777. (when (and contents-end
  18778. (> (point-max) contents-end)
  18779. ;; Skip blank lines between elements.
  18780. (< (org-element-property :end element)
  18781. (save-excursion (goto-char contents-end)
  18782. (skip-chars-forward " \r\t\n"))))
  18783. (narrow-to-region (org-element-property :contents-begin element)
  18784. contents-end))
  18785. ;; End of heading is considered as the end of a sentence.
  18786. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  18787. (call-interactively #'forward-sentence)))))))
  18788. (defun org-kill-line (&optional _arg)
  18789. "Kill line, to tags or end of line."
  18790. (interactive)
  18791. (cond
  18792. ((or (not org-special-ctrl-k)
  18793. (bolp)
  18794. (not (org-at-heading-p)))
  18795. (when (and (get-char-property (line-end-position) 'invisible)
  18796. org-ctrl-k-protect-subtree
  18797. (or (eq org-ctrl-k-protect-subtree 'error)
  18798. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  18799. (user-error
  18800. (substitute-command-keys
  18801. "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
  18802. (call-interactively
  18803. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  18804. ((org-match-line org-tag-line-re)
  18805. (let ((end (save-excursion
  18806. (goto-char (match-beginning 1))
  18807. (skip-chars-backward " \t")
  18808. (point))))
  18809. (if (<= end (point)) ;on tags part
  18810. (kill-region (point) (line-end-position))
  18811. (kill-region (point) end)))
  18812. ;; Only align tags when we are still on a heading:
  18813. (if (org-at-heading-p) (org-align-tags)))
  18814. (t (kill-region (point) (line-end-position)))))
  18815. (defun org-yank (&optional arg)
  18816. "Yank. If the kill is a subtree, treat it specially.
  18817. This command will look at the current kill and check if is a single
  18818. subtree, or a series of subtrees[1]. If it passes the test, and if the
  18819. cursor is at the beginning of a line or after the stars of a currently
  18820. empty headline, then the yank is handled specially. How exactly depends
  18821. on the value of the following variables.
  18822. `org-yank-folded-subtrees'
  18823. By default, this variable is non-nil, which results in
  18824. subtree(s) being folded after insertion, except if doing so
  18825. would swallow text after the yanked text.
  18826. `org-yank-adjusted-subtrees'
  18827. When non-nil (the default value is nil), the subtree will be
  18828. promoted or demoted in order to fit into the local outline tree
  18829. structure, which means that the level will be adjusted so that it
  18830. becomes the smaller one of the two *visible* surrounding headings.
  18831. Any prefix to this command will cause `yank' to be called directly with
  18832. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  18833. will just
  18834. plainly yank the text as it is.
  18835. \[1] The test checks if the first non-white line is a heading
  18836. and if there are no other headings with fewer stars."
  18837. (interactive "P")
  18838. (org-yank-generic 'yank arg))
  18839. (defun org-yank-generic (command arg)
  18840. "Perform some yank-like command.
  18841. This function implements the behavior described in the `org-yank'
  18842. documentation. However, it has been generalized to work for any
  18843. interactive command with similar behavior."
  18844. ;; pretend to be command COMMAND
  18845. (setq this-command command)
  18846. (if arg
  18847. (call-interactively command)
  18848. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  18849. (and (org-kill-is-subtree-p)
  18850. (or (bolp)
  18851. (and (looking-at "[ \t]*$")
  18852. (string-match
  18853. "\\`\\*+\\'"
  18854. (buffer-substring (point-at-bol) (point)))))))
  18855. swallowp)
  18856. (cond
  18857. ((and subtreep org-yank-folded-subtrees)
  18858. (let ((beg (point))
  18859. end)
  18860. (if (and subtreep org-yank-adjusted-subtrees)
  18861. (org-paste-subtree nil nil 'for-yank)
  18862. (call-interactively command))
  18863. (setq end (point))
  18864. (goto-char beg)
  18865. (when (and (bolp) subtreep
  18866. (not (setq swallowp
  18867. (org-yank-folding-would-swallow-text beg end))))
  18868. (org-with-limited-levels
  18869. (or (looking-at org-outline-regexp)
  18870. (re-search-forward org-outline-regexp-bol end t))
  18871. (while (and (< (point) end) (looking-at org-outline-regexp))
  18872. (org-flag-subtree t)
  18873. (org-cycle-show-empty-lines 'folded)
  18874. (condition-case nil
  18875. (outline-forward-same-level 1)
  18876. (error (goto-char end))))))
  18877. (when swallowp
  18878. (message
  18879. "Inserted text not folded because that would swallow text"))
  18880. (goto-char end)
  18881. (skip-chars-forward " \t\n\r")
  18882. (beginning-of-line 1)
  18883. (push-mark beg 'nomsg)))
  18884. ((and subtreep org-yank-adjusted-subtrees)
  18885. (let ((beg (point-at-bol)))
  18886. (org-paste-subtree nil nil 'for-yank)
  18887. (push-mark beg 'nomsg)))
  18888. (t
  18889. (call-interactively command))))))
  18890. (defun org-yank-folding-would-swallow-text (beg end)
  18891. "Would `hide-subtree' at BEG swallow any text after END?"
  18892. (let (level)
  18893. (org-with-limited-levels
  18894. (save-excursion
  18895. (goto-char beg)
  18896. (when (or (looking-at org-outline-regexp)
  18897. (re-search-forward org-outline-regexp-bol end t))
  18898. (setq level (org-outline-level)))
  18899. (goto-char end)
  18900. (skip-chars-forward " \t\r\n\v\f")
  18901. (not (or (eobp)
  18902. (and (bolp) (looking-at-p org-outline-regexp)
  18903. (<= (org-outline-level) level))))))))
  18904. (defun org-back-to-heading (&optional invisible-ok)
  18905. "Go back to beginning of heading."
  18906. (beginning-of-line)
  18907. (or (org-at-heading-p (not invisible-ok))
  18908. (let (found)
  18909. (save-excursion
  18910. ;; At inlinetask end. Move to bol, so that the following
  18911. ;; search goes to the beginning of the inlinetask.
  18912. (when (and (featurep 'org-inlinetask)
  18913. (fboundp 'org-inlinetask-end-p)
  18914. (org-inlinetask-end-p))
  18915. (goto-char (line-beginning-position)))
  18916. (while (not found)
  18917. (or (re-search-backward (concat "^\\(?:" outline-regexp "\\)")
  18918. nil t)
  18919. (user-error "Before first headline at position %d in buffer %s"
  18920. (point) (current-buffer)))
  18921. ;; Skip inlinetask end.
  18922. (if (and (featurep 'org-inlinetask)
  18923. (fboundp 'org-inlinetask-end-p)
  18924. (org-inlinetask-end-p))
  18925. (org-inlinetask-goto-beginning)
  18926. (setq found (and (or invisible-ok (not (org-invisible-p)))
  18927. (point))))))
  18928. (goto-char found)
  18929. found)))
  18930. (defun org-back-to-heading-or-point-min (&optional invisible-ok)
  18931. "Go back to heading or first point in buffer.
  18932. If point is before first heading go to first point in buffer
  18933. instead of back to heading."
  18934. (if (org-before-first-heading-p)
  18935. (goto-char (point-min))
  18936. (org-back-to-heading invisible-ok)))
  18937. (defun org-before-first-heading-p ()
  18938. "Before first heading?"
  18939. (org-with-limited-levels
  18940. (save-excursion
  18941. (end-of-line)
  18942. (null (re-search-backward org-outline-regexp-bol nil t)))))
  18943. (defun org-at-heading-p (&optional _)
  18944. "Non-nil when on a headline."
  18945. (outline-on-heading-p t))
  18946. (defun org-in-commented-heading-p (&optional no-inheritance element)
  18947. "Non-nil if point is under a commented heading.
  18948. This function also checks ancestors of the current headline,
  18949. unless optional argument NO-INHERITANCE is non-nil.
  18950. Optional argument ELEMENT contains element at point."
  18951. (save-match-data
  18952. (if-let ((el (or element (org-element-at-point nil 'cached))))
  18953. (catch :found
  18954. (setq el (org-element-lineage el '(headline) 'include-self))
  18955. (if no-inheritance
  18956. (org-element-property :commentedp el)
  18957. (while el
  18958. (when (org-element-property :commentedp el)
  18959. (throw :found t))
  18960. (setq el (org-element-property :parent el)))))
  18961. (cond
  18962. ((org-before-first-heading-p) nil)
  18963. ((let ((headline (nth 4 (org-heading-components))))
  18964. (and headline
  18965. (let ((case-fold-search nil))
  18966. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  18967. headline)))))
  18968. (no-inheritance nil)
  18969. (t
  18970. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))))
  18971. (defun org-in-archived-heading-p (&optional no-inheritance element)
  18972. "Non-nil if point is under an archived heading.
  18973. This function also checks ancestors of the current headline,
  18974. unless optional argument NO-INHERITANCE is non-nil.
  18975. Optional argument ELEMENT contains element at point."
  18976. (cond
  18977. ((org-before-first-heading-p) nil)
  18978. ((if element
  18979. (org-element-property :archivedp element)
  18980. (let ((tags (org-get-tags element 'local)))
  18981. (and tags
  18982. (cl-some (apply-partially #'string= org-archive-tag) tags)))))
  18983. (no-inheritance nil)
  18984. (t
  18985. (if (org-element--cache-active-p)
  18986. (cl-some (lambda (el) (org-element-property :archivedp el))
  18987. (org-element-lineage (org-element-at-point) nil t))
  18988. (save-excursion (and (org-up-heading-safe) (org-in-archived-heading-p)))))))
  18989. (defun org-at-comment-p nil
  18990. "Return t if cursor is in a commented line."
  18991. (save-excursion
  18992. (save-match-data
  18993. (beginning-of-line)
  18994. (looking-at org-comment-regexp))))
  18995. (defun org-at-keyword-p nil
  18996. "Return t if cursor is at a keyword-line."
  18997. (save-excursion
  18998. (move-beginning-of-line 1)
  18999. (looking-at org-keyword-regexp)))
  19000. (defun org-at-drawer-p nil
  19001. "Return t if cursor is at a drawer keyword."
  19002. (save-excursion
  19003. (move-beginning-of-line 1)
  19004. (looking-at org-drawer-regexp)))
  19005. (defun org-at-block-p nil
  19006. "Return t if cursor is at a block keyword."
  19007. (save-excursion
  19008. (move-beginning-of-line 1)
  19009. (looking-at org-block-regexp)))
  19010. (defun org-point-at-end-of-empty-headline ()
  19011. "If point is at the end of an empty headline, return t, else nil.
  19012. If the heading only contains a TODO keyword, it is still considered
  19013. empty."
  19014. (let ((case-fold-search nil))
  19015. (and (looking-at "[ \t]*$")
  19016. org-todo-line-regexp
  19017. (save-excursion
  19018. (beginning-of-line)
  19019. (looking-at org-todo-line-regexp)
  19020. (string= (match-string 3) "")))))
  19021. (defun org-at-heading-or-item-p ()
  19022. (or (org-at-heading-p) (org-at-item-p)))
  19023. (defun org-up-heading-all (arg)
  19024. "Move to the heading line of which the present line is a subheading.
  19025. This function considers both visible and invisible heading lines.
  19026. With argument, move up ARG levels."
  19027. (outline-up-heading arg t))
  19028. (defvar-local org--up-heading-cache nil
  19029. "Buffer-local `org-up-heading-safe' cache.")
  19030. (defvar-local org--up-heading-cache-tick nil
  19031. "Buffer `buffer-chars-modified-tick' in `org--up-heading-cache'.")
  19032. (defun org-up-heading-safe ()
  19033. "Move to the heading line of which the present line is a subheading.
  19034. This version will not throw an error. It will return the level of the
  19035. headline found, or nil if no higher level is found.
  19036. Also, this function will be a lot faster than `outline-up-heading',
  19037. because it relies on stars being the outline starters. This can really
  19038. make a significant difference in outlines with very many siblings."
  19039. (if-let ((element (and (org-element--cache-active-p)
  19040. (org-element-at-point nil t))))
  19041. (let* ((current-heading (org-element-lineage element '(headline) 'with-self))
  19042. (parent (org-element-lineage current-heading '(headline))))
  19043. (if (and parent
  19044. (<= (point-min) (org-element-property :begin parent)))
  19045. (progn
  19046. (goto-char (org-element-property :begin parent))
  19047. (org-element-property :level parent))
  19048. (when (and current-heading
  19049. (<= (point-min) (org-element-property :begin current-heading)))
  19050. (goto-char (org-element-property :begin current-heading))
  19051. nil)))
  19052. (when (ignore-errors (org-back-to-heading t))
  19053. (let (level-cache)
  19054. (unless org--up-heading-cache
  19055. (setq org--up-heading-cache (make-hash-table)))
  19056. (if (and (eq (buffer-chars-modified-tick) org--up-heading-cache-tick)
  19057. (setq level-cache (gethash (point) org--up-heading-cache)))
  19058. (when (<= (point-min) (car level-cache) (point-max))
  19059. ;; Parent is inside accessible part of the buffer.
  19060. (progn (goto-char (car level-cache))
  19061. (cdr level-cache)))
  19062. ;; Buffer modified. Invalidate cache.
  19063. (unless (eq (buffer-chars-modified-tick) org--up-heading-cache-tick)
  19064. (setq-local org--up-heading-cache-tick
  19065. (buffer-chars-modified-tick))
  19066. (clrhash org--up-heading-cache))
  19067. (let* ((level-up (1- (funcall outline-level)))
  19068. (pos (point))
  19069. (result (and (> level-up 0)
  19070. (re-search-backward
  19071. (format "^\\*\\{1,%d\\} " level-up) nil t)
  19072. (funcall outline-level))))
  19073. (when result (puthash pos (cons (point) result) org--up-heading-cache))
  19074. result))))))
  19075. (defun org-up-heading-or-point-min ()
  19076. "Move to the heading line of which the present is a subheading, or point-min.
  19077. This version is needed to make point-min behave like a virtual
  19078. heading of level 0 for property-inheritance. It will return the
  19079. level of the headline found (down to 0) or nil if already at a
  19080. point before the first headline or at point-min."
  19081. (when (ignore-errors (org-back-to-heading t))
  19082. (if (< 1 (funcall outline-level))
  19083. (or (org-up-heading-safe)
  19084. ;; The first heading may not be level 1 heading.
  19085. (goto-char (point-min)))
  19086. (unless (= (point) (point-min)) (goto-char (point-min))))))
  19087. (defun org-first-sibling-p ()
  19088. "Is this heading the first child of its parents?"
  19089. (interactive)
  19090. (let ((re org-outline-regexp-bol)
  19091. level l)
  19092. (unless (org-at-heading-p t)
  19093. (user-error "Not at a heading"))
  19094. (setq level (funcall outline-level))
  19095. (save-excursion
  19096. (if (not (re-search-backward re nil t))
  19097. t
  19098. (setq l (funcall outline-level))
  19099. (< l level)))))
  19100. (defun org-goto-sibling (&optional previous)
  19101. "Goto the next sibling, even if it is invisible.
  19102. When PREVIOUS is set, go to the previous sibling instead. Returns t
  19103. when a sibling was found. When none is found, return nil and don't
  19104. move point."
  19105. (let ((fun (if previous 're-search-backward 're-search-forward))
  19106. (pos (point))
  19107. (re org-outline-regexp-bol)
  19108. level l)
  19109. (when (ignore-errors (org-back-to-heading t))
  19110. (setq level (funcall outline-level))
  19111. (catch 'exit
  19112. (or previous (forward-char 1))
  19113. (while (funcall fun re nil t)
  19114. (setq l (funcall outline-level))
  19115. (when (< l level) (goto-char pos) (throw 'exit nil))
  19116. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  19117. (goto-char pos)
  19118. nil))))
  19119. (defun org-show-siblings ()
  19120. "Show all siblings of the current headline."
  19121. (save-excursion
  19122. (while (org-goto-sibling) (org-flag-heading nil)))
  19123. (save-excursion
  19124. (while (org-goto-sibling 'previous)
  19125. (org-flag-heading nil))))
  19126. (defun org-goto-first-child (&optional element)
  19127. "Goto the first child, even if it is invisible.
  19128. Return t when a child was found. Otherwise don't move point and
  19129. return nil."
  19130. (if (org-element--cache-active-p)
  19131. (when-let ((heading (org-element-lineage
  19132. (or element (org-element-at-point))
  19133. '(headline inlinetask org-data)
  19134. t)))
  19135. (unless (or (eq 'inlinetask (org-element-type heading))
  19136. (not (org-element-property :contents-begin heading)))
  19137. (let ((pos (point)))
  19138. (goto-char (org-element-property :contents-begin heading))
  19139. (if (re-search-forward
  19140. org-outline-regexp-bol
  19141. (org-element-property :end heading)
  19142. t)
  19143. (progn (goto-char (match-beginning 0)) t)
  19144. (goto-char pos) nil))))
  19145. (let (level (pos (point)) (re org-outline-regexp-bol))
  19146. (when (org-back-to-heading-or-point-min t)
  19147. (setq level (org-outline-level))
  19148. (forward-char 1)
  19149. (if (and (re-search-forward re nil t) (> (org-outline-level) level))
  19150. (progn (goto-char (match-beginning 0)) t)
  19151. (goto-char pos) nil)))))
  19152. (defun org-show-hidden-entry ()
  19153. "Show an entry where even the heading is hidden."
  19154. (save-excursion
  19155. (org-show-entry)))
  19156. (defun org-flag-heading (flag &optional entry)
  19157. "Flag the current heading. FLAG non-nil means make invisible.
  19158. When ENTRY is non-nil, show the entire entry."
  19159. (save-excursion
  19160. (org-back-to-heading t)
  19161. ;; Check if we should show the entire entry
  19162. (if (not entry)
  19163. (org-flag-region
  19164. (line-end-position 0) (line-end-position) flag 'outline)
  19165. (org-show-entry)
  19166. (save-excursion
  19167. (and (outline-next-heading)
  19168. (org-flag-heading nil))))))
  19169. (defun org-get-next-sibling ()
  19170. "Move to next heading of the same level, and return point.
  19171. If there is no such heading, return nil.
  19172. This is like outline-next-sibling, but invisible headings are ok."
  19173. (let ((level (funcall outline-level)))
  19174. (outline-next-heading)
  19175. (while (and (not (eobp)) (> (funcall outline-level) level))
  19176. (outline-next-heading))
  19177. (unless (or (eobp) (< (funcall outline-level) level))
  19178. (point))))
  19179. (defun org-get-previous-sibling ()
  19180. "Move to previous heading of the same level, and return point.
  19181. If there is no such heading, return nil."
  19182. (let ((opoint (point))
  19183. (level (funcall outline-level)))
  19184. (outline-previous-heading)
  19185. (when (and (/= (point) opoint) (outline-on-heading-p t))
  19186. (while (and (> (funcall outline-level) level)
  19187. (not (bobp)))
  19188. (outline-previous-heading))
  19189. (unless (< (funcall outline-level) level)
  19190. (point)))))
  19191. (defun org-end-of-subtree (&optional invisible-ok to-heading element)
  19192. "Goto to the end of a subtree at point or for ELEMENT heading."
  19193. ;; This contains an exact copy of the original function, but it uses
  19194. ;; `org-back-to-heading-or-point-min', to make it work also in invisible
  19195. ;; trees and before first headline. And is uses an invisible-ok argument.
  19196. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  19197. ;; Furthermore, when used inside Org, finding the end of a large subtree
  19198. ;; with many children and grandchildren etc, this can be much faster
  19199. ;; than the outline version.
  19200. (org-back-to-heading-or-point-min invisible-ok)
  19201. (unless (and (org-element--cache-active-p)
  19202. (let ((cached (or element (org-element-at-point nil t))))
  19203. (and cached
  19204. (eq 'headline (org-element-type cached))
  19205. (goto-char (org-element-property
  19206. :end cached)))))
  19207. (let ((first t)
  19208. (level (funcall outline-level)))
  19209. (cond ((= level 0)
  19210. (goto-char (point-max)))
  19211. ((and (derived-mode-p 'org-mode) (< level 1000))
  19212. ;; A true heading (not a plain list item), in Org
  19213. ;; This means we can easily find the end by looking
  19214. ;; only for the right number of stars. Using a regexp to do
  19215. ;; this is so much faster than using a Lisp loop.
  19216. (let ((re (concat "^\\*\\{1," (number-to-string level) "\\} ")))
  19217. (forward-char 1)
  19218. (and (re-search-forward re nil 'move) (beginning-of-line 1))))
  19219. (t
  19220. ;; something else, do it the slow way
  19221. (while (and (not (eobp))
  19222. (or first (> (funcall outline-level) level)))
  19223. (setq first nil)
  19224. (outline-next-heading))))))
  19225. (unless to-heading
  19226. (when (memq (preceding-char) '(?\n ?\^M))
  19227. ;; Go to end of line before heading
  19228. (forward-char -1)
  19229. (when (memq (preceding-char) '(?\n ?\^M))
  19230. ;; leave blank line before heading
  19231. (forward-char -1))))
  19232. (point))
  19233. (defun org-end-of-meta-data (&optional full)
  19234. "Skip planning line and properties drawer in current entry.
  19235. When optional argument FULL is t, also skip planning information,
  19236. clocking lines and any kind of drawer.
  19237. When FULL is non-nil but not t, skip planning information,
  19238. properties, clocking lines and logbook drawers."
  19239. (org-back-to-heading t)
  19240. (forward-line)
  19241. ;; Skip planning information.
  19242. (when (looking-at-p org-planning-line-re) (forward-line))
  19243. ;; Skip property drawer.
  19244. (when (looking-at org-property-drawer-re)
  19245. (goto-char (match-end 0))
  19246. (forward-line))
  19247. ;; When FULL is not nil, skip more.
  19248. (when (and full (not (org-at-heading-p)))
  19249. (catch 'exit
  19250. (let ((end (save-excursion (outline-next-heading) (point)))
  19251. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  19252. (while (not (eobp))
  19253. (cond ;; Skip clock lines.
  19254. ((looking-at-p re) (forward-line))
  19255. ;; Skip logbook drawer.
  19256. ((looking-at-p org-logbook-drawer-re)
  19257. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  19258. (forward-line)
  19259. (throw 'exit t)))
  19260. ;; When FULL is t, skip regular drawer too.
  19261. ((and (eq full t) (looking-at-p org-drawer-regexp))
  19262. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  19263. (forward-line)
  19264. (throw 'exit t)))
  19265. (t (throw 'exit t))))))))
  19266. (defun org--line-fully-invisible-p ()
  19267. "Return non-nil if the current line is fully invisible."
  19268. (let ((line-beg (line-beginning-position))
  19269. (line-pos (1- (line-end-position)))
  19270. (is-invisible t))
  19271. (while (and (< line-beg line-pos) is-invisible)
  19272. (setq is-invisible (org-invisible-p line-pos))
  19273. (setq line-pos (1- line-pos)))
  19274. is-invisible))
  19275. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  19276. "Move forward to the ARG'th subheading at same level as this one.
  19277. Stop at the first and last subheadings of a superior heading.
  19278. Normally this only looks at visible headings, but when INVISIBLE-OK is
  19279. non-nil it will also look at invisible ones."
  19280. (interactive "p")
  19281. (let ((backward? (and arg (< arg 0))))
  19282. (if (org-before-first-heading-p)
  19283. (if backward? (goto-char (point-min)) (outline-next-heading))
  19284. (org-back-to-heading invisible-ok)
  19285. (unless backward? (end-of-line)) ;do not match current headline
  19286. (let ((level (- (match-end 0) (match-beginning 0) 1))
  19287. (f (if backward? #'re-search-backward #'re-search-forward))
  19288. (count (if arg (abs arg) 1))
  19289. (result (point)))
  19290. (while (and (> count 0)
  19291. (funcall f org-outline-regexp-bol nil 'move))
  19292. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  19293. (cond ((< l level) (setq count 0))
  19294. ((and (= l level)
  19295. (or invisible-ok
  19296. ;; FIXME: See commit a700fadd72 and the
  19297. ;; related discussion on why using
  19298. ;; `org--line-fully-invisible-p' is needed
  19299. ;; here, which is to serve the needs of an
  19300. ;; external package. If the change is
  19301. ;; wrong regarding Org itself, it should
  19302. ;; be removed.
  19303. (not (org--line-fully-invisible-p))))
  19304. (cl-decf count)
  19305. (when (= l level) (setq result (point)))))))
  19306. (goto-char result))
  19307. (beginning-of-line))))
  19308. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  19309. "Move backward to the ARG'th subheading at same level as this one.
  19310. Stop at the first and last subheadings of a superior heading."
  19311. (interactive "p")
  19312. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  19313. (defun org-next-visible-heading (arg)
  19314. "Move to the next visible heading line.
  19315. With ARG, repeats or can move backward if negative."
  19316. (interactive "p")
  19317. (let ((regexp (concat "^" (org-get-limited-outline-regexp))))
  19318. (if (< arg 0)
  19319. (beginning-of-line)
  19320. (end-of-line))
  19321. (while (and (< arg 0) (re-search-backward regexp nil :move))
  19322. (unless (bobp)
  19323. (while (pcase (get-char-property-and-overlay (point) 'invisible)
  19324. (`(outline . ,o)
  19325. (goto-char (overlay-start o))
  19326. (re-search-backward regexp nil :move))
  19327. (_ nil))))
  19328. (cl-incf arg))
  19329. (while (and (> arg 0) (re-search-forward regexp nil t))
  19330. (while (pcase (get-char-property-and-overlay (point) 'invisible)
  19331. (`(outline . ,o)
  19332. (goto-char (overlay-end o))
  19333. (re-search-forward regexp nil :move))
  19334. (_
  19335. (end-of-line)
  19336. nil))) ;leave the loop
  19337. (cl-decf arg))
  19338. (if (> arg 0) (goto-char (point-max)) (beginning-of-line))))
  19339. (defun org-previous-visible-heading (arg)
  19340. "Move to the previous visible heading.
  19341. With ARG, repeats or can move forward if negative."
  19342. (interactive "p")
  19343. (org-next-visible-heading (- arg)))
  19344. (defun org-forward-paragraph (&optional arg)
  19345. "Move forward by a paragraph, or equivalent, unit.
  19346. With argument ARG, do it ARG times;
  19347. a negative argument ARG = -N means move backward N paragraphs.
  19348. The function moves point between two structural
  19349. elements (paragraphs, tables, lists, etc.).
  19350. It also provides the following special moves for convenience:
  19351. - on a table or a property drawer, move to its beginning;
  19352. - on comment, example, export, source and verse blocks, stop
  19353. at blank lines;
  19354. - skip consecutive clocks, diary S-exps, and keywords."
  19355. (interactive "^p")
  19356. (unless arg (setq arg 1))
  19357. (if (< arg 0) (org-backward-paragraph (- arg))
  19358. (while (and (> arg 0) (not (eobp)))
  19359. (org--forward-paragraph-once)
  19360. (cl-decf arg))
  19361. ;; Return moves left.
  19362. arg))
  19363. (defun org-backward-paragraph (&optional arg)
  19364. "Move backward by a paragraph, or equivalent, unit.
  19365. With argument ARG, do it ARG times;
  19366. a negative argument ARG = -N means move forward N paragraphs.
  19367. The function moves point between two structural
  19368. elements (paragraphs, tables, lists, etc.).
  19369. It also provides the following special moves for convenience:
  19370. - on a table or a property drawer, move to its beginning;
  19371. - on comment, example, export, source and verse blocks, stop
  19372. at blank lines;
  19373. - skip consecutive clocks, diary S-exps, and keywords."
  19374. (interactive "^p")
  19375. (unless arg (setq arg 1))
  19376. (if (< arg 0) (org-forward-paragraph (- arg))
  19377. (while (and (> arg 0) (not (bobp)))
  19378. (org--backward-paragraph-once)
  19379. (cl-decf arg))
  19380. ;; Return moves left.
  19381. arg))
  19382. (defun org--paragraph-at-point ()
  19383. "Return paragraph, or equivalent, element at point.
  19384. Paragraph element at point is the element at point, with the
  19385. following special cases:
  19386. - treat table rows (resp. node properties) as the table
  19387. \(resp. property drawer) containing them.
  19388. - treat plain lists with an item every line as a whole.
  19389. - treat consecutive keywords, clocks, and diary-sexps as a single
  19390. block.
  19391. Function may return a real element, or a pseudo-element with type
  19392. `pseudo-paragraph'."
  19393. (let* ((e (org-element-at-point))
  19394. (type (org-element-type e))
  19395. ;; If we need to fake a new pseudo-element, triplet is
  19396. ;;
  19397. ;; (BEG END PARENT)
  19398. ;;
  19399. ;; where BEG and END are element boundaries, and PARENT the
  19400. ;; element containing it, or nil.
  19401. (triplet
  19402. (cond
  19403. ((memq type '(table property-drawer))
  19404. (list (org-element-property :begin e)
  19405. (org-element-property :end e)
  19406. (org-element-property :parent e)))
  19407. ((memq type '(node-property table-row))
  19408. (let ((e (org-element-property :parent e)))
  19409. (list (org-element-property :begin e)
  19410. (org-element-property :end e)
  19411. (org-element-property :parent e))))
  19412. ((memq type '(clock diary-sexp keyword))
  19413. (let* ((regexp (pcase type
  19414. (`clock org-clock-line-re)
  19415. (`diary-sexp "%%(")
  19416. (_ org-keyword-regexp)))
  19417. (end (if (< 0 (org-element-property :post-blank e))
  19418. (org-element-property :end e)
  19419. (org-with-wide-buffer
  19420. (forward-line)
  19421. (while (looking-at regexp) (forward-line))
  19422. (skip-chars-forward " \t\n")
  19423. (line-beginning-position))))
  19424. (begin (org-with-point-at (org-element-property :begin e)
  19425. (while (and (not (bobp)) (looking-at regexp))
  19426. (forward-line -1))
  19427. ;; We may have gotten one line too far.
  19428. (if (looking-at regexp)
  19429. (point)
  19430. (line-beginning-position 2)))))
  19431. (list begin end (org-element-property :parent e))))
  19432. ;; Find the full plain list containing point, the check it
  19433. ;; contains exactly one line per item.
  19434. ((let ((l (org-element-lineage e '(plain-list) t)))
  19435. (while (memq (org-element-type (org-element-property :parent l))
  19436. '(item plain-list))
  19437. (setq l (org-element-property :parent l)))
  19438. (and l
  19439. (org-with-point-at (org-element-property :post-affiliated l)
  19440. (forward-line (length (org-element-property :structure l)))
  19441. (= (point) (org-element-property :contents-end l)))
  19442. ;; Return value.
  19443. (list (org-element-property :begin l)
  19444. (org-element-property :end l)
  19445. (org-element-property :parent l)))))
  19446. (t nil)))) ;no triplet: return element
  19447. (pcase triplet
  19448. (`(,b ,e ,p)
  19449. (org-element-create
  19450. 'pseudo-paragraph
  19451. (list :begin b :end e :parent p :post-blank 0 :post-affiliated b)))
  19452. (_ e))))
  19453. (defun org--forward-paragraph-once ()
  19454. "Move forward to end of paragraph or equivalent, once.
  19455. See `org-forward-paragraph'."
  19456. (interactive)
  19457. (save-restriction
  19458. (widen)
  19459. (skip-chars-forward " \t\n")
  19460. (cond
  19461. ((eobp) nil)
  19462. ;; When inside a folded part, move out of it.
  19463. ((pcase (get-char-property-and-overlay (point) 'invisible)
  19464. (`(,(or `outline `org-hide-block) . ,o)
  19465. (goto-char (overlay-end o))
  19466. (forward-line)
  19467. t)
  19468. (_ nil)))
  19469. (t
  19470. (let* ((element (org--paragraph-at-point))
  19471. (type (org-element-type element))
  19472. (contents-begin (org-element-property :contents-begin element))
  19473. (end (org-element-property :end element))
  19474. (post-affiliated (org-element-property :post-affiliated element)))
  19475. (cond
  19476. ((eq type 'plain-list)
  19477. (forward-char)
  19478. (org--forward-paragraph-once))
  19479. ;; If the element is folded, skip it altogether.
  19480. ((pcase (org-with-point-at post-affiliated
  19481. (get-char-property-and-overlay (line-end-position)
  19482. 'invisible))
  19483. (`(,(or `outline `org-hide-block) . ,o)
  19484. (goto-char (overlay-end o))
  19485. (forward-line)
  19486. t)
  19487. (_ nil)))
  19488. ;; At a greater element, move inside.
  19489. ((and contents-begin
  19490. (> contents-begin (point))
  19491. (not (eq type 'paragraph)))
  19492. (goto-char contents-begin)
  19493. ;; Items and footnote definitions contents may not start at
  19494. ;; the beginning of the line. In this case, skip until the
  19495. ;; next paragraph.
  19496. (cond
  19497. ((not (bolp)) (org--forward-paragraph-once))
  19498. ((org-previous-line-empty-p) (forward-line -1))
  19499. (t nil)))
  19500. ;; Move between empty lines in some blocks.
  19501. ((memq type '(comment-block example-block export-block src-block
  19502. verse-block))
  19503. (let ((contents-start
  19504. (org-with-point-at post-affiliated
  19505. (line-beginning-position 2))))
  19506. (if (< (point) contents-start)
  19507. (goto-char contents-start)
  19508. (let ((contents-end
  19509. (org-with-point-at end
  19510. (skip-chars-backward " \t\n")
  19511. (line-beginning-position))))
  19512. (cond
  19513. ((>= (point) contents-end)
  19514. (goto-char end)
  19515. (skip-chars-backward " \t\n")
  19516. (forward-line))
  19517. ((re-search-forward "^[ \t]*\n" contents-end :move)
  19518. (forward-line -1))
  19519. (t nil))))))
  19520. (t
  19521. ;; Move to element's end.
  19522. (goto-char end)
  19523. (skip-chars-backward " \t\n")
  19524. (forward-line))))))))
  19525. (defun org--backward-paragraph-once ()
  19526. "Move backward to start of paragraph or equivalent, once.
  19527. See `org-backward-paragraph'."
  19528. (interactive)
  19529. (save-restriction
  19530. (widen)
  19531. (cond
  19532. ((bobp) nil)
  19533. ;; Blank lines at the beginning of the buffer.
  19534. ((and (org-match-line "^[ \t]*$")
  19535. (save-excursion (skip-chars-backward " \t\n") (bobp)))
  19536. (goto-char (point-min)))
  19537. ;; When inside a folded part, move out of it.
  19538. ((pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  19539. (`(,(or `outline `org-hide-block) . ,o)
  19540. (goto-char (1- (overlay-start o)))
  19541. (org--backward-paragraph-once)
  19542. t)
  19543. (_ nil)))
  19544. (t
  19545. (let* ((element (org--paragraph-at-point))
  19546. (type (org-element-type element))
  19547. (begin (org-element-property :begin element))
  19548. (post-affiliated (org-element-property :post-affiliated element))
  19549. (contents-end (org-element-property :contents-end element))
  19550. (end (org-element-property :end element))
  19551. (parent (org-element-property :parent element))
  19552. (reach
  19553. ;; Move to the visible empty line above position P, or
  19554. ;; to position P. Return t.
  19555. (lambda (p)
  19556. (goto-char p)
  19557. (when (and (org-previous-line-empty-p)
  19558. (let ((end (line-end-position 0)))
  19559. (or (= end (point-min))
  19560. (not (org-invisible-p (1- end))))))
  19561. (forward-line -1))
  19562. t)))
  19563. (cond
  19564. ;; Already at the beginning of an element.
  19565. ((= begin (point))
  19566. (cond
  19567. ;; There is a blank line above. Move there.
  19568. ((and (org-previous-line-empty-p)
  19569. (let ((lep (line-end-position 0)))
  19570. ;; When the first headline start at point 2, don't choke while
  19571. ;; checking with `org-invisible-p'.
  19572. (or (= lep 1)
  19573. (not (org-invisible-p (1- (line-end-position 0)))))))
  19574. (forward-line -1))
  19575. ;; At the beginning of the first element within a greater
  19576. ;; element. Move to the beginning of the greater element.
  19577. ((and parent (= begin (org-element-property :contents-begin parent)))
  19578. (funcall reach (org-element-property :begin parent)))
  19579. ;; Since we have to move anyway, find the beginning
  19580. ;; position of the element above.
  19581. (t
  19582. (forward-char -1)
  19583. (org--backward-paragraph-once))))
  19584. ;; Skip paragraphs at the very beginning of footnote
  19585. ;; definitions or items.
  19586. ((and (eq type 'paragraph)
  19587. (org-with-point-at begin (not (bolp))))
  19588. (funcall reach (progn (goto-char begin) (line-beginning-position))))
  19589. ;; If the element is folded, skip it altogether.
  19590. ((org-with-point-at post-affiliated
  19591. (org-invisible-p (line-end-position) t))
  19592. (funcall reach begin))
  19593. ;; At the end of a greater element, move inside.
  19594. ((and contents-end
  19595. (<= contents-end (point))
  19596. (not (eq type 'paragraph)))
  19597. (cond
  19598. ((memq type '(footnote-definition plain-list))
  19599. (skip-chars-backward " \t\n")
  19600. (org--backward-paragraph-once))
  19601. ((= contents-end (point))
  19602. (forward-char -1)
  19603. (org--backward-paragraph-once))
  19604. (t
  19605. (goto-char contents-end))))
  19606. ;; Move between empty lines in some blocks.
  19607. ((and (memq type '(comment-block example-block export-block src-block
  19608. verse-block))
  19609. (let ((contents-start
  19610. (org-with-point-at post-affiliated
  19611. (line-beginning-position 2))))
  19612. (when (> (point) contents-start)
  19613. (let ((contents-end
  19614. (org-with-point-at end
  19615. (skip-chars-backward " \t\n")
  19616. (line-beginning-position))))
  19617. (if (> (point) contents-end)
  19618. (progn (goto-char contents-end) t)
  19619. (skip-chars-backward " \t\n" begin)
  19620. (re-search-backward "^[ \t]*\n" contents-start :move)
  19621. t))))))
  19622. ;; Move to element's start.
  19623. (t
  19624. (funcall reach begin))))))))
  19625. (defun org-forward-element ()
  19626. "Move forward by one element.
  19627. Move to the next element at the same level, when possible."
  19628. (interactive)
  19629. (cond ((eobp) (user-error "Cannot move further down"))
  19630. ((org-with-limited-levels (org-at-heading-p))
  19631. (let ((origin (point)))
  19632. (goto-char (org-end-of-subtree nil t))
  19633. (unless (org-with-limited-levels (org-at-heading-p))
  19634. (goto-char origin)
  19635. (user-error "Cannot move further down"))))
  19636. (t
  19637. (let* ((elem (org-element-at-point))
  19638. (end (org-element-property :end elem))
  19639. (parent (org-element-property :parent elem)))
  19640. (cond ((and parent (= (org-element-property :contents-end parent) end))
  19641. (goto-char (org-element-property :end parent)))
  19642. ((integer-or-marker-p end) (goto-char end))
  19643. (t (message "No element at point")))))))
  19644. (defun org-backward-element ()
  19645. "Move backward by one element.
  19646. Move to the previous element at the same level, when possible."
  19647. (interactive)
  19648. (cond ((bobp) (user-error "Cannot move further up"))
  19649. ((org-with-limited-levels (org-at-heading-p))
  19650. ;; At a headline, move to the previous one, if any, or stay
  19651. ;; here.
  19652. (let ((origin (point)))
  19653. (org-with-limited-levels (org-backward-heading-same-level 1))
  19654. ;; When current headline has no sibling above, move to its
  19655. ;; parent.
  19656. (when (= (point) origin)
  19657. (or (org-with-limited-levels (org-up-heading-safe))
  19658. (progn (goto-char origin)
  19659. (user-error "Cannot move further up"))))))
  19660. (t
  19661. (let* ((elem (org-element-at-point))
  19662. (beg (org-element-property :begin elem)))
  19663. (cond
  19664. ;; Move to beginning of current element if point isn't
  19665. ;; there already.
  19666. ((null beg) (message "No element at point"))
  19667. ((/= (point) beg) (goto-char beg))
  19668. (t (goto-char beg)
  19669. (skip-chars-backward " \r\t\n")
  19670. (unless (bobp)
  19671. (let ((prev (org-element-at-point)))
  19672. (goto-char (org-element-property :begin prev))
  19673. (while (and (setq prev (org-element-property :parent prev))
  19674. (<= (org-element-property :end prev) beg))
  19675. (goto-char (org-element-property :begin prev)))))))))))
  19676. (defun org-up-element ()
  19677. "Move to upper element."
  19678. (interactive)
  19679. (if (org-with-limited-levels (org-at-heading-p))
  19680. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  19681. (let* ((elem (org-element-at-point))
  19682. (parent (org-element-property :parent elem)))
  19683. (if (and parent
  19684. (not (memq (org-element-type parent) '(section org-data))))
  19685. (goto-char (org-element-property :begin parent))
  19686. (if (org-with-limited-levels (org-before-first-heading-p))
  19687. (user-error "No surrounding element")
  19688. (org-with-limited-levels (org-back-to-heading)))))))
  19689. (defun org-down-element ()
  19690. "Move to inner element."
  19691. (interactive)
  19692. (let ((element (org-element-at-point)))
  19693. (cond
  19694. ((memq (org-element-type element) '(plain-list table))
  19695. (goto-char (org-element-property :contents-begin element))
  19696. (forward-char))
  19697. ((memq (org-element-type element) org-element-greater-elements)
  19698. ;; If contents are hidden, first disclose them.
  19699. (when (org-invisible-p (line-end-position)) (org-cycle))
  19700. (goto-char (or (org-element-property :contents-begin element)
  19701. (user-error "No content for this element"))))
  19702. (t (user-error "No inner element")))))
  19703. (defun org-drag-element-backward ()
  19704. "Move backward element at point."
  19705. (interactive)
  19706. (let ((elem (or (org-element-at-point)
  19707. (user-error "No element at point"))))
  19708. (if (eq (org-element-type elem) 'headline)
  19709. ;; Preserve point when moving a whole tree, even if point was
  19710. ;; on blank lines below the headline.
  19711. (let ((offset (skip-chars-backward " \t\n")))
  19712. (unwind-protect (org-move-subtree-up)
  19713. (forward-char (- offset))))
  19714. (let ((prev-elem
  19715. (save-excursion
  19716. (goto-char (org-element-property :begin elem))
  19717. (skip-chars-backward " \r\t\n")
  19718. (unless (bobp)
  19719. (let* ((beg (org-element-property :begin elem))
  19720. (prev (org-element-at-point))
  19721. (up prev))
  19722. (while (and (setq up (org-element-property :parent up))
  19723. (<= (org-element-property :end up) beg))
  19724. (setq prev up))
  19725. prev)))))
  19726. ;; Error out if no previous element or previous element is
  19727. ;; a parent of the current one.
  19728. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  19729. (user-error "Cannot drag element backward")
  19730. (let ((pos (point)))
  19731. (org-element-swap-A-B prev-elem elem)
  19732. (goto-char (+ (org-element-property :begin prev-elem)
  19733. (- pos (org-element-property :begin elem))))))))))
  19734. (defun org-drag-element-forward ()
  19735. "Move forward element at point."
  19736. (interactive)
  19737. (let* ((pos (point))
  19738. (elem (or (org-element-at-point)
  19739. (user-error "No element at point"))))
  19740. (when (= (point-max) (org-element-property :end elem))
  19741. (user-error "Cannot drag element forward"))
  19742. (goto-char (org-element-property :end elem))
  19743. (let ((next-elem (org-element-at-point)))
  19744. (when (or (org-element-nested-p elem next-elem)
  19745. (and (eq (org-element-type next-elem) 'headline)
  19746. (not (eq (org-element-type elem) 'headline))))
  19747. (goto-char pos)
  19748. (user-error "Cannot drag element forward"))
  19749. ;; Compute new position of point: it's shifted by NEXT-ELEM
  19750. ;; body's length (without final blanks) and by the length of
  19751. ;; blanks between ELEM and NEXT-ELEM.
  19752. (let ((size-next (- (save-excursion
  19753. (goto-char (org-element-property :end next-elem))
  19754. (skip-chars-backward " \r\t\n")
  19755. (forward-line)
  19756. ;; Small correction if buffer doesn't end
  19757. ;; with a newline character.
  19758. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  19759. (org-element-property :begin next-elem)))
  19760. (size-blank (- (org-element-property :end elem)
  19761. (save-excursion
  19762. (goto-char (org-element-property :end elem))
  19763. (skip-chars-backward " \r\t\n")
  19764. (forward-line)
  19765. (point)))))
  19766. (org-element-swap-A-B elem next-elem)
  19767. (goto-char (+ pos size-next size-blank))))))
  19768. (defun org-drag-line-forward (arg)
  19769. "Drag the line at point ARG lines forward."
  19770. (interactive "p")
  19771. (dotimes (_ (abs arg))
  19772. (let ((c (current-column)))
  19773. (if (< 0 arg)
  19774. (progn
  19775. (beginning-of-line 2)
  19776. (transpose-lines 1)
  19777. (beginning-of-line 0))
  19778. (transpose-lines 1)
  19779. (beginning-of-line -1))
  19780. (org-move-to-column c))))
  19781. (defun org-drag-line-backward (arg)
  19782. "Drag the line at point ARG lines backward."
  19783. (interactive "p")
  19784. (org-drag-line-forward (- arg)))
  19785. (defun org-mark-element ()
  19786. "Put point at beginning of this element, mark at end.
  19787. Interactively, if this command is repeated or (in Transient Mark
  19788. mode) if the mark is active, it marks the next element after the
  19789. ones already marked."
  19790. (interactive)
  19791. (let (deactivate-mark)
  19792. (if (and (called-interactively-p 'any)
  19793. (or (and (eq last-command this-command) (mark t))
  19794. (and transient-mark-mode mark-active)))
  19795. (set-mark
  19796. (save-excursion
  19797. (goto-char (mark))
  19798. (goto-char (org-element-property :end (org-element-at-point)))
  19799. (point)))
  19800. (let ((element (org-element-at-point)))
  19801. (end-of-line)
  19802. (push-mark (min (point-max) (org-element-property :end element)) t t)
  19803. (goto-char (org-element-property :begin element))))))
  19804. (defun org-narrow-to-element ()
  19805. "Narrow buffer to current element."
  19806. (interactive)
  19807. (let ((elem (org-element-at-point)))
  19808. (cond
  19809. ((eq (car elem) 'headline)
  19810. (narrow-to-region
  19811. (org-element-property :begin elem)
  19812. (org-element-property :end elem)))
  19813. ((memq (car elem) org-element-greater-elements)
  19814. (narrow-to-region
  19815. (org-element-property :contents-begin elem)
  19816. (org-element-property :contents-end elem)))
  19817. (t
  19818. (narrow-to-region
  19819. (org-element-property :begin elem)
  19820. (org-element-property :end elem))))))
  19821. (defun org-transpose-element ()
  19822. "Transpose current and previous elements, keeping blank lines between.
  19823. Point is moved after both elements."
  19824. (interactive)
  19825. (org-skip-whitespace)
  19826. (let ((end (org-element-property :end (org-element-at-point))))
  19827. (org-drag-element-backward)
  19828. (goto-char end)))
  19829. (defun org-unindent-buffer ()
  19830. "Un-indent the visible part of the buffer.
  19831. Relative indentation (between items, inside blocks, etc.) isn't
  19832. modified."
  19833. (interactive)
  19834. (unless (eq major-mode 'org-mode)
  19835. (user-error "Cannot un-indent a buffer not in Org mode"))
  19836. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  19837. (unindent-tree
  19838. (lambda (contents)
  19839. (dolist (element (reverse contents))
  19840. (if (memq (org-element-type element) '(headline section))
  19841. (funcall unindent-tree (org-element-contents element))
  19842. (save-excursion
  19843. (save-restriction
  19844. (narrow-to-region
  19845. (org-element-property :begin element)
  19846. (org-element-property :end element))
  19847. (org-do-remove-indentation))))))))
  19848. (funcall unindent-tree (org-element-contents parse-tree))))
  19849. (defun org-make-options-regexp (kwds &optional extra)
  19850. "Make a regular expression for keyword lines.
  19851. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  19852. when non-nil, is a regexp matching keywords names."
  19853. (concat "^[ \t]*#\\+\\("
  19854. (regexp-opt kwds)
  19855. (and extra (concat (and kwds "\\|") extra))
  19856. "\\):[ \t]*\\(.*\\)"))
  19857. ;;; Conveniently switch to Info nodes
  19858. (defun org-info-find-node (&optional nodename)
  19859. "Find Info documentation NODENAME or Org documentation according context.
  19860. Started from `gnus-info-find-node'."
  19861. (interactive)
  19862. (Info-goto-node
  19863. (or nodename
  19864. (let ((default-org-info-node "(org) Top"))
  19865. (cond
  19866. ((eq 'org-agenda-mode major-mode) "(org) Agenda Views")
  19867. ((eq 'org-mode major-mode)
  19868. (let* ((context (org-element-at-point))
  19869. (element-info-nodes ; compare to `org-element-all-elements'.
  19870. `((babel-call . "(org) Evaluating Code Blocks")
  19871. (center-block . "(org) Paragraphs")
  19872. (clock . ,default-org-info-node)
  19873. (comment . "(org) Comment Lines")
  19874. (comment-block . "(org) Comment Lines")
  19875. (diary-sexp . ,default-org-info-node)
  19876. (drawer . "(org) Drawers")
  19877. (dynamic-block . "(org) Dynamic Blocks")
  19878. (example-block . "(org) Literal Examples")
  19879. (export-block . "(org) ASCII/Latin-1/UTF-8 export")
  19880. (fixed-width . ,default-org-info-node)
  19881. (footnote-definition . "(org) Creating Footnotes")
  19882. (headline . "(org) Document Structure")
  19883. (horizontal-rule . "(org) Built-in Table Editor")
  19884. (inlinetask . ,default-org-info-node)
  19885. (item . "(org) Plain Lists")
  19886. (keyword . "(org) Per-file keywords")
  19887. (latex-environment . "(org) LaTeX Export")
  19888. (node-property . "(org) Properties and Columns")
  19889. (paragraph . "(org) Paragraphs")
  19890. (plain-list . "(org) Plain Lists")
  19891. (planning . "(org) Deadlines and Scheduling")
  19892. (property-drawer . "(org) Properties and Columns")
  19893. (quote-block . "(org) Paragraphs")
  19894. (section . ,default-org-info-node)
  19895. (special-block . ,default-org-info-node)
  19896. (src-block . "(org) Working with Source Code")
  19897. (table . "(org) Tables")
  19898. (table-row . "(org) Tables")
  19899. (verse-block . "(org) Paragraphs"))))
  19900. (or (cdr (assoc (car context) element-info-nodes))
  19901. default-org-info-node)))
  19902. (t default-org-info-node))))))
  19903. ;;; Finish up
  19904. (add-hook 'org-mode-hook ;remove overlays when changing major mode
  19905. (lambda () (add-hook 'change-major-mode-hook
  19906. 'org-show-all 'append 'local)))
  19907. (provide 'org)
  19908. (run-hooks 'org-load-hook)
  19909. ;;; org.el ends here