org.el 813 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155
  1. ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
  2. ;; Carstens outline-mode for keeping track of everything.
  3. ;; Copyright (C) 2004-2022 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
  6. ;; Maintainer: Bastien Guerry <bzg@gnu.org>
  7. ;; Keywords: outlines, hypermedia, calendar, wp
  8. ;; URL: 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 Org mode website,
  55. ;; you can read the same text online as HTML. There is also an excellent
  56. ;; reference card made by Philip Rooke. This card can be found in the
  57. ;; 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. (require 'org-fold)
  88. (require 'org-cycle)
  89. (defvaralias 'org-hide-block-startup 'org-cycle-hide-block-startup)
  90. (defvaralias 'org-pre-cycle-hook 'org-cycle-pre-hook)
  91. (defvaralias 'org-tab-first-hook 'org-cycle-tab-first-hook)
  92. (defalias 'org-global-cycle #'org-cycle-global)
  93. (defalias 'org-overview #'org-cycle-overview)
  94. (defalias 'org-content #'org-cycle-content)
  95. (defalias 'org-reveal #'org-fold-reveal)
  96. (defalias 'org-force-cycle-archived #'org-cycle-force-archived)
  97. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  98. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  99. (defvar org-outline-regexp "\\*+ "
  100. "Regexp to match Org headlines.")
  101. (defvar org-outline-regexp-bol "^\\*+ "
  102. "Regexp to match Org headlines.
  103. This is similar to `org-outline-regexp' but additionally makes
  104. sure that we are at the beginning of the line.")
  105. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  106. "Matches a headline, putting stars and text into groups.
  107. Stars are put in group 1 and the trimmed body in group 2.")
  108. (declare-function calendar-check-holidays "holidays" (date))
  109. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  110. (declare-function cdlatex-math-symbol "ext:cdlatex")
  111. (declare-function Info-goto-node "info" (nodename &optional fork strict-case))
  112. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  113. (declare-function org-add-archive-files "org-archive" (files))
  114. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  115. (declare-function org-agenda-todo-yesterday "org-agenda" (&optional arg))
  116. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
  117. (declare-function org-agenda-redo "org-agenda" (&optional all))
  118. (declare-function org-agenda-remove-restriction-lock "org-agenda" (&optional noupdate))
  119. (declare-function org-archive-subtree "org-archive" (&optional find-done))
  120. (declare-function org-archive-subtree-default "org-archive" ())
  121. (declare-function org-archive-to-archive-sibling "org-archive" ())
  122. (declare-function org-attach "org-attach" ())
  123. (declare-function org-attach-dir "org-attach"
  124. (&optional create-if-not-exists-p no-fs-check))
  125. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  126. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  127. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  128. (declare-function org-clock-auto-clockout "org-clock" ())
  129. (declare-function org-clock-cancel "org-clock" ())
  130. (declare-function org-clock-display "org-clock" (&optional arg))
  131. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  132. (declare-function org-clock-goto "org-clock" (&optional select))
  133. (declare-function org-clock-in "org-clock" (&optional select start-time))
  134. (declare-function org-clock-in-last "org-clock" (&optional arg))
  135. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  136. (declare-function org-clock-out-if-current "org-clock" ())
  137. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  138. (declare-function org-clock-report "org-clock" (&optional arg))
  139. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  140. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  141. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  142. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  143. (declare-function org-clock-update-time-maybe "org-clock" ())
  144. (declare-function org-clocktable-shift "org-clock" (dir n))
  145. (declare-function org-columns-quit "org-colview" ())
  146. (declare-function org-columns-insert-dblock "org-colview" ())
  147. (declare-function org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  148. (declare-function org-duration-to-minutes "org-duration" (duration &optional canonical))
  149. (declare-function org-element-at-point "org-element" (&optional pom cached-only))
  150. (declare-function org-element-at-point-no-context "org-element" (&optional pom))
  151. (declare-function org-element-cache-refresh "org-element" (pos))
  152. (declare-function org-element-cache-reset "org-element" (&optional all))
  153. (declare-function org-element-cache-map "org-element" (func &rest keys))
  154. (declare-function org-element-contents "org-element" (element))
  155. (declare-function org-element-context "org-element" (&optional element))
  156. (declare-function org-element-copy "org-element" (datum))
  157. (declare-function org-element-create "org-element" (type &optional props &rest children))
  158. (declare-function org-element-extract-element "org-element" (element))
  159. (declare-function org-element-insert-before "org-element" (element location))
  160. (declare-function org-element-interpret-data "org-element" (data))
  161. (declare-function org-element-keyword-parser "org-element" (limit affiliated))
  162. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  163. (declare-function org-element-link-parser "org-element" ())
  164. (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion with-affiliated))
  165. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  166. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  167. (declare-function org-element-parse-secondary-string "org-element" (string restriction &optional parent))
  168. (declare-function org-element-property "org-element" (property element))
  169. (declare-function org-element-put-property "org-element" (element property value))
  170. (declare-function org-element-restriction "org-element" (element))
  171. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  172. (declare-function org-element-timestamp-parser "org-element" ())
  173. (declare-function org-element-type "org-element" (element))
  174. (declare-function org-element--cache-active-p "org-element" ())
  175. (declare-function org-export-dispatch "ox" (&optional arg))
  176. (declare-function org-export-get-backend "ox" (name))
  177. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  178. (declare-function org-feed-goto-inbox "org-feed" (feed))
  179. (declare-function org-feed-update-all "org-feed" ())
  180. (declare-function org-goto "org-goto" (&optional alternative-interface))
  181. (declare-function org-id-find-id-file "org-id" (id))
  182. (declare-function org-id-get-create "org-id" (&optional force))
  183. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  184. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  185. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  186. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  187. (declare-function org-num-mode "org-num" (&optional arg))
  188. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  189. (declare-function org-persist-load "org-persist" (container &optional associated hash-must-match))
  190. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  191. (declare-function org-timer "org-timer" (&optional restart no-insert))
  192. (declare-function org-timer-item "org-timer" (&optional arg))
  193. (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
  194. (declare-function org-timer-set-timer "org-timer" (&optional opt))
  195. (declare-function org-timer-start "org-timer" (&optional offset))
  196. (declare-function org-timer-stop "org-timer" ())
  197. (declare-function org-toggle-archive-tag "org-archive" (&optional find-done))
  198. (declare-function org-update-radio-target-regexp "ol" ())
  199. (defvar org-agenda-buffer-name)
  200. (defvar org-element-paragraph-separate)
  201. (defvar org-element-cache-map-continue-from)
  202. (defvar org-element--timestamp-regexp)
  203. (defvar org-indent-indentation-per-level)
  204. (defvar org-radio-target-regexp)
  205. (defvar org-target-link-regexp)
  206. (defvar org-target-regexp)
  207. (defvar org-id-overriding-file-name)
  208. ;; load languages based on value of `org-babel-load-languages'
  209. (defvar org-babel-load-languages)
  210. (defvar crm-separator) ; dynamically scoped param
  211. ;;;###autoload
  212. (defun org-babel-do-load-languages (sym value)
  213. "Load the languages defined in `org-babel-load-languages'."
  214. (set-default-toplevel-value sym value)
  215. (dolist (pair org-babel-load-languages)
  216. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  217. (if active
  218. (require (intern (concat "ob-" lang)))
  219. (fmakunbound
  220. (intern (concat "org-babel-execute:" lang)))
  221. (fmakunbound
  222. (intern (concat "org-babel-expand-body:" lang)))))))
  223. ;;;###autoload
  224. (defun org-babel-load-file (file &optional compile)
  225. "Load Emacs Lisp source code blocks in the Org FILE.
  226. This function exports the source code using `org-babel-tangle'
  227. and then loads the resulting file using `load-file'. With
  228. optional prefix argument COMPILE, the tangled Emacs Lisp file is
  229. byte-compiled before it is loaded."
  230. (interactive "fFile to load: \nP")
  231. (let ((tangled-file (concat (file-name-sans-extension file) ".el")))
  232. ;; Tangle only if the Org file is newer than the Elisp file.
  233. (unless (org-file-newer-than-p
  234. tangled-file
  235. (file-attribute-modification-time
  236. (file-attributes (file-truename file))))
  237. ;; Make sure that tangled file modification time is
  238. ;; updated even when `org-babel-tangle-file' does not make changes.
  239. ;; This avoids re-tangling changed FILE where the changes did
  240. ;; not affect the tangled code.
  241. (when (file-exists-p tangled-file)
  242. (set-file-times tangled-file))
  243. (org-babel-tangle-file file
  244. tangled-file
  245. (rx string-start
  246. (or "emacs-lisp" "elisp")
  247. string-end)))
  248. (if compile
  249. (progn
  250. (byte-compile-file tangled-file)
  251. (load-file (byte-compile-dest-file tangled-file))
  252. (message "Compiled and loaded %s" tangled-file))
  253. (load-file tangled-file)
  254. (message "Loaded %s" tangled-file))))
  255. (defcustom org-babel-load-languages '((emacs-lisp . t))
  256. "Languages which can be evaluated in Org buffers.
  257. \\<org-mode-map>
  258. This list can be used to load support for any of the languages
  259. below. Each language will depend on a different set of system
  260. executables and/or Emacs modes.
  261. When a language is \"loaded\", code blocks in that language can
  262. be evaluated with `org-babel-execute-src-block', which is bound
  263. by default to \\[org-ctrl-c-ctrl-c].
  264. The `org-babel-no-eval-on-ctrl-c-ctrl-c' option can be set to
  265. remove code block evaluation from \\[org-ctrl-c-ctrl-c]. By
  266. default, only Emacs Lisp is loaded, since it has no specific
  267. requirement."
  268. :group 'org-babel
  269. :set 'org-babel-do-load-languages
  270. :version "24.1"
  271. :type '(alist :tag "Babel Languages"
  272. :key-type
  273. (choice
  274. (const :tag "Awk" awk)
  275. (const :tag "C" C)
  276. (const :tag "R" R)
  277. (const :tag "Calc" calc)
  278. (const :tag "Clojure" clojure)
  279. (const :tag "CSS" css)
  280. (const :tag "Ditaa" ditaa)
  281. (const :tag "Dot" dot)
  282. (const :tag "Emacs Lisp" emacs-lisp)
  283. (const :tag "Forth" forth)
  284. (const :tag "Fortran" fortran)
  285. (const :tag "Gnuplot" gnuplot)
  286. (const :tag "Haskell" haskell)
  287. (const :tag "Java" java)
  288. (const :tag "Javascript" js)
  289. (const :tag "LaTeX" latex)
  290. (const :tag "Lilypond" lilypond)
  291. (const :tag "Lisp" lisp)
  292. (const :tag "Makefile" makefile)
  293. (const :tag "Maxima" maxima)
  294. (const :tag "Matlab" matlab)
  295. (const :tag "Ocaml" ocaml)
  296. (const :tag "Octave" octave)
  297. (const :tag "Org" org)
  298. (const :tag "Perl" perl)
  299. (const :tag "Pico Lisp" picolisp)
  300. (const :tag "PlantUML" plantuml)
  301. (const :tag "Python" python)
  302. (const :tag "Ruby" ruby)
  303. (const :tag "Sass" sass)
  304. (const :tag "Scala" scala)
  305. (const :tag "Scheme" scheme)
  306. (const :tag "Screen" screen)
  307. (const :tag "Shell Script" shell)
  308. (const :tag "Sql" sql)
  309. (const :tag "Sqlite" sqlite)
  310. (const :tag "Stan" stan))
  311. :value-type (boolean :tag "Activate" :value t)))
  312. ;;;; Customization variables
  313. (defcustom org-clone-delete-id nil
  314. "Remove ID property of clones of a subtree.
  315. When non-nil, clones of a subtree don't inherit the ID property.
  316. Otherwise they inherit the ID property with a new unique
  317. identifier."
  318. :type 'boolean
  319. :version "24.1"
  320. :group 'org-id)
  321. ;;; Version
  322. (org-check-version)
  323. ;;;###autoload
  324. (defun org-version (&optional here full message)
  325. "Show the Org version.
  326. Interactively, or when MESSAGE is non-nil, show it in echo area.
  327. With prefix argument, or when HERE is non-nil, insert it at point.
  328. In non-interactive uses, a reduced version string is output unless
  329. FULL is given."
  330. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  331. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  332. (save-load-suffixes load-suffixes)
  333. (load-suffixes (list ".el"))
  334. (org-install-dir
  335. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  336. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  337. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  338. (let* ((load-suffixes save-load-suffixes)
  339. (release (org-release))
  340. (git-version (org-git-version))
  341. (version (format "Org mode version %s (%s @ %s)"
  342. release
  343. git-version
  344. (if org-install-dir
  345. (if (string= org-dir org-install-dir)
  346. org-install-dir
  347. (concat "mixed installation! "
  348. org-install-dir
  349. " and "
  350. org-dir))
  351. "org-loaddefs.el can not be found!")))
  352. (version1 (if full version release)))
  353. (when here (insert version1))
  354. (when message (message "%s" version1))
  355. version1)))
  356. (defconst org-version (org-version))
  357. ;;; Syntax Constants
  358. ;;;; Comments
  359. (defconst org-comment-regexp
  360. (rx (seq bol (zero-or-more (any "\t ")) "#" (or " " eol)))
  361. "Regular expression for comment lines.")
  362. ;;;; Keyword
  363. (defconst org-keyword-regexp "^[ \t]*#\\+\\(\\S-+?\\):[ \t]*\\(.*\\)$"
  364. "Regular expression for keyword-lines.")
  365. ;;;; Block
  366. (defconst org-block-regexp
  367. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  368. "Regular expression for hiding blocks.")
  369. (defconst org-dblock-start-re
  370. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  371. "Matches the start line of a dynamic block, with parameters.")
  372. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  373. "Matches the end of a dynamic block.")
  374. ;;;; Timestamp
  375. (defconst org-ts--internal-regexp
  376. (rx (seq
  377. (= 4 digit) "-" (= 2 digit) "-" (= 2 digit)
  378. (optional " " (*? nonl))))
  379. "Regular expression matching the innards of a time stamp.")
  380. (defconst org-ts-regexp (format "<\\(%s\\)>" org-ts--internal-regexp)
  381. "Regular expression for fast time stamp matching.")
  382. (defconst org-ts-regexp-inactive
  383. (format "\\[\\(%s\\)\\]" org-ts--internal-regexp)
  384. "Regular expression for fast inactive time stamp matching.")
  385. (defconst org-ts-regexp-both (format "[[<]\\(%s\\)[]>]" org-ts--internal-regexp)
  386. "Regular expression for fast time stamp matching.")
  387. (defconst org-ts-regexp0
  388. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  389. "Regular expression matching time strings for analysis.
  390. This one does not require the space after the date, so it can be used
  391. on a string that terminates immediately after the date.")
  392. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  393. "Regular expression matching time strings for analysis.")
  394. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  395. "Regular expression matching time stamps, with groups.")
  396. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  397. "Regular expression matching time stamps (also [..]), with groups.")
  398. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  399. "Regular expression matching a time stamp range.")
  400. (defconst org-tr-regexp-both
  401. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  402. "Regular expression matching a time stamp range.")
  403. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  404. org-ts-regexp "\\)?")
  405. "Regular expression matching a time stamp or time stamp range.")
  406. (defconst org-tsr-regexp-both
  407. (concat org-ts-regexp-both "\\(--?-?"
  408. org-ts-regexp-both "\\)?")
  409. "Regular expression matching a time stamp or time stamp range.
  410. The time stamps may be either active or inactive.")
  411. (defconst org-repeat-re
  412. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\
  413. \\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  414. "Regular expression for specifying repeated events.
  415. After a match, group 1 contains the repeat expression.")
  416. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  417. "Formats for `format-time-string' which are used for time stamps.")
  418. ;;;; Clock and Planning
  419. (defconst org-clock-string "CLOCK:"
  420. "String used as prefix for timestamps clocking work hours on an item.")
  421. (defvar org-closed-string "CLOSED:"
  422. "String used as the prefix for timestamps logging closing a TODO entry.")
  423. (defvar org-deadline-string "DEADLINE:"
  424. "String to mark deadline entries.
  425. \\<org-mode-map>
  426. A deadline is this string, followed by a time stamp. It must be
  427. a word, terminated by a colon. You can insert a schedule keyword
  428. and a timestamp with `\\[org-deadline]'.")
  429. (defvar org-scheduled-string "SCHEDULED:"
  430. "String to mark scheduled TODO entries.
  431. \\<org-mode-map>
  432. A schedule is this string, followed by a time stamp. It must be
  433. a word, terminated by a colon. You can insert a schedule keyword
  434. and a timestamp with `\\[org-schedule]'.")
  435. (defconst org-ds-keyword-length
  436. (+ 2
  437. (apply #'max
  438. (mapcar #'length
  439. (list org-deadline-string org-scheduled-string
  440. org-clock-string org-closed-string))))
  441. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  442. (defconst org-planning-line-re
  443. (concat "^[ \t]*"
  444. (regexp-opt
  445. (list org-closed-string org-deadline-string org-scheduled-string)
  446. t))
  447. "Matches a line with planning info.
  448. Matched keyword is in group 1.")
  449. (defconst org-clock-line-re
  450. (concat "^[ \t]*" org-clock-string)
  451. "Matches a line with clock info.")
  452. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  453. "Matches the DEADLINE keyword.")
  454. (defconst org-deadline-time-regexp
  455. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  456. "Matches the DEADLINE keyword together with a time stamp.")
  457. (defconst org-deadline-time-hour-regexp
  458. (concat "\\<" org-deadline-string
  459. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
  460. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  461. (defconst org-deadline-line-regexp
  462. (concat "\\<\\(" org-deadline-string "\\).*")
  463. "Matches the DEADLINE keyword and the rest of the line.")
  464. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  465. "Matches the SCHEDULED keyword.")
  466. (defconst org-scheduled-time-regexp
  467. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  468. "Matches the SCHEDULED keyword together with a time stamp.")
  469. (defconst org-scheduled-time-hour-regexp
  470. (concat "\\<" org-scheduled-string
  471. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
  472. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  473. (defconst org-closed-time-regexp
  474. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  475. "Matches the CLOSED keyword together with a time stamp.")
  476. (defconst org-keyword-time-regexp
  477. (concat "\\<"
  478. (regexp-opt
  479. (list org-scheduled-string org-deadline-string org-closed-string
  480. org-clock-string)
  481. t)
  482. " *[[<]\\([^]>]+\\)[]>]")
  483. "Matches any of the 4 keywords, together with the time stamp.")
  484. (defconst org-keyword-time-not-clock-regexp
  485. (concat
  486. "\\<"
  487. (regexp-opt
  488. (list org-scheduled-string org-deadline-string org-closed-string) t)
  489. " *[[<]\\([^]>]+\\)[]>]")
  490. "Matches any of the 3 keywords, together with the time stamp.")
  491. (defconst org-all-time-keywords
  492. (mapcar (lambda (w) (substring w 0 -1))
  493. (list org-scheduled-string org-deadline-string
  494. org-clock-string org-closed-string))
  495. "List of time keywords.")
  496. ;;;; Drawer
  497. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  498. "Matches first or last line of a hidden block.
  499. Group 1 contains drawer's name or \"END\".")
  500. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  501. "Regular expression matching the first line of a property drawer.")
  502. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  503. "Regular expression matching the last line of a property drawer.")
  504. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  505. "Regular expression matching the first line of a clock drawer.")
  506. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  507. "Regular expression matching the last line of a clock drawer.")
  508. (defconst org-logbook-drawer-re
  509. (rx (seq bol (0+ (any "\t ")) ":LOGBOOK:" (0+ (any "\t ")) "\n"
  510. (*? (0+ nonl) "\n")
  511. (0+ (any "\t ")) ":END:" (0+ (any "\t ")) eol))
  512. "Matches an entire LOGBOOK drawer.")
  513. (defconst org-property-drawer-re
  514. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  515. "\\(?:[ \t]*:\\S-+:\\(?:[ \t].*\\)?[ \t]*\n\\)*?"
  516. "[ \t]*:END:[ \t]*$")
  517. "Matches an entire property drawer.")
  518. (defconst org-clock-drawer-re
  519. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  520. org-clock-drawer-end-re "\\)\n?")
  521. "Matches an entire clock drawer.")
  522. ;;;; Headline
  523. (defconst org-heading-keyword-regexp-format
  524. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  525. "Printf format for a regexp matching a headline with some keyword.
  526. This regexp will match the headline of any node which has the
  527. exact keyword that is put into the format. The keyword isn't in
  528. any group by default, but the stars and the body are.")
  529. (defconst org-heading-keyword-maybe-regexp-format
  530. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  531. "Printf format for a regexp matching a headline, possibly with some keyword.
  532. This regexp can match any headline with the specified keyword, or
  533. without a keyword. The keyword isn't in any group by default,
  534. but the stars and the body are.")
  535. (defconst org-archive-tag "ARCHIVE"
  536. "The tag that marks a subtree as archived.
  537. An archived subtree does not open during visibility cycling, and does
  538. not contribute to the agenda listings.")
  539. (defconst org-tag-re "[[:alnum:]_@#%]+"
  540. "Regexp matching a single tag.")
  541. (defconst org-tag-group-re "[ \t]+\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  542. "Regexp matching the tag group at the end of a line, with leading spaces.
  543. Tags are stored in match group 1. Match group 2 stores the tags
  544. without the enclosing colons.")
  545. (defconst org-tag-line-re
  546. "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  547. "Regexp matching tags in a headline.
  548. Tags are stored in match group 1. Match group 2 stores the tags
  549. without the enclosing colons.")
  550. (eval-and-compile
  551. (defconst org-comment-string "COMMENT"
  552. "Entries starting with this keyword will never be exported.
  553. \\<org-mode-map>
  554. An entry can be toggled between COMMENT and normal with
  555. `\\[org-toggle-comment]'."))
  556. ;;;; LaTeX Environments and Fragments
  557. (defconst org-latex-regexps
  558. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  559. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  560. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  561. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  562. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  563. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  564. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  565. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  566. "Regular expressions for matching embedded LaTeX.")
  567. ;;;; Node Property
  568. (defconst org-effort-property "Effort"
  569. "The property that is being used to keep track of effort estimates.
  570. Effort estimates given in this property need to be in the format
  571. defined in org-duration.el.")
  572. ;;; The custom variables
  573. (defgroup org nil
  574. "Outline-based notes management and organizer."
  575. :tag "Org"
  576. :group 'outlines
  577. :group 'calendar)
  578. (defcustom org-mode-hook nil
  579. "Mode hook for Org mode, run after the mode was turned on."
  580. :group 'org
  581. :type 'hook)
  582. (defcustom org-load-hook nil
  583. "Hook that is run after org.el has been loaded."
  584. :group 'org
  585. :type 'hook)
  586. (make-obsolete-variable
  587. 'org-load-hook
  588. "use `with-eval-after-load' instead." "9.5")
  589. (defcustom org-log-buffer-setup-hook nil
  590. "Hook that is run after an Org log buffer is created."
  591. :group 'org
  592. :version "24.1"
  593. :type 'hook)
  594. (defvar org-modules) ; defined below
  595. (defvar org-modules-loaded nil
  596. "Have the modules been loaded already?")
  597. ;;;###autoload
  598. (defun org-load-modules-maybe (&optional force)
  599. "Load all extensions listed in `org-modules'."
  600. (when (or force (not org-modules-loaded))
  601. (dolist (ext org-modules)
  602. (condition-case nil (require ext)
  603. (error (message "Problems while trying to load feature `%s'" ext))))
  604. (setq org-modules-loaded t)))
  605. (defun org-set-modules (var value)
  606. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  607. (set-default-toplevel-value var value)
  608. (when (featurep 'org)
  609. (org-load-modules-maybe 'force)
  610. (org-element-cache-reset 'all)))
  611. (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)
  612. "Modules that should always be loaded together with org.el.
  613. If a description starts with <C>, the file is not part of Emacs and Org mode,
  614. so loading it will require that you have properly installed org-contrib
  615. package from NonGNU Emacs Lisp Package Archive
  616. https://elpa.nongnu.org/nongnu/org-contrib.html
  617. You can also use this system to load external packages (i.e. neither Org
  618. core modules, nor org-contrib modules). Just add symbols
  619. to the end of the list. If the package is called org-xyz.el, then you need
  620. to add the symbol `xyz', and the package must have a call to:
  621. (provide \\='org-xyz)
  622. For export specific modules, see also `org-export-backends'."
  623. :group 'org
  624. :set 'org-set-modules
  625. :package-version '(Org . "9.5")
  626. :type
  627. '(set :greedy t
  628. (const :tag " bbdb: Links to BBDB entries" ol-bbdb)
  629. (const :tag " bibtex: Links to BibTeX entries" ol-bibtex)
  630. (const :tag " crypt: Encryption of subtrees" org-crypt)
  631. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  632. (const :tag " docview: Links to Docview buffers" ol-docview)
  633. (const :tag " doi: Links to DOI references" ol-doi)
  634. (const :tag " eww: Store link to URL of Eww" ol-eww)
  635. (const :tag " gnus: Links to GNUS folders/messages" ol-gnus)
  636. (const :tag " habit: Track your consistency with habits" org-habit)
  637. (const :tag " id: Global IDs for identifying entries" org-id)
  638. (const :tag " info: Links to Info nodes" ol-info)
  639. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  640. (const :tag " irc: Links to IRC/ERC chat sessions" ol-irc)
  641. (const :tag " mhe: Links to MHE folders/messages" ol-mhe)
  642. (const :tag " mouse: Additional mouse support" org-mouse)
  643. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  644. (const :tag " rmail: Links to RMAIL folders/messages" ol-rmail)
  645. (const :tag " tempo: Fast completion for structures" org-tempo)
  646. (const :tag " w3m: Special cut/paste from w3m to Org mode." ol-w3m)
  647. (const :tag " eshell: Links to working directories in Eshell" ol-eshell)
  648. (const :tag "C annotate-file: Annotate a file with Org syntax" org-annotate-file)
  649. (const :tag "C bookmark: Links to bookmarks" ol-bookmark)
  650. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  651. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  652. (const :tag "C collector: Collect properties into tables" org-collector)
  653. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  654. (const :tag "C elisp-symbol: Links to emacs-lisp symbols" ol-elisp-symbol)
  655. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  656. (const :tag "C eval: Include command output as text" org-eval)
  657. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  658. (const :tag "C git-link: Links to specific file version" ol-git-link)
  659. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  660. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  661. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  662. (const :tag "C mac-iCal: Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  663. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  664. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  665. (const :tag "C man: Links to man pages in Org mode" ol-man)
  666. (const :tag "C mew: Links to Mew folders/messages" ol-mew)
  667. (const :tag "C notify: Notifications for Org mode" org-notify)
  668. (const :tag "C notmuch: Provide Org links to notmuch searches or messages" ol-notmuch)
  669. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  670. (const :tag "C registry: A registry for Org links" org-registry)
  671. (const :tag "C screen: Visit screen sessions through links" org-screen)
  672. (const :tag "C screenshot: Take and manage screenshots in Org files" org-screenshot)
  673. (const :tag "C secretary: Team management with Org" org-secretary)
  674. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  675. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  676. (const :tag "C track: Keep up with Org mode development" org-track)
  677. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  678. (const :tag "C vm: Links to VM folders/messages" ol-vm)
  679. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  680. (const :tag "C wl: Links to Wanderlust folders/messages" ol-wl)
  681. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  682. (defvar org-export-registered-backends) ; From ox.el.
  683. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  684. (declare-function org-export-backend-name "ox" (backend) t)
  685. (defcustom org-export-backends '(ascii html icalendar latex odt)
  686. "List of export back-ends that should be always available.
  687. If a description starts with <C>, the file is not part of Emacs and Org mode,
  688. so loading it will require that you have properly installed org-contrib
  689. package from NonGNU Emacs Lisp Package Archive
  690. https://elpa.nongnu.org/nongnu/org-contrib.html
  691. Unlike to `org-modules', libraries in this list will not be
  692. loaded along with Org, but only once the export framework is
  693. needed.
  694. This variable needs to be set before org.el is loaded. If you
  695. need to make a change while Emacs is running, use the customize
  696. interface or run the following code, where VAL stands for the new
  697. value of the variable, after updating it:
  698. (progn
  699. (setq org-export-registered-backends
  700. (cl-remove-if-not
  701. (lambda (backend)
  702. (let ((name (org-export-backend-name backend)))
  703. (or (memq name val)
  704. (catch \\='parentp
  705. (dolist (b val)
  706. (and (org-export-derived-backend-p b name)
  707. (throw \\='parentp t)))))))
  708. org-export-registered-backends))
  709. (let ((new-list (mapcar #\\='org-export-backend-name
  710. org-export-registered-backends)))
  711. (dolist (backend val)
  712. (cond
  713. ((not (load (format \"ox-%s\" backend) t t))
  714. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  715. backend))
  716. ((not (memq backend new-list)) (push backend new-list))))
  717. (set-default \\='org-export-backends new-list)))
  718. Adding a back-end to this list will also pull the back-end it
  719. depends on, if any."
  720. :group 'org
  721. :group 'org-export
  722. :version "26.1"
  723. :package-version '(Org . "9.0")
  724. :initialize 'custom-initialize-set
  725. :set (lambda (var val)
  726. (if (not (featurep 'ox)) (set-default-toplevel-value var val)
  727. ;; Any back-end not required anymore (not present in VAL and not
  728. ;; a parent of any back-end in the new value) is removed from the
  729. ;; list of registered back-ends.
  730. (setq org-export-registered-backends
  731. (cl-remove-if-not
  732. (lambda (backend)
  733. (let ((name (org-export-backend-name backend)))
  734. (or (memq name val)
  735. (catch 'parentp
  736. (dolist (b val)
  737. (and (org-export-derived-backend-p b name)
  738. (throw 'parentp t)))))))
  739. org-export-registered-backends))
  740. ;; Now build NEW-LIST of both new back-ends and required
  741. ;; parents.
  742. (let ((new-list (mapcar #'org-export-backend-name
  743. org-export-registered-backends)))
  744. (dolist (backend val)
  745. (cond
  746. ((not (load (format "ox-%s" backend) t t))
  747. (message "Problems while trying to load export back-end `%s'"
  748. backend))
  749. ((not (memq backend new-list)) (push backend new-list))))
  750. ;; Set VAR to that list with fixed dependencies.
  751. (set-default-toplevel-value var new-list))))
  752. :type '(set :greedy t
  753. (const :tag " ascii Export buffer to ASCII format" ascii)
  754. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  755. (const :tag " html Export buffer to HTML format" html)
  756. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  757. (const :tag " latex Export buffer to LaTeX format" latex)
  758. (const :tag " man Export buffer to MAN format" man)
  759. (const :tag " md Export buffer to Markdown format" md)
  760. (const :tag " odt Export buffer to ODT format" odt)
  761. (const :tag " org Export buffer to Org format" org)
  762. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  763. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  764. (const :tag "C deck Export buffer to deck.js presentations" deck)
  765. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  766. (const :tag "C groff Export buffer to Groff format" groff)
  767. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  768. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  769. (const :tag "C s5 Export buffer to s5 presentations" s5)
  770. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  771. (eval-after-load 'ox
  772. '(dolist (backend org-export-backends)
  773. (condition-case nil (require (intern (format "ox-%s" backend)))
  774. (error (message "Problems while trying to load export back-end `%s'"
  775. backend)))))
  776. (defcustom org-support-shift-select nil
  777. "Non-nil means make shift-cursor commands select text when possible.
  778. \\<org-mode-map>
  779. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  780. start selecting a region, or enlarge regions started in this way.
  781. In Org mode, in special contexts, these same keys are used for
  782. other purposes, important enough to compete with shift selection.
  783. Org tries to balance these needs by supporting `shift-select-mode'
  784. outside these special contexts, under control of this variable.
  785. The default of this variable is nil, to avoid confusing behavior. Shifted
  786. cursor keys will then execute Org commands in the following contexts:
  787. - on a headline, changing TODO state (left/right) and priority (up/down)
  788. - on a time stamp, changing the time
  789. - in a plain list item, changing the bullet type
  790. - in a property definition line, switching between allowed values
  791. - in the BEGIN line of a clock table (changing the time block).
  792. - in a table, moving the cell in the specified direction.
  793. Outside these contexts, the commands will throw an error.
  794. When this variable is t and the cursor is not in a special
  795. context, Org mode will support shift-selection for making and
  796. enlarging regions. To make this more effective, the bullet
  797. cycling will no longer happen anywhere in an item line, but only
  798. if the cursor is exactly on the bullet.
  799. If you set this variable to the symbol `always', then the keys
  800. will not be special in headlines, property lines, item lines, and
  801. table cells, to make shift selection work there as well. If this is
  802. what you want, you can use the following alternative commands:
  803. `\\[org-todo]' and `\\[org-priority]' \
  804. to change TODO state and priority,
  805. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  806. can be used to switch TODO sets,
  807. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  808. and properties can be edited by hand or in column view.
  809. However, when the cursor is on a timestamp, shift-cursor commands
  810. will still edit the time stamp - this is just too good to give up."
  811. :group 'org
  812. :type '(choice
  813. (const :tag "Never" nil)
  814. (const :tag "When outside special context" t)
  815. (const :tag "Everywhere except timestamps" always)))
  816. (defcustom org-loop-over-headlines-in-active-region t
  817. "Shall some commands act upon headlines in the active region?
  818. When set to t, some commands will be performed in all headlines
  819. within the active region.
  820. When set to `start-level', some commands will be performed in all
  821. headlines within the active region, provided that these headlines
  822. are of the same level than the first one.
  823. When set to a string, those commands will be performed on the
  824. matching headlines within the active region. Such string must be
  825. a tags/property/todo match as it is used in the agenda tags view.
  826. The list of commands is: `org-schedule', `org-deadline',
  827. `org-todo', `org-set-tags-command', `org-archive-subtree',
  828. `org-archive-set-tag', `org-toggle-archive-tag' and
  829. `org-archive-to-archive-sibling'. The archiving commands skip
  830. already archived entries.
  831. See `org-agenda-loop-over-headlines-in-active-region' for the
  832. equivalent option for agenda views."
  833. :type '(choice (const :tag "Don't loop" nil)
  834. (const :tag "All headlines in active region" t)
  835. (const :tag "In active region, headlines at the same level than the first one" start-level)
  836. (string :tag "Tags/Property/Todo matcher"))
  837. :package-version '(Org . "9.4")
  838. :group 'org-todo
  839. :group 'org-archive)
  840. (defcustom org-startup-folded 'showeverything
  841. "Non-nil means entering Org mode will switch to OVERVIEW.
  842. This can also be configured on a per-file basis by adding one of
  843. the following lines anywhere in the buffer:
  844. #+STARTUP: fold (or `overview', this is equivalent)
  845. #+STARTUP: nofold (or `showall', this is equivalent)
  846. #+STARTUP: content
  847. #+STARTUP: show<n>levels (<n> = 2..5)
  848. #+STARTUP: showeverything
  849. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  850. to ignore this option when Org opens agenda files for the first
  851. time."
  852. :group 'org-startup
  853. :package-version '(Org . "9.4")
  854. :type '(choice
  855. (const :tag "nofold: show all" nil)
  856. (const :tag "fold: overview" t)
  857. (const :tag "fold: show two levels" show2levels)
  858. (const :tag "fold: show three levels" show3levels)
  859. (const :tag "fold: show four levels" show4evels)
  860. (const :tag "fold: show five levels" show5levels)
  861. (const :tag "content: all headlines" content)
  862. (const :tag "show everything, even drawers" showeverything)))
  863. (defcustom org-startup-truncated t
  864. "Non-nil means entering Org mode will set `truncate-lines'.
  865. This is useful since some lines containing links can be very long and
  866. uninteresting. Also tables look terrible when wrapped.
  867. The variable `org-startup-truncated' allows to configure
  868. truncation for Org mode different to the other modes that use the
  869. variable `truncate-lines' and as a shortcut instead of putting
  870. the variable `truncate-lines' into the `org-mode-hook'. If one
  871. wants to configure truncation for Org mode not statically but
  872. dynamically e.g. in a hook like `ediff-prepare-buffer-hook' then
  873. the variable `truncate-lines' has to be used because in such a
  874. case it is too late to set the variable `org-startup-truncated'."
  875. :group 'org-startup
  876. :type 'boolean)
  877. (defcustom org-startup-indented nil
  878. "Non-nil means turn on `org-indent-mode' on startup.
  879. This can also be configured on a per-file basis by adding one of
  880. the following lines anywhere in the buffer:
  881. #+STARTUP: indent
  882. #+STARTUP: noindent"
  883. :group 'org-structure
  884. :type '(choice
  885. (const :tag "Not" nil)
  886. (const :tag "Globally (slow on startup in large files)" t)))
  887. (defcustom org-startup-numerated nil
  888. "Non-nil means turn on `org-num-mode' on startup.
  889. This can also be configured on a per-file basis by adding one of
  890. the following lines anywhere in the buffer:
  891. #+STARTUP: num
  892. #+STARTUP: nonum"
  893. :group 'org-structure
  894. :package-version '(Org . "9.4")
  895. :type '(choice
  896. (const :tag "Not" nil)
  897. (const :tag "Globally" t)))
  898. (defcustom org-use-sub-superscripts t
  899. "Non-nil means interpret \"_\" and \"^\" for display.
  900. If you want to control how Org exports those characters, see
  901. `org-export-with-sub-superscripts'.
  902. When this option is turned on, you can use TeX-like syntax for
  903. sub- and superscripts within the buffer. Several characters after
  904. \"_\" or \"^\" will be considered as a single item - so grouping
  905. with {} is normally not needed. For example, the following things
  906. will be parsed as single sub- or superscripts:
  907. 10^24 or 10^tau several digits will be considered 1 item.
  908. 10^-12 or 10^-tau a leading sign with digits or a word
  909. x^2-y^3 will be read as x^2 - y^3, because items are
  910. terminated by almost any nonword/nondigit char.
  911. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  912. Still, ambiguity is possible. So when in doubt, use {} to enclose
  913. the sub/superscript. If you set this variable to the symbol `{}',
  914. the braces are *required* in order to trigger interpretations as
  915. sub/superscript. This can be helpful in documents that need \"_\"
  916. frequently in plain text."
  917. :group 'org-startup
  918. :version "24.4"
  919. :package-version '(Org . "8.0")
  920. :type '(choice
  921. (const :tag "Always interpret" t)
  922. (const :tag "Only with braces" {})
  923. (const :tag "Never interpret" nil)))
  924. (defcustom org-startup-with-beamer-mode nil
  925. "Non-nil means turn on `org-beamer-mode' on startup.
  926. This can also be configured on a per-file basis by adding one of
  927. the following lines anywhere in the buffer:
  928. #+STARTUP: beamer"
  929. :group 'org-startup
  930. :version "24.1"
  931. :type 'boolean)
  932. (defcustom org-startup-align-all-tables nil
  933. "Non-nil means align all tables when visiting a file.
  934. This can also be configured on a per-file basis by adding one of
  935. the following lines anywhere in the buffer:
  936. #+STARTUP: align
  937. #+STARTUP: noalign"
  938. :group 'org-startup
  939. :type 'boolean)
  940. (defcustom org-startup-shrink-all-tables nil
  941. "Non-nil means shrink all table columns with a width cookie.
  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: shrink"
  945. :group 'org-startup
  946. :type 'boolean
  947. :version "27.1"
  948. :package-version '(Org . "9.2")
  949. :safe #'booleanp)
  950. (defcustom org-startup-with-inline-images nil
  951. "Non-nil means show inline images when loading a new Org file.
  952. This can also be configured on a per-file basis by adding one of
  953. the following lines anywhere in the buffer:
  954. #+STARTUP: inlineimages
  955. #+STARTUP: noinlineimages"
  956. :group 'org-startup
  957. :version "24.1"
  958. :type 'boolean)
  959. (defcustom org-startup-with-latex-preview nil
  960. "Non-nil means preview LaTeX fragments when loading a new Org file.
  961. This can also be configured on a per-file basis by adding one of
  962. the following lines anywhere in the buffer:
  963. #+STARTUP: latexpreview
  964. #+STARTUP: nolatexpreview"
  965. :group 'org-startup
  966. :version "24.4"
  967. :package-version '(Org . "8.0")
  968. :type 'boolean)
  969. (defcustom org-insert-mode-line-in-empty-file nil
  970. "Non-nil means insert the first line setting Org mode in empty files.
  971. When the function `org-mode' is called interactively in an empty file, this
  972. normally means that the file name does not automatically trigger Org mode.
  973. To ensure that the file will always be in Org mode in the future, a
  974. line enforcing Org mode will be inserted into the buffer, if this option
  975. has been set."
  976. :group 'org-startup
  977. :type 'boolean)
  978. (defcustom org-ellipsis nil
  979. "The ellipsis to use in the Org mode outline.
  980. When nil, just use the standard three dots. When a non-empty string,
  981. use that string instead.
  982. The change affects only Org mode (which will then use its own display table).
  983. Changing this requires executing `\\[org-mode]' in a buffer to become
  984. effective. It cannot be set as a local variable."
  985. :group 'org-startup
  986. :type '(choice (const :tag "Default" nil)
  987. (string :tag "String" :value "...#")))
  988. (defvar org-display-table nil
  989. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  990. (defcustom org-directory "~/org"
  991. "Directory with Org files.
  992. This is just a default location to look for Org files. There is no need
  993. at all to put your files into this directory. It is used in the
  994. following situations:
  995. 1. When a capture template specifies a target file that is not an
  996. absolute path. The path will then be interpreted relative to
  997. `org-directory'
  998. 2. When the value of variable `org-agenda-files' is a single file, any
  999. relative paths in this file will be taken as relative to
  1000. `org-directory'."
  1001. :group 'org-refile
  1002. :group 'org-capture
  1003. :type 'directory)
  1004. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  1005. "Default target for storing notes.
  1006. Used as a fall back file for org-capture.el, for templates that
  1007. do not specify a target file."
  1008. :group 'org-refile
  1009. :group 'org-capture
  1010. :type 'file)
  1011. (defcustom org-reverse-note-order nil
  1012. "Non-nil means store new notes at the beginning of a file or entry.
  1013. When nil, new notes will be filed to the end of a file or entry.
  1014. This can also be a list with cons cells of regular expressions that
  1015. are matched against file names, and values."
  1016. :group 'org-capture
  1017. :group 'org-refile
  1018. :type '(choice
  1019. (const :tag "Reverse always" t)
  1020. (const :tag "Reverse never" nil)
  1021. (repeat :tag "By file name regexp"
  1022. (cons regexp boolean))))
  1023. (defgroup org-keywords nil
  1024. "Keywords in Org mode."
  1025. :tag "Org Keywords"
  1026. :group 'org)
  1027. (defcustom org-closed-keep-when-no-todo nil
  1028. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  1029. :group 'org-todo
  1030. :group 'org-keywords
  1031. :version "24.4"
  1032. :package-version '(Org . "8.0")
  1033. :type 'boolean)
  1034. (defgroup org-structure nil
  1035. "Options concerning the general structure of Org files."
  1036. :tag "Org Structure"
  1037. :group 'org)
  1038. (defcustom org-indirect-buffer-display 'other-window
  1039. "How should indirect tree buffers be displayed?
  1040. This applies to indirect buffers created with the commands
  1041. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1042. Valid values are:
  1043. current-window Display in the current window
  1044. other-window Just display in another window.
  1045. dedicated-frame Create one new frame, and re-use it each time.
  1046. new-frame Make a new frame each time. Note that in this case
  1047. previously-made indirect buffers are kept, and you need to
  1048. kill these buffers yourself."
  1049. :group 'org-structure
  1050. :group 'org-agenda-windows
  1051. :type '(choice
  1052. (const :tag "In current window" current-window)
  1053. (const :tag "In current frame, other window" other-window)
  1054. (const :tag "Each time a new frame" new-frame)
  1055. (const :tag "One dedicated frame" dedicated-frame)))
  1056. (defconst org-file-apps-gnu
  1057. '((remote . emacs)
  1058. (system . mailcap)
  1059. (t . mailcap))
  1060. "Default file applications on a UNIX or GNU/Linux system.
  1061. See `org-file-apps'.")
  1062. (defconst org-file-apps-macos
  1063. '((remote . emacs)
  1064. (system . "open %s")
  1065. ("ps.gz" . "gv %s")
  1066. ("eps.gz" . "gv %s")
  1067. ("dvi" . "xdvi %s")
  1068. ("fig" . "xfig %s")
  1069. (t . "open %s"))
  1070. "Default file applications on a macOS system.
  1071. The system \"open\" is known as a default, but we use X11 applications
  1072. for some files for which the OS does not have a good default.
  1073. See `org-file-apps'.")
  1074. (defconst org-file-apps-windowsnt
  1075. (list '(remote . emacs)
  1076. (cons 'system (lambda (file _path)
  1077. (with-no-warnings (w32-shell-execute "open" file))))
  1078. (cons t (lambda (file _path)
  1079. (with-no-warnings (w32-shell-execute "open" file)))))
  1080. "Default file applications on a Windows NT system.
  1081. The system \"open\" is used for most files.
  1082. See `org-file-apps'.")
  1083. (defcustom org-file-apps
  1084. '((auto-mode . emacs)
  1085. (directory . emacs)
  1086. ("\\.mm\\'" . default)
  1087. ("\\.x?html?\\'" . default)
  1088. ("\\.pdf\\'" . default))
  1089. "Applications for opening `file:path' items in a document.
  1090. \\<org-mode-map>
  1091. Org mode uses system defaults for different file types, but you
  1092. can use this variable to set the application for a given file
  1093. extension. The entries in this list are cons cells where the car
  1094. identifies files and the cdr the corresponding command.
  1095. Possible values for the file identifier are:
  1096. \"string\" A string as a file identifier can be interpreted in different
  1097. ways, depending on its contents:
  1098. - Alphanumeric characters only:
  1099. Match links with this file extension.
  1100. Example: (\"pdf\" . \"evince %s\")
  1101. to open PDFs with evince.
  1102. - Regular expression: Match links where the
  1103. filename matches the regexp. If you want to
  1104. use groups here, use shy groups.
  1105. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1106. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1107. to open *.html and *.xhtml with firefox.
  1108. - Regular expression which contains (non-shy) groups:
  1109. Match links where the whole link, including \"::\", and
  1110. anything after that, matches the regexp.
  1111. In a custom command string, %1, %2, etc. are replaced with
  1112. the parts of the link that were matched by the groups.
  1113. For backwards compatibility, if a command string is given
  1114. that does not use any of the group matches, this case is
  1115. handled identically to the second one (i.e. match against
  1116. file name only).
  1117. In a custom function, you can access the group matches with
  1118. (match-string n link).
  1119. Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
  1120. \"evince -p %1 %s\")
  1121. to open [[file:document.pdf::5]] with evince at page 5.
  1122. `directory' Matches a directory
  1123. `remote' Matches a remote file, accessible through tramp or efs.
  1124. Remote files most likely should be visited through Emacs
  1125. because external applications cannot handle such paths.
  1126. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1127. so all files Emacs knows how to handle. Using this with
  1128. command `emacs' will open most files in Emacs. Beware that this
  1129. will also open html files inside Emacs, unless you add
  1130. (\"html\" . default) to the list as well.
  1131. `system' The system command to open files, like `open' on Windows
  1132. and macOS, and mailcap under GNU/Linux. This is the command
  1133. that will be selected if you call `org-open-at-point' with a
  1134. double prefix argument (`\\[universal-argument] \
  1135. \\[universal-argument] \\[org-open-at-point]').
  1136. t Default for files not matched by any of the other options.
  1137. Possible values for the command are:
  1138. `emacs' The file will be visited by the current Emacs process.
  1139. `default' Use the default application for this file type, which is the
  1140. association for t in the list, most likely in the system-specific
  1141. part. This can be used to overrule an unwanted setting in the
  1142. system-specific variable.
  1143. `system' Use the system command for opening files, like \"open\".
  1144. This command is specified by the entry whose car is `system'.
  1145. Most likely, the system-specific version of this variable
  1146. does define this command, but you can overrule/replace it
  1147. here.
  1148. `mailcap' Use command specified in the mailcaps.
  1149. string A command to be executed by a shell; %s will be replaced
  1150. by the path to the file.
  1151. function A Lisp function, which will be called with two arguments:
  1152. the file path and the original link string, without the
  1153. \"file:\" prefix.
  1154. For more examples, see the system specific constants
  1155. `org-file-apps-macos'
  1156. `org-file-apps-windowsnt'
  1157. `org-file-apps-gnu'."
  1158. :group 'org
  1159. :package-version '(Org . "9.4")
  1160. :type '(repeat
  1161. (cons (choice :value ""
  1162. (string :tag "Extension")
  1163. (const :tag "System command to open files" system)
  1164. (const :tag "Default for unrecognized files" t)
  1165. (const :tag "Remote file" remote)
  1166. (const :tag "Links to a directory" directory)
  1167. (const :tag "Any files that have Emacs modes"
  1168. auto-mode))
  1169. (choice :value ""
  1170. (const :tag "Visit with Emacs" emacs)
  1171. (const :tag "Use default" default)
  1172. (const :tag "Use the system command" system)
  1173. (string :tag "Command")
  1174. (function :tag "Function")))))
  1175. (defcustom org-resource-download-policy 'prompt
  1176. "The policy applied to requests to obtain remote resources.
  1177. This affects keywords like #+setupfile and #+incude on export,
  1178. `org-persist-write:url',and `org-attach-url' in non-interactive
  1179. Emacs sessions.
  1180. This recognises four possible values:
  1181. - t, remote resources should always be downloaded.
  1182. - prompt, you will be prompted to download resources nt considered safe.
  1183. - safe, only resources considered safe will be downloaded.
  1184. - nil, never download remote resources.
  1185. A resource is considered safe if it matches one of the patterns
  1186. in `org-safe-remote-resources'."
  1187. :group 'org
  1188. :type '(choice (const :tag "Always download remote resources" t)
  1189. (const :tag "Prompt before downloading an unsafe resource" prompt)
  1190. (const :tag "Only download resources considered safe" safe)
  1191. (const :tag "Never download any resources" nil)))
  1192. (defcustom org-safe-remote-resources nil
  1193. "A list of regexp patterns matching safe URIs.
  1194. URI regexps are applied to both URLs and Org files requesting
  1195. remote resources."
  1196. :group 'org
  1197. :type '(list regexp))
  1198. (defcustom org-open-non-existing-files nil
  1199. "Non-nil means `org-open-file' opens non-existing files.
  1200. When nil, an error is thrown.
  1201. This variable applies only to external applications because they
  1202. might choke on non-existing files. If the link is to a file that
  1203. will be opened in Emacs, the variable is ignored."
  1204. :group 'org
  1205. :type 'boolean
  1206. :safe #'booleanp)
  1207. (defcustom org-open-directory-means-index-dot-org nil
  1208. "When non-nil a link to a directory really means to \"index.org\".
  1209. When nil, following a directory link runs Dired or opens
  1210. a finder/explorer window on that directory."
  1211. :group 'org
  1212. :type 'boolean
  1213. :safe #'booleanp)
  1214. (defcustom org-bookmark-names-plist
  1215. '(:last-capture "org-capture-last-stored"
  1216. :last-refile "org-refile-last-stored"
  1217. :last-capture-marker "org-capture-last-stored-marker")
  1218. "Names for bookmarks automatically set by some Org commands.
  1219. This can provide strings as names for a number of bookmarks Org sets
  1220. automatically. The following keys are currently implemented:
  1221. :last-capture
  1222. :last-capture-marker
  1223. :last-refile
  1224. When a key does not show up in the property list, the corresponding bookmark
  1225. is not set."
  1226. :group 'org-structure
  1227. :type 'plist)
  1228. (defgroup org-edit-structure nil
  1229. "Options concerning structure editing in Org mode."
  1230. :tag "Org Edit Structure"
  1231. :group 'org-structure)
  1232. (defcustom org-odd-levels-only nil
  1233. "Non-nil means skip even levels and only use odd levels for the outline.
  1234. This has the effect that two stars are being added/taken away in
  1235. promotion/demotion commands. It also influences how levels are
  1236. handled by the exporters.
  1237. Changing it requires restart of `font-lock-mode' to become effective
  1238. for fontification also in regions already fontified.
  1239. You may also set this on a per-file basis by adding one of the following
  1240. lines to the buffer:
  1241. #+STARTUP: odd
  1242. #+STARTUP: oddeven"
  1243. :group 'org-edit-structure
  1244. :group 'org-appearance
  1245. :type 'boolean)
  1246. (defcustom org-adapt-indentation nil
  1247. "Non-nil means adapt indentation to outline node level.
  1248. When set to t, Org assumes that you write outlines by indenting
  1249. text in each node to align with the headline, after the stars.
  1250. When this variable is set to `headline-data', Org only adapts the
  1251. indentation of the data lines right below the headline, such as
  1252. planning/clock lines and property/logbook drawers.
  1253. The following issues are influenced by this variable:
  1254. - The indentation is increased by one space in a demotion
  1255. command, and decreased by one in a promotion command. However,
  1256. in the latter case, if shifting some line in the entry body
  1257. would alter document structure (e.g., insert a new headline),
  1258. indentation is not changed at all.
  1259. - Property drawers and planning information is inserted indented
  1260. when this variable is set. When nil, they will not be indented.
  1261. - TAB indents a line relative to current level. The lines below
  1262. a headline will be indented when this variable is set to t.
  1263. Note that this is all about true indentation, by adding and
  1264. removing space characters. See also \"org-indent.el\" which does
  1265. level-dependent indentation in a virtual way, i.e. at display
  1266. time in Emacs."
  1267. :group 'org-edit-structure
  1268. :type '(choice
  1269. (const :tag "Adapt indentation for all lines" t)
  1270. (const :tag "Adapt indentation for headline data lines"
  1271. headline-data)
  1272. (const :tag "Do not adapt indentation at all" nil))
  1273. :safe (lambda (x) (memq x '(t nil headline-data))))
  1274. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1275. (defcustom org-special-ctrl-a/e nil
  1276. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1277. When t, `C-a' will bring back the cursor to the beginning of the
  1278. headline text, i.e. after the stars and after a possible TODO
  1279. keyword. In an item, this will be the position after bullet and
  1280. check-box, if any. When the cursor is already at that position,
  1281. another `C-a' will bring it to the beginning of the line.
  1282. `C-e' will jump to the end of the headline, ignoring the presence
  1283. of tags in the headline. A second `C-e' will then jump to the
  1284. true end of the line, after any tags. This also means that, when
  1285. this variable is non-nil, `C-e' also will never jump beyond the
  1286. end of the heading of a folded section, i.e. not after the
  1287. ellipses.
  1288. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1289. normally, going to the true line boundary first. Only a directly
  1290. following, identical keypress will bring the cursor to the
  1291. special positions.
  1292. This may also be a cons cell where the behavior for `C-a' and
  1293. `C-e' is set separately."
  1294. :group 'org-edit-structure
  1295. :type '(choice
  1296. (const :tag "off" nil)
  1297. (const :tag "on: after stars/bullet and before tags first" t)
  1298. (const :tag "reversed: true line boundary first" reversed)
  1299. (cons :tag "Set C-a and C-e separately"
  1300. (choice :tag "Special C-a"
  1301. (const :tag "off" nil)
  1302. (const :tag "on: after stars/bullet first" t)
  1303. (const :tag "reversed: before stars/bullet first" reversed))
  1304. (choice :tag "Special C-e"
  1305. (const :tag "off" nil)
  1306. (const :tag "on: before tags first" t)
  1307. (const :tag "reversed: after tags first" reversed)))))
  1308. (defcustom org-special-ctrl-k nil
  1309. "Non-nil means `C-k' will behave specially in headlines.
  1310. When nil, `C-k' will call the default `kill-line' command.
  1311. When t, the following will happen while the cursor is in the headline:
  1312. - When at the beginning of a headline, kill the entire subtree.
  1313. - When in the middle of the headline text, kill the text up to the tags.
  1314. - When after the headline text and before the tags, kill all the tags."
  1315. :group 'org-edit-structure
  1316. :type 'boolean)
  1317. (defcustom org-ctrl-k-protect-subtree nil
  1318. "Non-nil means, do not delete a hidden subtree with `C-k'.
  1319. When set to the symbol `error', simply throw an error when `C-k' is
  1320. used to kill (part-of) a headline that has hidden text behind it.
  1321. Any other non-nil value will result in a query to the user, if it is
  1322. OK to kill that hidden subtree. When nil, kill without remorse."
  1323. :group 'org-edit-structure
  1324. :version "24.1"
  1325. :type '(choice
  1326. (const :tag "Do not protect hidden subtrees" nil)
  1327. (const :tag "Protect hidden subtrees with a security query" t)
  1328. (const :tag "Never kill a hidden subtree with C-k" error)))
  1329. (defcustom org-special-ctrl-o t
  1330. "Non-nil means, make `open-line' (\\[open-line]) insert a row in tables."
  1331. :group 'org-edit-structure
  1332. :type 'boolean)
  1333. (defcustom org-yank-folded-subtrees t
  1334. "Non-nil means when yanking subtrees, fold them.
  1335. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1336. it starts with a heading and all other headings in it are either children
  1337. or siblings, then fold all the subtrees. However, do this only if no
  1338. text after the yank would be swallowed into a folded tree by this action."
  1339. :group 'org-edit-structure
  1340. :type 'boolean)
  1341. (defcustom org-yank-adjusted-subtrees nil
  1342. "Non-nil means when yanking subtrees, adjust the level.
  1343. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1344. this function for details."
  1345. :group 'org-edit-structure
  1346. :type 'boolean)
  1347. (defcustom org-M-RET-may-split-line '((default . t))
  1348. "Non-nil means M-RET will split the line at the cursor position.
  1349. When nil, it will go to the end of the line before making a
  1350. new line.
  1351. You may also set this option in a different way for different
  1352. contexts. Valid contexts are:
  1353. headline when creating a new headline
  1354. item when creating a new item
  1355. table in a table field
  1356. default the value to be used for all contexts not explicitly
  1357. customized"
  1358. :group 'org-structure
  1359. :group 'org-table
  1360. :type '(choice
  1361. (const :tag "Always" t)
  1362. (const :tag "Never" nil)
  1363. (repeat :greedy t :tag "Individual contexts"
  1364. (cons
  1365. (choice :tag "Context"
  1366. (const headline)
  1367. (const item)
  1368. (const table)
  1369. (const default))
  1370. (boolean)))))
  1371. (defcustom org-insert-heading-respect-content nil
  1372. "Non-nil means insert new headings after the current subtree.
  1373. \\<org-mode-map>
  1374. When nil, the new heading is created directly after the current line.
  1375. The commands `\\[org-insert-heading-respect-content]' and \
  1376. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1377. for the duration of the command."
  1378. :group 'org-structure
  1379. :type 'boolean)
  1380. (defcustom org-blank-before-new-entry '((heading . auto)
  1381. (plain-list-item . auto))
  1382. "Should `org-insert-heading' leave a blank line before new heading/item?
  1383. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1384. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1385. which case Org will look at the surrounding headings/items and try to
  1386. make an intelligent decision whether to insert a blank line or not."
  1387. :group 'org-edit-structure
  1388. :type '(list
  1389. (cons (const heading)
  1390. (choice (const :tag "Never" nil)
  1391. (const :tag "Always" t)
  1392. (const :tag "Auto" auto)))
  1393. (cons (const plain-list-item)
  1394. (choice (const :tag "Never" nil)
  1395. (const :tag "Always" t)
  1396. (const :tag "Auto" auto)))))
  1397. (defcustom org-insert-heading-hook nil
  1398. "Hook being run after inserting a new heading."
  1399. :group 'org-edit-structure
  1400. :type 'hook)
  1401. (defgroup org-sparse-trees nil
  1402. "Options concerning sparse trees in Org mode."
  1403. :tag "Org Sparse Trees"
  1404. :group 'org-structure)
  1405. (defcustom org-highlight-sparse-tree-matches t
  1406. "Non-nil means highlight all matches that define a sparse tree.
  1407. The highlights will automatically disappear the next time the buffer is
  1408. changed by an edit command."
  1409. :group 'org-sparse-trees
  1410. :type 'boolean)
  1411. (defcustom org-remove-highlights-with-change t
  1412. "Non-nil means any change to the buffer will remove temporary highlights.
  1413. \\<org-mode-map>\
  1414. Such highlights are created by `org-occur' and `org-clock-display'.
  1415. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1416. to get rid of the highlights.
  1417. The highlights created by `org-latex-preview' always need
  1418. `\\[org-latex-preview]' to be removed."
  1419. :group 'org-sparse-trees
  1420. :group 'org-time
  1421. :type 'boolean)
  1422. (defcustom org-occur-case-fold-search t
  1423. "Non-nil means `org-occur' should be case-insensitive.
  1424. If set to `smart' the search will be case-insensitive only if it
  1425. doesn't specify any upper case character."
  1426. :group 'org-sparse-trees
  1427. :version "26.1"
  1428. :type '(choice
  1429. (const :tag "Case-sensitive" nil)
  1430. (const :tag "Case-insensitive" t)
  1431. (const :tag "Case-insensitive for lower case searches only" smart)))
  1432. (defcustom org-occur-hook '(org-first-headline-recenter)
  1433. "Hook that is run after `org-occur' has constructed a sparse tree.
  1434. This can be used to recenter the window to show as much of the structure
  1435. as possible."
  1436. :group 'org-sparse-trees
  1437. :type 'hook)
  1438. (defcustom org-self-insert-cluster-for-undo nil
  1439. "Non-nil means cluster self-insert commands for undo when possible.
  1440. If this is set, then, like in the Emacs command loop, 20 consecutive
  1441. characters will be undone together.
  1442. This is configurable, because there is some impact on typing performance."
  1443. :group 'org-table
  1444. :type 'boolean)
  1445. (defvaralias 'org-activate-links 'org-highlight-links)
  1446. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1447. "Types of links that should be highlighted in Org files.
  1448. This is a list of symbols, each one of them leading to the
  1449. highlighting of a certain link type.
  1450. You can still open links that are not highlighted.
  1451. In principle, it does not hurt to turn on highlighting for all
  1452. link types. There may be a small gain when turning off unused
  1453. link types. The types are:
  1454. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1455. angle Links in angular brackets that may contain whitespace like
  1456. <bbdb:Carsten Dominik>.
  1457. plain Plain links in normal text, no whitespace, like https://gnu.org.
  1458. radio Text that is matched by a radio target, see manual for details.
  1459. tag Tag settings in a headline (link to tag search).
  1460. date Time stamps (link to calendar).
  1461. footnote Footnote labels.
  1462. If you set this variable during an Emacs session, use `org-mode-restart'
  1463. in the Org buffer so that the change takes effect."
  1464. :group 'org-appearance
  1465. :type '(set :greedy t
  1466. (const :tag "Double bracket links" bracket)
  1467. (const :tag "Angular bracket links" angle)
  1468. (const :tag "Plain text links" plain)
  1469. (const :tag "Radio target matches" radio)
  1470. (const :tag "Tags" tag)
  1471. (const :tag "Timestamps" date)
  1472. (const :tag "Footnotes" footnote)))
  1473. (defcustom org-mark-ring-length 4
  1474. "Number of different positions to be recorded in the ring.
  1475. Changing this requires a restart of Emacs to work correctly."
  1476. :group 'org-link-follow
  1477. :type 'integer)
  1478. (defgroup org-todo nil
  1479. "Options concerning TODO items in Org mode."
  1480. :tag "Org TODO"
  1481. :group 'org)
  1482. (defgroup org-progress nil
  1483. "Options concerning Progress logging in Org mode."
  1484. :tag "Org Progress"
  1485. :group 'org-time)
  1486. (defvar org-todo-interpretation-widgets
  1487. '((:tag "Sequence (cycling hits every state)" sequence)
  1488. (:tag "Type (cycling directly to DONE)" type))
  1489. "The available interpretation symbols for customizing `org-todo-keywords'.
  1490. Interested libraries should add to this list.")
  1491. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  1492. "List of TODO entry keyword sequences and their interpretation.
  1493. \\<org-mode-map>This is a list of sequences.
  1494. Each sequence starts with a symbol, either `sequence' or `type',
  1495. indicating if the keywords should be interpreted as a sequence of
  1496. action steps, or as different types of TODO items. The first
  1497. keywords are states requiring action - these states will select a headline
  1498. for inclusion into the global TODO list Org produces. If one of the
  1499. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  1500. signify that no further action is necessary. If \"|\" is not found,
  1501. the last keyword is treated as the only DONE state of the sequence.
  1502. The command `\\[org-todo]' cycles an entry through these states, and one
  1503. additional state where no keyword is present. For details about this
  1504. cycling, see the manual.
  1505. TODO keywords and interpretation can also be set on a per-file basis with
  1506. the special #+SEQ_TODO and #+TYP_TODO lines.
  1507. Each keyword can optionally specify a character for fast state selection
  1508. \(in combination with the variable `org-use-fast-todo-selection')
  1509. and specifiers for state change logging, using the same syntax that
  1510. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  1511. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  1512. indicates to record a time stamp each time this state is selected.
  1513. Each keyword may also specify if a timestamp or a note should be
  1514. recorded when entering or leaving the state, by adding additional
  1515. characters in the parenthesis after the keyword. This looks like this:
  1516. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  1517. record only the time of the state change. With X and Y being either
  1518. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  1519. Y when leaving the state if and only if the *target* state does not
  1520. define X. You may omit any of the fast-selection key or X or /Y,
  1521. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  1522. For backward compatibility, this variable may also be just a list
  1523. of keywords. In this case the interpretation (sequence or type) will be
  1524. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  1525. :group 'org-todo
  1526. :group 'org-keywords
  1527. :type '(choice
  1528. (repeat :tag "Old syntax, just keywords"
  1529. (string :tag "Keyword"))
  1530. (repeat :tag "New syntax"
  1531. (cons
  1532. (choice
  1533. :tag "Interpretation"
  1534. ;;Quick and dirty way to see
  1535. ;;`org-todo-interpretation'. This takes the
  1536. ;;place of item arguments
  1537. :convert-widget
  1538. (lambda (widget)
  1539. (widget-put widget
  1540. :args (mapcar
  1541. (lambda (x)
  1542. (widget-convert
  1543. (cons 'const x)))
  1544. org-todo-interpretation-widgets))
  1545. widget))
  1546. (repeat
  1547. (string :tag "Keyword"))))))
  1548. (defvar-local org-todo-keywords-1 nil
  1549. "All TODO and DONE keywords active in a buffer.")
  1550. (defvar org-todo-keywords-for-agenda nil)
  1551. (defvar org-done-keywords-for-agenda nil)
  1552. (defvar org-todo-keyword-alist-for-agenda nil)
  1553. (defvar org-tag-alist-for-agenda nil
  1554. "Alist of all tags from all agenda files.")
  1555. (defvar org-tag-groups-alist-for-agenda nil
  1556. "Alist of all groups tags from all current agenda files.")
  1557. (defvar-local org-tag-groups-alist nil)
  1558. (defvar org-agenda-contributing-files nil)
  1559. (defvar-local org-current-tag-alist nil
  1560. "Alist of all tag groups in current buffer.
  1561. This variable takes into consideration `org-tag-alist',
  1562. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  1563. (defvar-local org-not-done-keywords nil)
  1564. (defvar-local org-done-keywords nil)
  1565. (defvar-local org-todo-heads nil)
  1566. (defvar-local org-todo-sets nil)
  1567. (defvar-local org-todo-log-states nil)
  1568. (defvar-local org-todo-kwd-alist nil)
  1569. (defvar-local org-todo-key-alist nil)
  1570. (defvar-local org-todo-key-trigger nil)
  1571. (defcustom org-todo-interpretation 'sequence
  1572. "Controls how TODO keywords are interpreted.
  1573. This variable is in principle obsolete and is only used for
  1574. backward compatibility, if the interpretation of todo keywords is
  1575. not given already in `org-todo-keywords'. See that variable for
  1576. more information."
  1577. :group 'org-todo
  1578. :group 'org-keywords
  1579. :type '(choice (const sequence)
  1580. (const type)))
  1581. (defcustom org-use-fast-todo-selection 'auto
  1582. "\\<org-mode-map>\
  1583. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  1584. This variable describes if and under what circumstances the cycling
  1585. mechanism for TODO keywords will be replaced by a single-key, direct
  1586. selection scheme, where the choices are displayed in a little window.
  1587. When nil, fast selection is never used. This means that the command
  1588. will always switch to the next state.
  1589. When it is the symbol `auto', fast selection is whenever selection
  1590. keys have been defined.
  1591. `expert' is like `auto', but no special window with the keyword
  1592. will be shown, choices will only be listed in the prompt.
  1593. In all cases, the special interface is only used if access keys have
  1594. actually been assigned by the user, i.e. if keywords in the configuration
  1595. are followed by a letter in parenthesis, like TODO(t)."
  1596. :group 'org-todo
  1597. :set (lambda (var val)
  1598. (cond
  1599. ((eq var t) (set-default-toplevel-value var 'auto))
  1600. ((eq var 'prefix) (set-default-toplevel-value var nil))
  1601. (t (set-default-toplevel-value var val))))
  1602. :type '(choice
  1603. (const :tag "Never" nil)
  1604. (const :tag "Automatically, when key letter have been defined" auto)
  1605. (const :tag "Automatically, but don't show the selection window" expert)))
  1606. (defcustom org-provide-todo-statistics t
  1607. "Non-nil means update todo statistics after insert and toggle.
  1608. ALL-HEADLINES means update todo statistics by including headlines
  1609. with no TODO keyword as well, counting them as not done.
  1610. A list of TODO keywords means the same, but skip keywords that are
  1611. not in this list.
  1612. When set to a list of two lists, the first list contains keywords
  1613. to consider as TODO keywords, the second list contains keywords
  1614. to consider as DONE keywords.
  1615. When this is set, todo statistics is updated in the parent of the
  1616. current entry each time a todo state is changed."
  1617. :group 'org-todo
  1618. :type '(choice
  1619. (const :tag "Yes, only for TODO entries" t)
  1620. (const :tag "Yes, including all entries" all-headlines)
  1621. (repeat :tag "Yes, for TODOs in this list"
  1622. (string :tag "TODO keyword"))
  1623. (list :tag "Yes, for TODOs and DONEs in these lists"
  1624. (repeat (string :tag "TODO keyword"))
  1625. (repeat (string :tag "DONE keyword")))
  1626. (other :tag "No TODO statistics" nil)))
  1627. (defcustom org-hierarchical-todo-statistics t
  1628. "Non-nil means TODO statistics covers just direct children.
  1629. When nil, all entries in the subtree are considered.
  1630. This has only an effect if `org-provide-todo-statistics' is set.
  1631. To set this to nil for only a single subtree, use a COOKIE_DATA
  1632. property and include the word \"recursive\" into the value."
  1633. :group 'org-todo
  1634. :type 'boolean)
  1635. (defcustom org-after-todo-state-change-hook nil
  1636. "Hook which is run after the state of a TODO item was changed.
  1637. The new state (a string with a TODO keyword, or nil) is available in the
  1638. Lisp variable `org-state'."
  1639. :group 'org-todo
  1640. :type 'hook)
  1641. (defvar org-blocker-hook nil
  1642. "Hook for functions that are allowed to block a state change.
  1643. Functions in this hook should not modify the buffer.
  1644. Each function gets as its single argument a property list,
  1645. see `org-trigger-hook' for more information about this list.
  1646. If any of the functions in this hook returns nil, the state change
  1647. is blocked.")
  1648. (defvar org-trigger-hook nil
  1649. "Hook for functions that are triggered by a state change.
  1650. Each function gets as its single argument a property list with at
  1651. least the following elements:
  1652. (:type type-of-change :position pos-at-entry-start
  1653. :from old-state :to new-state)
  1654. Depending on the type, more properties may be present.
  1655. This mechanism is currently implemented for:
  1656. TODO state changes
  1657. ------------------
  1658. :type todo-state-change
  1659. :from previous state (keyword as a string), or nil, or a symbol
  1660. `todo' or `done', to indicate the general type of state.
  1661. :to new state, like in :from")
  1662. (defcustom org-enforce-todo-dependencies nil
  1663. "Non-nil means undone TODO entries will block switching the parent to DONE.
  1664. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  1665. be blocked if any prior sibling is not yet done.
  1666. Finally, if the parent is blocked because of ordered siblings of its own,
  1667. the child will also be blocked."
  1668. :set (lambda (var val)
  1669. (set-default-toplevel-value var val)
  1670. (if val
  1671. (add-hook 'org-blocker-hook
  1672. 'org-block-todo-from-children-or-siblings-or-parent)
  1673. (remove-hook 'org-blocker-hook
  1674. 'org-block-todo-from-children-or-siblings-or-parent)))
  1675. :group 'org-todo
  1676. :type 'boolean)
  1677. (defcustom org-enforce-todo-checkbox-dependencies nil
  1678. "Non-nil means unchecked boxes will block switching the parent to DONE.
  1679. When this is nil, checkboxes have no influence on switching TODO states.
  1680. When non-nil, you first need to check off all check boxes before the TODO
  1681. entry can be switched to DONE.
  1682. This variable needs to be set before org.el is loaded, and you need to
  1683. restart Emacs after a change to make the change effective. The only way
  1684. to change it while Emacs is running is through the customize interface."
  1685. :set (lambda (var val)
  1686. (set-default-toplevel-value var val)
  1687. (if val
  1688. (add-hook 'org-blocker-hook
  1689. 'org-block-todo-from-checkboxes)
  1690. (remove-hook 'org-blocker-hook
  1691. 'org-block-todo-from-checkboxes)))
  1692. :group 'org-todo
  1693. :type 'boolean)
  1694. (defcustom org-treat-insert-todo-heading-as-state-change nil
  1695. "Non-nil means inserting a TODO heading is treated as state change.
  1696. So when the command `\\[org-insert-todo-heading]' is used, state change
  1697. logging will apply if appropriate. When nil, the new TODO item will
  1698. be inserted directly, and no logging will take place."
  1699. :group 'org-todo
  1700. :type 'boolean)
  1701. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  1702. "Non-nil means switching TODO states with S-cursor counts as state change.
  1703. This is the default behavior. However, setting this to nil allows a
  1704. convenient way to select a TODO state and bypass any logging associated
  1705. with that."
  1706. :group 'org-todo
  1707. :type 'boolean)
  1708. (defcustom org-todo-state-tags-triggers nil
  1709. "Tag changes that should be triggered by TODO state changes.
  1710. This is a list. Each entry is
  1711. (state-change (tag . flag) .......)
  1712. State-change can be a string with a state, and empty string to indicate the
  1713. state that has no TODO keyword, or it can be one of the symbols `todo'
  1714. or `done', meaning any not-done or done state, respectively."
  1715. :group 'org-todo
  1716. :group 'org-tags
  1717. :type '(repeat
  1718. (cons (choice :tag "When changing to"
  1719. (const :tag "Not-done state" todo)
  1720. (const :tag "Done state" done)
  1721. (string :tag "State"))
  1722. (repeat
  1723. (cons :tag "Tag action"
  1724. (string :tag "Tag")
  1725. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  1726. (defcustom org-log-done nil
  1727. "Information to record when a task moves to the DONE state.
  1728. Possible values are:
  1729. nil Don't add anything, just change the keyword
  1730. time Add a time stamp to the task
  1731. note Prompt for a note and add it with template `org-log-note-headings'
  1732. This option can also be set with on a per-file-basis with
  1733. #+STARTUP: nologdone
  1734. #+STARTUP: logdone
  1735. #+STARTUP: lognotedone
  1736. You can have local logging settings for a subtree by setting the LOGGING
  1737. property to one or more of these keywords."
  1738. :group 'org-todo
  1739. :group 'org-progress
  1740. :type '(choice
  1741. (const :tag "No logging" nil)
  1742. (const :tag "Record CLOSED timestamp" time)
  1743. (const :tag "Record CLOSED timestamp with note." note)))
  1744. ;; Normalize old uses of org-log-done.
  1745. (cond
  1746. ((eq org-log-done t) (setq org-log-done 'time))
  1747. ((and (listp org-log-done) (memq 'done org-log-done))
  1748. (setq org-log-done 'note)))
  1749. (defcustom org-log-reschedule nil
  1750. "Information to record when the scheduling date of a task is modified.
  1751. Possible values are:
  1752. nil Don't add anything, just change the date
  1753. time Add a time stamp to the task
  1754. note Prompt for a note and add it with template `org-log-note-headings'
  1755. This option can also be set with on a per-file-basis with
  1756. #+STARTUP: nologreschedule
  1757. #+STARTUP: logreschedule
  1758. #+STARTUP: lognotereschedule
  1759. You can have local logging settings for a subtree by setting the LOGGING
  1760. property to one or more of these keywords.
  1761. This variable has an effect when calling `org-schedule' or
  1762. `org-agenda-schedule' only."
  1763. :group 'org-todo
  1764. :group 'org-progress
  1765. :type '(choice
  1766. (const :tag "No logging" nil)
  1767. (const :tag "Record timestamp" time)
  1768. (const :tag "Record timestamp with note" note)))
  1769. (defcustom org-log-redeadline nil
  1770. "Information to record when the deadline date of a task is modified.
  1771. Possible values are:
  1772. nil Don't add anything, just change the date
  1773. time Add a time stamp to the task
  1774. note Prompt for a note and add it with template `org-log-note-headings'
  1775. This option can also be set with on a per-file-basis with
  1776. #+STARTUP: nologredeadline
  1777. #+STARTUP: logredeadline
  1778. #+STARTUP: lognoteredeadline
  1779. You can have local logging settings for a subtree by setting the LOGGING
  1780. property to one or more of these keywords.
  1781. This variable has an effect when calling `org-deadline' or
  1782. `org-agenda-deadline' only."
  1783. :group 'org-todo
  1784. :group 'org-progress
  1785. :type '(choice
  1786. (const :tag "No logging" nil)
  1787. (const :tag "Record timestamp" time)
  1788. (const :tag "Record timestamp with note." note)))
  1789. (defcustom org-log-note-clock-out nil
  1790. "Non-nil means record a note when clocking out of an item.
  1791. This can also be configured on a per-file basis by adding one of
  1792. the following lines anywhere in the buffer:
  1793. #+STARTUP: lognoteclock-out
  1794. #+STARTUP: nolognoteclock-out"
  1795. :group 'org-todo
  1796. :group 'org-progress
  1797. :type 'boolean)
  1798. (defcustom org-log-done-with-time t
  1799. "Non-nil means the CLOSED time stamp will contain date and time.
  1800. When nil, only the date will be recorded."
  1801. :group 'org-progress
  1802. :type 'boolean)
  1803. (defcustom org-log-note-headings
  1804. '((done . "CLOSING NOTE %t")
  1805. (state . "State %-12s from %-12S %t")
  1806. (note . "Note taken on %t")
  1807. (reschedule . "Rescheduled from %S on %t")
  1808. (delschedule . "Not scheduled, was %S on %t")
  1809. (redeadline . "New deadline from %S on %t")
  1810. (deldeadline . "Removed deadline, was %S on %t")
  1811. (refile . "Refiled on %t")
  1812. (clock-out . ""))
  1813. "Headings for notes added to entries.
  1814. The value is an alist, with the car being a symbol indicating the
  1815. note context, and the cdr is the heading to be used. The heading
  1816. may also be the empty string. The following placeholders can be
  1817. used:
  1818. %t a time stamp.
  1819. %T an active time stamp instead the default inactive one
  1820. %d a short-format time stamp.
  1821. %D an active short-format time stamp.
  1822. %s the new TODO state or time stamp (inactive), in double quotes.
  1823. %S the old TODO state or time stamp (inactive), in double quotes.
  1824. %u the user name.
  1825. %U full user name.
  1826. In fact, it is not a good idea to change the `state' entry,
  1827. because Agenda Log mode depends on the format of these entries."
  1828. :group 'org-todo
  1829. :group 'org-progress
  1830. :type '(list :greedy t
  1831. (cons (const :tag "Heading when closing an item" done) string)
  1832. (cons (const :tag
  1833. "Heading when changing todo state (todo sequence only)"
  1834. state) string)
  1835. (cons (const :tag "Heading when just taking a note" note) string)
  1836. (cons (const :tag "Heading when rescheduling" reschedule) string)
  1837. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  1838. (cons (const :tag "Heading when changing deadline" redeadline) string)
  1839. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  1840. (cons (const :tag "Heading when refiling" refile) string)
  1841. (cons (const :tag "Heading when clocking out" clock-out) string)))
  1842. (unless (assq 'note org-log-note-headings)
  1843. (push '(note . "%t") org-log-note-headings))
  1844. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  1845. (defcustom org-log-into-drawer nil
  1846. "Non-nil means insert state change notes and time stamps into a drawer.
  1847. When nil, state changes notes will be inserted after the headline and
  1848. any scheduling and clock lines, but not inside a drawer.
  1849. The value of this variable should be the name of the drawer to use.
  1850. LOGBOOK is proposed as the default drawer for this purpose, you can
  1851. also set this to a string to define the drawer of your choice.
  1852. A value of t is also allowed, representing \"LOGBOOK\".
  1853. A value of t or nil can also be set with on a per-file-basis with
  1854. #+STARTUP: logdrawer
  1855. #+STARTUP: nologdrawer
  1856. If this variable is set, `org-log-state-notes-insert-after-drawers'
  1857. will be ignored.
  1858. You can set the property LOG_INTO_DRAWER to overrule this setting for
  1859. a subtree.
  1860. Do not check directly this variable in a Lisp program. Call
  1861. function `org-log-into-drawer' instead."
  1862. :group 'org-todo
  1863. :group 'org-progress
  1864. :type '(choice
  1865. (const :tag "Not into a drawer" nil)
  1866. (const :tag "LOGBOOK" t)
  1867. (string :tag "Other")))
  1868. (defun org-log-into-drawer ()
  1869. "Name of the log drawer, as a string, or nil.
  1870. This is the value of `org-log-into-drawer'. However, if the
  1871. current entry has or inherits a LOG_INTO_DRAWER property, it will
  1872. be used instead of the default value."
  1873. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  1874. (cond ((equal p "nil") nil)
  1875. ((equal p "t") "LOGBOOK")
  1876. ((stringp p) p)
  1877. (p "LOGBOOK")
  1878. ((stringp org-log-into-drawer) org-log-into-drawer)
  1879. (org-log-into-drawer "LOGBOOK"))))
  1880. (defcustom org-log-state-notes-insert-after-drawers nil
  1881. "Non-nil means insert state change notes after any drawers in entry.
  1882. Only the drawers that *immediately* follow the headline and the
  1883. deadline/scheduled line are skipped.
  1884. When nil, insert notes right after the heading and perhaps the line
  1885. with deadline/scheduling if present.
  1886. This variable will have no effect if `org-log-into-drawer' is
  1887. set."
  1888. :group 'org-todo
  1889. :group 'org-progress
  1890. :type 'boolean)
  1891. (defcustom org-log-states-order-reversed t
  1892. "Non-nil means the latest state note will be directly after heading.
  1893. When nil, the state change notes will be ordered according to time.
  1894. This option can also be set with on a per-file-basis with
  1895. #+STARTUP: logstatesreversed
  1896. #+STARTUP: nologstatesreversed"
  1897. :group 'org-todo
  1898. :group 'org-progress
  1899. :type 'boolean)
  1900. (defcustom org-todo-repeat-to-state nil
  1901. "The TODO state to which a repeater should return the repeating task.
  1902. By default this is the first task of a TODO sequence or the
  1903. previous state of a TYPE_TODO set. But you can specify to use
  1904. the previous state in a TODO sequence or a string.
  1905. Alternatively, you can set the :REPEAT_TO_STATE: property of the
  1906. entry, which has precedence over this option."
  1907. :group 'org-todo
  1908. :version "24.1"
  1909. :type '(choice (const :tag "Use the previous TODO state" t)
  1910. (const :tag "Use the head of the TODO sequence" nil)
  1911. (string :tag "Use a specific TODO state")))
  1912. (defcustom org-log-repeat 'time
  1913. "Non-nil means record moving through the DONE state when triggering repeat.
  1914. An auto-repeating task is immediately switched back to TODO when
  1915. marked DONE. If you are not logging state changes (by adding \"@\"
  1916. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  1917. record a closing note, there will be no record of the task moving
  1918. through DONE. This variable forces taking a note anyway.
  1919. nil Don't force a record
  1920. time Record a time stamp
  1921. note Prompt for a note and add it with template `org-log-note-headings'
  1922. This option can also be set with on a per-file-basis with
  1923. #+STARTUP: nologrepeat
  1924. #+STARTUP: logrepeat
  1925. #+STARTUP: lognoterepeat
  1926. You can have local logging settings for a subtree by setting the LOGGING
  1927. property to one or more of these keywords."
  1928. :group 'org-todo
  1929. :group 'org-progress
  1930. :type '(choice
  1931. (const :tag "Don't force a record" nil)
  1932. (const :tag "Force recording the DONE state" time)
  1933. (const :tag "Force recording a note with the DONE state" note)))
  1934. (defcustom org-todo-repeat-hook nil
  1935. "Hook that is run after a task has been repeated."
  1936. :package-version '(Org . "9.2")
  1937. :group 'org-todo
  1938. :type 'hook)
  1939. (defgroup org-priorities nil
  1940. "Priorities in Org mode."
  1941. :tag "Org Priorities"
  1942. :group 'org-todo)
  1943. (defvaralias 'org-enable-priority-commands 'org-priority-enable-commands)
  1944. (defcustom org-priority-enable-commands t
  1945. "Non-nil means priority commands are active.
  1946. When nil, these commands will be disabled, so that you never accidentally
  1947. set a priority."
  1948. :group 'org-priorities
  1949. :type 'boolean)
  1950. (defvaralias 'org-highest-priority 'org-priority-highest)
  1951. (defcustom org-priority-highest ?A
  1952. "The highest priority of TODO items.
  1953. A character like ?A, ?B, etc., or a numeric value like 1, 2, etc.
  1954. The default is the character ?A, which is 65 as a numeric value.
  1955. If you set `org-priority-highest' to a numeric value inferior to
  1956. 65, Org assumes you want to use digits for the priority cookie.
  1957. If you set it to >=65, Org assumes you want to use alphabetical
  1958. characters.
  1959. In both cases, the value of `org-priority-highest' must be
  1960. smaller than `org-priority-lowest': for example, if \"A\" is the
  1961. highest priority, it is smaller than the lowest \"C\" priority:
  1962. 65 < 67."
  1963. :group 'org-priorities
  1964. :type '(choice
  1965. (character :tag "Character")
  1966. (integer :tag "Integer (< 65)")))
  1967. (defvaralias 'org-lowest-priority 'org-priority-lowest)
  1968. (defcustom org-priority-lowest ?C
  1969. "The lowest priority of TODO items.
  1970. A character like ?C, ?B, etc., or a numeric value like 9, 8, etc.
  1971. The default is the character ?C, which is 67 as a numeric value.
  1972. If you set `org-priority-lowest' to a numeric value inferior to
  1973. 65, Org assumes you want to use digits for the priority cookie.
  1974. If you set it to >=65, Org assumes you want to use alphabetical
  1975. characters.
  1976. In both cases, the value of `org-priority-lowest' must be greater
  1977. than `org-priority-highest': for example, if \"C\" is the lowest
  1978. priority, it is greater than the highest \"A\" priority: 67 >
  1979. 65."
  1980. :group 'org-priorities
  1981. :type '(choice
  1982. (character :tag "Character")
  1983. (integer :tag "Integer (< 65)")))
  1984. (defvaralias 'org-default-priority 'org-priority-default)
  1985. (defcustom org-priority-default ?B
  1986. "The default priority of TODO items.
  1987. This is the priority an item gets if no explicit priority is given.
  1988. When starting to cycle on an empty priority the first step in the cycle
  1989. depends on `org-priority-start-cycle-with-default'. The resulting first
  1990. step priority must not exceed the range from `org-priority-highest' to
  1991. `org-priority-lowest' which means that `org-priority-default' has to be
  1992. in this range exclusive or inclusive to the range boundaries. Else the
  1993. first step refuses to set the default and the second will fall back on
  1994. \(depending on the command used) the highest or lowest priority."
  1995. :group 'org-priorities
  1996. :type '(choice
  1997. (character :tag "Character")
  1998. (integer :tag "Integer (< 65)")))
  1999. (defcustom org-priority-start-cycle-with-default t
  2000. "Non-nil means start with default priority when starting to cycle.
  2001. When this is nil, the first step in the cycle will be (depending on the
  2002. command used) one higher or lower than the default priority.
  2003. See also `org-priority-default'."
  2004. :group 'org-priorities
  2005. :type 'boolean)
  2006. (defvaralias 'org-get-priority-function 'org-priority-get-priority-function)
  2007. (defcustom org-priority-get-priority-function nil
  2008. "Function to extract the priority from a string.
  2009. The string is normally the headline. If this is nil, Org
  2010. computes the priority from the priority cookie like [#A] in the
  2011. headline. It returns an integer, increasing by 1000 for each
  2012. priority level.
  2013. The user can set a different function here, which should take a
  2014. string as an argument and return the numeric priority."
  2015. :group 'org-priorities
  2016. :version "24.1"
  2017. :type '(choice
  2018. (const nil)
  2019. (function)))
  2020. (defgroup org-time nil
  2021. "Options concerning time stamps and deadlines in Org mode."
  2022. :tag "Org Time"
  2023. :group 'org)
  2024. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2025. "Number of minutes to round time stamps to.
  2026. \\<org-mode-map>\
  2027. These are two values, the first applies when first creating a time stamp.
  2028. The second applies when changing it with the commands `S-up' and `S-down'.
  2029. When changing the time stamp, this means that it will change in steps
  2030. of N minutes, as given by the second value.
  2031. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2032. numbers should be factors of 60, so for example 5, 10, 15.
  2033. When this is larger than 1, you can still force an exact time stamp by using
  2034. a double prefix argument to a time stamp command like \
  2035. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2036. and by using a prefix arg to `S-up/down' to specify the exact number
  2037. of minutes to shift."
  2038. :group 'org-time
  2039. :get (lambda (var) ; Make sure both elements are there
  2040. (if (integerp (default-value var))
  2041. (list (default-value var) 5)
  2042. (default-value var)))
  2043. :type '(list
  2044. (integer :tag "when inserting times")
  2045. (integer :tag "when modifying times")))
  2046. ;; Normalize old customizations of this variable.
  2047. (when (integerp org-time-stamp-rounding-minutes)
  2048. (setq org-time-stamp-rounding-minutes
  2049. (list org-time-stamp-rounding-minutes
  2050. org-time-stamp-rounding-minutes)))
  2051. (defcustom org-display-custom-times nil
  2052. "Non-nil means overlay custom formats over all time stamps.
  2053. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2054. To turn this on on a per-file basis, insert anywhere in the file:
  2055. #+STARTUP: customtime"
  2056. :group 'org-time
  2057. :type 'sexp)
  2058. (make-variable-buffer-local 'org-display-custom-times)
  2059. (defcustom org-time-stamp-custom-formats
  2060. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2061. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2062. These are overlaid over the default ISO format if the variable
  2063. `org-display-custom-times' is set. Time like %H:%M should be at the
  2064. end of the second format. The custom formats are also honored by export
  2065. commands, if custom time display is turned on at the time of export."
  2066. :group 'org-time
  2067. :type 'sexp)
  2068. (defun org-time-stamp-format (&optional long inactive)
  2069. "Get the right format for a time string."
  2070. (let ((f (if long (cdr org-time-stamp-formats)
  2071. (car org-time-stamp-formats))))
  2072. (if inactive
  2073. (concat "[" (substring f 1 -1) "]")
  2074. f)))
  2075. (defcustom org-deadline-warning-days 14
  2076. "Number of days before expiration during which a deadline becomes active.
  2077. This variable governs the display in sparse trees and in the agenda.
  2078. When 0 or negative, it means use this number (the absolute value of it)
  2079. even if a deadline has a different individual lead time specified.
  2080. Custom commands can set this variable in the options section."
  2081. :group 'org-time
  2082. :group 'org-agenda-daily/weekly
  2083. :type 'integer)
  2084. (defcustom org-scheduled-delay-days 0
  2085. "Number of days before a scheduled item becomes active.
  2086. This variable governs the display in sparse trees and in the agenda.
  2087. The default value (i.e. 0) means: don't delay scheduled item.
  2088. When negative, it means use this number (the absolute value of it)
  2089. even if a scheduled item has a different individual delay time
  2090. specified.
  2091. Custom commands can set this variable in the options section."
  2092. :group 'org-time
  2093. :group 'org-agenda-daily/weekly
  2094. :version "24.4"
  2095. :package-version '(Org . "8.0")
  2096. :type 'integer)
  2097. (defcustom org-read-date-prefer-future t
  2098. "Non-nil means assume future for incomplete date input from user.
  2099. This affects the following situations:
  2100. 1. The user gives a month but not a year.
  2101. For example, if it is April and you enter \"feb 2\", this will be read
  2102. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2103. 2. The user gives a day, but no month.
  2104. For example, if today is the 15th, and you enter \"3\", Org will read
  2105. this as the third of *next* month. However, if you enter \"17\",
  2106. it will be considered as *this* month.
  2107. If you set this variable to the symbol `time', then also the following
  2108. will work:
  2109. 3. If the user gives a time.
  2110. If the time is before now, it will be interpreted as tomorrow.
  2111. Currently none of this works for ISO week specifications.
  2112. When this option is nil, the current day, month and year will always be
  2113. used as defaults.
  2114. See also `org-agenda-jump-prefer-future'."
  2115. :group 'org-time
  2116. :type '(choice
  2117. (const :tag "Never" nil)
  2118. (const :tag "Check month and day" t)
  2119. (const :tag "Check month, day, and time" time)))
  2120. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2121. "Should the agenda jump command prefer the future for incomplete dates?
  2122. The default is to do the same as configured in `org-read-date-prefer-future'.
  2123. But you can also set a deviating value here.
  2124. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2125. :group 'org-agenda
  2126. :group 'org-time
  2127. :version "24.1"
  2128. :type '(choice
  2129. (const :tag "Use org-read-date-prefer-future"
  2130. org-read-date-prefer-future)
  2131. (const :tag "Never" nil)
  2132. (const :tag "Always" t)))
  2133. (defcustom org-read-date-force-compatible-dates t
  2134. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2135. Depending on the system Emacs is running on, certain dates cannot
  2136. be represented with the type used internally to represent time.
  2137. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2138. correctly. Some systems allow for earlier dates, some for later,
  2139. some for both. One way to find out is to insert any date into an
  2140. Org buffer, putting the cursor on the year and hitting S-up and
  2141. S-down to test the range.
  2142. When this variable is set to t, the date/time prompt will not let
  2143. you specify dates outside the 1970-2037 range, so it is certain that
  2144. these dates will work in whatever version of Emacs you are
  2145. running, and also that you can move a file from one Emacs implementation
  2146. to another. Whenever Org is forcing the year for you, it will display
  2147. a message and beep.
  2148. When this variable is nil, Org will check if the date is
  2149. representable in the specific Emacs implementation you are using.
  2150. If not, it will force a year, usually the current year, and beep
  2151. to remind you. Currently this setting is not recommended because
  2152. the likelihood that you will open your Org files in an Emacs that
  2153. has limited date range is not negligible.
  2154. A workaround for this problem is to use diary sexp dates for time
  2155. stamps outside of this range."
  2156. :group 'org-time
  2157. :version "24.1"
  2158. :type 'boolean)
  2159. (defcustom org-read-date-display-live t
  2160. "Non-nil means display current interpretation of date prompt live.
  2161. This display will be in an overlay, in the minibuffer. Note that
  2162. live display is only active when `org-read-date-popup-calendar'
  2163. is non-nil."
  2164. :group 'org-time
  2165. :type 'boolean)
  2166. (defvaralias 'org-popup-calendar-for-date-prompt
  2167. 'org-read-date-popup-calendar)
  2168. (defcustom org-read-date-popup-calendar t
  2169. "Non-nil means pop up a calendar when prompting for a date.
  2170. In the calendar, the date can be selected with mouse-1. However, the
  2171. minibuffer will also be active, and you can simply enter the date as well.
  2172. When nil, only the minibuffer will be available."
  2173. :group 'org-time
  2174. :type 'boolean)
  2175. (defcustom org-extend-today-until 0
  2176. "The hour when your day really ends. Must be an integer.
  2177. This has influence for the following applications:
  2178. - When switching the agenda to \"today\". If it is still earlier than
  2179. the time given here, the day recognized as TODAY is actually yesterday.
  2180. - When a date is read from the user and it is still before the time given
  2181. here, the current date and time will be assumed to be yesterday, 23:59.
  2182. Also, timestamps inserted in capture templates follow this rule.
  2183. IMPORTANT: This is a feature whose implementation is and likely will
  2184. remain incomplete. Really, it is only here because past midnight seems to
  2185. be the favorite working time of John Wiegley :-)"
  2186. :group 'org-time
  2187. :type 'integer)
  2188. (defcustom org-use-effective-time nil
  2189. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2190. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2191. \"effective time\" of any timestamps between midnight and 8am will be
  2192. 23:59 of the previous day."
  2193. :group 'org-time
  2194. :version "24.1"
  2195. :type 'boolean)
  2196. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2197. "When non-nil, use the last clock out time for `org-todo'.
  2198. Note that this option has precedence over the combined use of
  2199. `org-use-effective-time' and `org-extend-today-until'."
  2200. :group 'org-time
  2201. :version "24.4"
  2202. :package-version '(Org . "8.0")
  2203. :type 'boolean)
  2204. (defcustom org-edit-timestamp-down-means-later nil
  2205. "Non-nil means S-down will increase the time in a time stamp.
  2206. When nil, S-up will increase."
  2207. :group 'org-time
  2208. :type 'boolean)
  2209. (defcustom org-calendar-follow-timestamp-change t
  2210. "Non-nil means make the calendar window follow timestamp changes.
  2211. When a timestamp is modified and the calendar window is visible, it will be
  2212. moved to the new date."
  2213. :group 'org-time
  2214. :type 'boolean)
  2215. (defgroup org-tags nil
  2216. "Options concerning tags in Org mode."
  2217. :tag "Org Tags"
  2218. :group 'org)
  2219. (defcustom org-tag-alist nil
  2220. "Default tags available in Org files.
  2221. The value of this variable is an alist. Associations either:
  2222. (TAG)
  2223. (TAG . SELECT)
  2224. (SPECIAL)
  2225. where TAG is a tag as a string, SELECT is character, used to
  2226. select that tag through the fast tag selection interface, and
  2227. SPECIAL is one of the following keywords: `:startgroup',
  2228. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2229. `:newline'. These keywords are used to define a hierarchy of
  2230. tags. See manual for details.
  2231. When this variable is nil, Org mode bases tag input on what is
  2232. already in the buffer. The value can be overridden locally by
  2233. using a TAGS keyword, e.g.,
  2234. #+TAGS: tag1 tag2
  2235. See also `org-tag-persistent-alist' to sidestep this behavior."
  2236. :group 'org-tags
  2237. :type '(repeat
  2238. (choice
  2239. (cons :tag "Tag with key"
  2240. (string :tag "Tag name")
  2241. (character :tag "Access char"))
  2242. (list :tag "Tag" (string :tag "Tag name"))
  2243. (const :tag "Start radio group" (:startgroup))
  2244. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2245. (const :tag "Group tags delimiter" (:grouptags))
  2246. (const :tag "End radio group" (:endgroup))
  2247. (const :tag "End tag group, non distinct" (:endgrouptag))
  2248. (const :tag "New line" (:newline)))))
  2249. (defcustom org-tag-persistent-alist nil
  2250. "Tags always available in Org files.
  2251. The value of this variable is an alist. Associations either:
  2252. (TAG)
  2253. (TAG . SELECT)
  2254. (SPECIAL)
  2255. where TAG is a tag as a string, SELECT is a character, used to
  2256. select that tag through the fast tag selection interface, and
  2257. SPECIAL is one of the following keywords: `:startgroup',
  2258. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2259. `:newline'. These keywords are used to define a hierarchy of
  2260. tags. See manual for details.
  2261. Unlike to `org-tag-alist', tags defined in this variable do not
  2262. depend on a local TAGS keyword. Instead, to disable these tags
  2263. on a per-file basis, insert anywhere in the file:
  2264. #+STARTUP: noptag"
  2265. :group 'org-tags
  2266. :type '(repeat
  2267. (choice
  2268. (cons :tag "Tag with key"
  2269. (string :tag "Tag name")
  2270. (character :tag "Access char"))
  2271. (list :tag "Tag" (string :tag "Tag name"))
  2272. (const :tag "Start radio group" (:startgroup))
  2273. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2274. (const :tag "Group tags delimiter" (:grouptags))
  2275. (const :tag "End radio group" (:endgroup))
  2276. (const :tag "End tag group, non distinct" (:endgrouptag))
  2277. (const :tag "New line" (:newline)))))
  2278. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2279. "If non-nil, always offer completion for all tags of all agenda files.
  2280. Setting this variable locally allows for dynamic generation of tag
  2281. completions in capture buffers.
  2282. (add-hook \\='org-capture-mode-hook
  2283. (lambda ()
  2284. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  2285. :group 'org-tags
  2286. :version "24.1"
  2287. :type 'boolean)
  2288. (defvar org-file-tags nil
  2289. "List of tags that can be inherited by all entries in the file.
  2290. The tags will be inherited if the variable `org-use-tag-inheritance'
  2291. says they should be.
  2292. This variable is populated from #+FILETAGS lines.")
  2293. (defcustom org-use-fast-tag-selection 'auto
  2294. "Non-nil means use fast tag selection scheme.
  2295. This is a special interface to select and deselect tags with single keys.
  2296. When nil, fast selection is never used.
  2297. When the symbol `auto', fast selection is used if and only if selection
  2298. characters for tags have been configured, either through the variable
  2299. `org-tag-alist' or through a #+TAGS line in the buffer.
  2300. When t, fast selection is always used and selection keys are assigned
  2301. automatically if necessary."
  2302. :group 'org-tags
  2303. :type '(choice
  2304. (const :tag "Always" t)
  2305. (const :tag "Never" nil)
  2306. (const :tag "When selection characters are configured" auto)))
  2307. (defcustom org-fast-tag-selection-single-key nil
  2308. "Non-nil means fast tag selection exits after first change.
  2309. When nil, you have to press RET to exit it.
  2310. During fast tag selection, you can toggle this flag with `C-c'.
  2311. This variable can also have the value `expert'. In this case, the window
  2312. displaying the tags menu is not even shown, until you press `C-c' again."
  2313. :group 'org-tags
  2314. :type '(choice
  2315. (const :tag "No" nil)
  2316. (const :tag "Yes" t)
  2317. (const :tag "Expert" expert)))
  2318. (defvar org-fast-tag-selection-include-todo nil
  2319. "Non-nil means fast tags selection interface will also offer TODO states.
  2320. This is an undocumented feature, you should not rely on it.")
  2321. (defcustom org-tags-column -77
  2322. "The column to which tags should be indented in a headline.
  2323. If this number is positive, it specifies the column. If it is negative,
  2324. it means that the tags should be flushright to that column. For example,
  2325. -80 works well for a normal 80 character screen.
  2326. When 0, place tags directly after headline text, with only one space in
  2327. between."
  2328. :group 'org-tags
  2329. :type 'integer)
  2330. (defcustom org-auto-align-tags t
  2331. "Non-nil keeps tags aligned when modifying headlines.
  2332. Some operations (i.e. demoting) change the length of a headline and
  2333. therefore shift the tags around. With this option turned on, after
  2334. each such operation the tags are again aligned to `org-tags-column'."
  2335. :group 'org-tags
  2336. :type 'boolean)
  2337. (defcustom org-use-tag-inheritance t
  2338. "Non-nil means tags in levels apply also for sublevels.
  2339. When nil, only the tags directly given in a specific line apply there.
  2340. This may also be a list of tags that should be inherited, or a regexp that
  2341. matches tags that should be inherited. Additional control is possible
  2342. with the variable `org-tags-exclude-from-inheritance' which gives an
  2343. explicit list of tags to be excluded from inheritance, even if the value of
  2344. `org-use-tag-inheritance' would select it for inheritance.
  2345. If this option is t, a match early-on in a tree can lead to a large
  2346. number of matches in the subtree when constructing the agenda or creating
  2347. a sparse tree. If you only want to see the first match in a tree during
  2348. a search, check out the variable `org-tags-match-list-sublevels'."
  2349. :group 'org-tags
  2350. :type '(choice
  2351. (const :tag "Not" nil)
  2352. (const :tag "Always" t)
  2353. (repeat :tag "Specific tags" (string :tag "Tag"))
  2354. (regexp :tag "Tags matched by regexp")))
  2355. (defcustom org-tags-exclude-from-inheritance nil
  2356. "List of tags that should never be inherited.
  2357. This is a way to exclude a few tags from inheritance. For way to do
  2358. the opposite, to actively allow inheritance for selected tags,
  2359. see the variable `org-use-tag-inheritance'."
  2360. :group 'org-tags
  2361. :type '(repeat (string :tag "Tag")))
  2362. (defun org-tag-inherit-p (tag)
  2363. "Check if TAG is one that should be inherited."
  2364. (cond
  2365. ((member tag org-tags-exclude-from-inheritance) nil)
  2366. ((eq org-use-tag-inheritance t) t)
  2367. ((not org-use-tag-inheritance) nil)
  2368. ((stringp org-use-tag-inheritance)
  2369. (string-match org-use-tag-inheritance tag))
  2370. ((listp org-use-tag-inheritance)
  2371. (member tag org-use-tag-inheritance))
  2372. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  2373. (defcustom org-tags-match-list-sublevels t
  2374. "Non-nil means list also sublevels of headlines matching a search.
  2375. This variable applies to tags/property searches, and also to stuck
  2376. projects because this search is based on a tags match as well.
  2377. When set to the symbol `indented', sublevels are indented with
  2378. leading dots.
  2379. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  2380. the sublevels of a headline matching a tag search often also match
  2381. the same search. Listing all of them can create very long lists.
  2382. Setting this variable to nil causes subtrees of a match to be skipped.
  2383. This variable is semi-obsolete and probably should always be true. It
  2384. is better to limit inheritance to certain tags using the variables
  2385. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  2386. :group 'org-tags
  2387. :type '(choice
  2388. (const :tag "No, don't list them" nil)
  2389. (const :tag "Yes, do list them" t)
  2390. (const :tag "List them, indented with leading dots" indented)))
  2391. (defcustom org-tags-sort-function nil
  2392. "When set, tags are sorted using this function as a comparator."
  2393. :group 'org-tags
  2394. :type '(choice
  2395. (const :tag "No sorting" nil)
  2396. (const :tag "Alphabetical" string-collate-lessp)
  2397. (const :tag "Reverse alphabetical" org-string-collate-greaterp)
  2398. (function :tag "Custom function" nil)))
  2399. (defvar org-tags-history nil
  2400. "History of minibuffer reads for tags.")
  2401. (defvar org-last-tags-completion-table nil
  2402. "The last used completion table for tags.")
  2403. (defvar org-after-tags-change-hook nil
  2404. "Hook that is run after the tags in a line have changed.")
  2405. (defgroup org-properties nil
  2406. "Options concerning properties in Org mode."
  2407. :tag "Org Properties"
  2408. :group 'org)
  2409. (defcustom org-property-format "%-10s %s"
  2410. "How property key/value pairs should be formatted by `indent-line'.
  2411. When `indent-line' hits a property definition, it will format the line
  2412. according to this format, mainly to make sure that the values are
  2413. lined-up with respect to each other."
  2414. :group 'org-properties
  2415. :type 'string)
  2416. (defcustom org-properties-postprocess-alist nil
  2417. "Alist of properties and functions to adjust inserted values.
  2418. Elements of this alist must be of the form
  2419. ([string] [function])
  2420. where [string] must be a property name and [function] must be a
  2421. lambda expression: this lambda expression must take one argument,
  2422. the value to adjust, and return the new value as a string.
  2423. For example, this element will allow the property \"Remaining\"
  2424. to be updated wrt the relation between the \"Effort\" property
  2425. and the clock summary:
  2426. ((\"Remaining\" (lambda(value)
  2427. (let ((clocksum (org-clock-sum-current-item))
  2428. (effort (org-duration-to-minutes
  2429. (org-entry-get (point) \"Effort\"))))
  2430. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  2431. :group 'org-properties
  2432. :version "24.1"
  2433. :type '(alist :key-type (string :tag "Property")
  2434. :value-type (function :tag "Function")))
  2435. (defcustom org-use-property-inheritance nil
  2436. "Non-nil means properties apply also for sublevels.
  2437. This setting is chiefly used during property searches. Turning it on can
  2438. cause significant overhead when doing a search, which is why it is not
  2439. on by default.
  2440. When nil, only the properties directly given in the current entry count.
  2441. When t, every property is inherited. The value may also be a list of
  2442. properties that should have inheritance, or a regular expression matching
  2443. properties that should be inherited.
  2444. However, note that some special properties use inheritance under special
  2445. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  2446. and the properties ending in \"_ALL\" when they are used as descriptor
  2447. for valid values of a property.
  2448. Note for programmers:
  2449. When querying an entry with `org-entry-get', you can control if inheritance
  2450. should be used. By default, `org-entry-get' looks only at the local
  2451. properties. You can request inheritance by setting the inherit argument
  2452. to t (to force inheritance) or to `selective' (to respect the setting
  2453. in this variable)."
  2454. :group 'org-properties
  2455. :type '(choice
  2456. (const :tag "Not" nil)
  2457. (const :tag "Always" t)
  2458. (repeat :tag "Specific properties" (string :tag "Property"))
  2459. (regexp :tag "Properties matched by regexp")))
  2460. (defun org-property-inherit-p (property)
  2461. "Return a non-nil value if PROPERTY should be inherited."
  2462. (cond
  2463. ((eq org-use-property-inheritance t) t)
  2464. ((not org-use-property-inheritance) nil)
  2465. ((stringp org-use-property-inheritance)
  2466. (string-match org-use-property-inheritance property))
  2467. ((listp org-use-property-inheritance)
  2468. (member-ignore-case property org-use-property-inheritance))
  2469. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  2470. (defcustom org-property-separators nil
  2471. "An alist to control how properties are combined.
  2472. The car of each item should be either a list of property names or
  2473. a regular expression, while the cdr should be the separator to
  2474. use when combining that property.
  2475. If an alist item cannot be found that matches a given property, a
  2476. single space will be used as the separator."
  2477. :group 'org-properties
  2478. :type '(alist :key-type (choice (repeat :tag "Properties" string)
  2479. (string :tag "Regular Expression"))
  2480. :value-type (restricted-sexp :tag "Separator"
  2481. :match-alternatives (stringp)
  2482. :value " ")))
  2483. (defun org--property-get-separator (property)
  2484. "Get the separator to use for combining PROPERTY."
  2485. (or
  2486. (catch 'separator
  2487. (dolist (spec org-property-separators)
  2488. (if (listp (car spec))
  2489. (if (member property (car spec))
  2490. (throw 'separator (cdr spec)))
  2491. (if (string-match-p (car spec) property)
  2492. (throw 'separator (cdr spec))))))
  2493. " "))
  2494. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  2495. "The default column format, if no other format has been defined.
  2496. This variable can be set on the per-file basis by inserting a line
  2497. #+COLUMNS: %25ITEM ....."
  2498. :group 'org-properties
  2499. :type 'string)
  2500. (defcustom org-columns-default-format-for-agenda nil
  2501. "The default column format in an agenda buffer.
  2502. This will be used for column view in the agenda unless a format has
  2503. been set by adding `org-overriding-columns-format' to the local
  2504. settings list of a custom agenda view. When nil, the columns format
  2505. for the first item in the agenda list will be used, or as a fall-back,
  2506. `org-columns-default-format'."
  2507. :group 'org-properties
  2508. :type '(choice
  2509. (const :tag "No default" nil)
  2510. (string :tag "Format string")))
  2511. (defcustom org-columns-ellipses ".."
  2512. "The ellipses to be used when a field in column view is truncated.
  2513. When this is the empty string, as many characters as possible are shown,
  2514. but then there will be no visual indication that the field has been truncated.
  2515. When this is a string of length N, the last N characters of a truncated
  2516. field are replaced by this string. If the column is narrower than the
  2517. ellipses string, only part of the ellipses string will be shown."
  2518. :group 'org-properties
  2519. :type 'string)
  2520. (defconst org-global-properties-fixed
  2521. '(("VISIBILITY_ALL" . "folded children content all")
  2522. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  2523. "List of property/value pairs that can be inherited by any entry.
  2524. These are fixed values, for the preset properties. The user variable
  2525. that can be used to add to this list is `org-global-properties'.
  2526. The entries in this list are cons cells where the car is a property
  2527. name and cdr is a string with the value. If the value represents
  2528. multiple items like an \"_ALL\" property, separate the items by
  2529. spaces.")
  2530. (defcustom org-global-properties nil
  2531. "List of property/value pairs that can be inherited by any entry.
  2532. This list will be combined with the constant `org-global-properties-fixed'.
  2533. The entries in this list are cons cells where the car is a property
  2534. name and cdr is a string with the value.
  2535. Buffer local properties are added either by a document property drawer
  2536. :PROPERTIES:
  2537. :NAME: VALUE
  2538. :END:
  2539. or by adding lines like
  2540. #+PROPERTY: NAME VALUE"
  2541. :group 'org-properties
  2542. :type '(repeat
  2543. (cons (string :tag "Property")
  2544. (string :tag "Value"))))
  2545. (defvar-local org-keyword-properties nil
  2546. "List of property/value pairs inherited by any entry.
  2547. Valid for the current buffer. This variable is populated from
  2548. PROPERTY keywords.
  2549. Note that properties are defined also in property drawers.
  2550. Properties defined there take precedence over properties defined
  2551. as keywords.")
  2552. (defgroup org-agenda nil
  2553. "Options concerning agenda views in Org mode."
  2554. :tag "Org Agenda"
  2555. :group 'org)
  2556. (defvar-local org-category nil
  2557. "Variable used by Org files to set a category for agenda display.
  2558. There are multiple ways to set the category. One way is to set
  2559. it in the document property drawer. For example:
  2560. :PROPERTIES:
  2561. :CATEGORY: ELisp
  2562. :END:
  2563. Other ways to define it is as an Emacs file variable, for example
  2564. # -*- mode: org; org-category: \"ELisp\"
  2565. or for the file to contain a special line:
  2566. #+CATEGORY: ELisp
  2567. If the file does not specify a category, then file's base name
  2568. is used instead.")
  2569. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  2570. (defcustom org-agenda-files nil
  2571. "The files to be used for agenda display.
  2572. If an entry is a directory, all files in that directory that are matched
  2573. by `org-agenda-file-regexp' will be part of the file list.
  2574. If the value of the variable is not a list but a single file name, then
  2575. the list of agenda files is actually stored and maintained in that file,
  2576. one agenda file per line. In this file paths can be given relative to
  2577. `org-directory'. Tilde expansion and environment variable substitution
  2578. are also made.
  2579. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  2580. and removed with `\\[org-remove-file]'."
  2581. :group 'org-agenda
  2582. :type '(choice
  2583. (repeat :tag "List of files and directories" file)
  2584. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  2585. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  2586. "Regular expression to match files for `org-agenda-files'.
  2587. If any element in the list in that variable contains a directory instead
  2588. of a normal file, all files in that directory that are matched by this
  2589. regular expression will be included."
  2590. :group 'org-agenda
  2591. :type 'regexp)
  2592. (defvaralias 'org-agenda-multi-occur-extra-files
  2593. 'org-agenda-text-search-extra-files)
  2594. (defcustom org-agenda-text-search-extra-files nil
  2595. "List of extra files to be searched by text search commands.
  2596. These files will be searched in addition to the agenda files by the
  2597. commands `org-search-view' (`\\[org-agenda] s') \
  2598. and `org-occur-in-agenda-files'.
  2599. Note that these files will only be searched for text search commands,
  2600. not for the other agenda views like todo lists, tag searches or the weekly
  2601. agenda. This variable is intended to list notes and possibly archive files
  2602. that should also be searched by these two commands.
  2603. In fact, if the first element in the list is the symbol `agenda-archives',
  2604. then all archive files of all agenda files will be added to the search
  2605. scope."
  2606. :group 'org-agenda
  2607. :type '(set :greedy t
  2608. (const :tag "Agenda Archives" agenda-archives)
  2609. (repeat :inline t (file))))
  2610. (defcustom org-agenda-skip-unavailable-files nil
  2611. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  2612. A nil value means to remove them, after a query, from the list."
  2613. :group 'org-agenda
  2614. :type 'boolean)
  2615. (defgroup org-latex nil
  2616. "Options for embedding LaTeX code into Org mode."
  2617. :tag "Org LaTeX"
  2618. :group 'org)
  2619. (defcustom org-format-latex-options
  2620. '(:foreground default :background default :scale 1.0
  2621. :html-foreground "Black" :html-background "Transparent"
  2622. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  2623. "Options for creating images from LaTeX fragments.
  2624. This is a property list with the following properties:
  2625. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  2626. `default' means use the foreground of the default face.
  2627. `auto' means use the foreground from the text face.
  2628. :background the background color, or \"Transparent\".
  2629. `default' means use the background of the default face.
  2630. `auto' means use the background from the text face.
  2631. :scale a scaling factor for the size of the images, to get more pixels
  2632. :html-foreground, :html-background, :html-scale
  2633. the same numbers for HTML export.
  2634. :matchers a list indicating which matchers should be used to
  2635. find LaTeX fragments. Valid members of this list are:
  2636. \"begin\" find environments
  2637. \"$1\" find single characters surrounded by $.$
  2638. \"$\" find math expressions surrounded by $...$
  2639. \"$$\" find math expressions surrounded by $$....$$
  2640. \"\\(\" find math expressions surrounded by \\(...\\)
  2641. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  2642. :group 'org-latex
  2643. :type 'plist)
  2644. (defcustom org-format-latex-signal-error t
  2645. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  2646. When nil, just push out a message."
  2647. :group 'org-latex
  2648. :version "24.1"
  2649. :type 'boolean)
  2650. (defcustom org-latex-to-mathml-jar-file nil
  2651. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  2652. Use this to specify additional executable file say a jar file.
  2653. When using MathToWeb as the converter, specify the full-path to
  2654. your mathtoweb.jar file."
  2655. :group 'org-latex
  2656. :version "24.1"
  2657. :type '(choice
  2658. (const :tag "None" nil)
  2659. (file :tag "JAR file" :must-match t)))
  2660. (defcustom org-latex-to-mathml-convert-command nil
  2661. "Command to convert LaTeX fragments to MathML.
  2662. Replace format-specifiers in the command as noted below and use
  2663. `shell-command' to convert LaTeX to MathML.
  2664. %j: Executable file in fully expanded form as specified by
  2665. `org-latex-to-mathml-jar-file'.
  2666. %I: Input LaTeX file in fully expanded form.
  2667. %i: The latex fragment to be converted.
  2668. %o: Output MathML file.
  2669. This command is used by `org-create-math-formula'.
  2670. When using MathToWeb as the converter, set this option to
  2671. \"java -jar %j -unicode -force -df %o %I\".
  2672. When using LaTeXML set this option to
  2673. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  2674. :group 'org-latex
  2675. :version "24.1"
  2676. :type '(choice
  2677. (const :tag "None" nil)
  2678. (string :tag "\nShell command")))
  2679. (defcustom org-latex-to-html-convert-command nil
  2680. "Command to convert LaTeX fragments to HTML.
  2681. This command is very open-ended: the output of the command will
  2682. directly replace the LaTeX fragment in the resulting HTML.
  2683. Replace format-specifiers in the command as noted below and use
  2684. `shell-command' to convert LaTeX to HTML.
  2685. %i: The LaTeX fragment to be converted.
  2686. For example, this could be used with LaTeXML as
  2687. \"latexmlc \\='literal:%i\\=' --profile=math --preload=siunitx.sty 2>/dev/null\"."
  2688. :group 'org-latex
  2689. :package-version '(Org . "9.4")
  2690. :type '(choice
  2691. (const :tag "None" nil)
  2692. (string :tag "Shell command")))
  2693. (defcustom org-preview-latex-default-process 'dvipng
  2694. "The default process to convert LaTeX fragments to image files.
  2695. All available processes and theirs documents can be found in
  2696. `org-preview-latex-process-alist', which see."
  2697. :group 'org-latex
  2698. :version "26.1"
  2699. :package-version '(Org . "9.0")
  2700. :type 'symbol)
  2701. (defcustom org-preview-latex-process-alist
  2702. '((dvipng
  2703. :programs ("latex" "dvipng")
  2704. :description "dvi > png"
  2705. :message "you need to install the programs: latex and dvipng."
  2706. :image-input-type "dvi"
  2707. :image-output-type "png"
  2708. :image-size-adjust (1.0 . 1.0)
  2709. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2710. :image-converter ("dvipng -D %D -T tight -o %O %f")
  2711. :transparent-image-converter
  2712. ("dvipng -D %D -T tight -bg Transparent -o %O %f"))
  2713. (dvisvgm
  2714. :programs ("latex" "dvisvgm")
  2715. :description "dvi > svg"
  2716. :message "you need to install the programs: latex and dvisvgm."
  2717. :image-input-type "dvi"
  2718. :image-output-type "svg"
  2719. :image-size-adjust (1.7 . 1.5)
  2720. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2721. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  2722. (imagemagick
  2723. :programs ("latex" "convert")
  2724. :description "pdf > png"
  2725. :message "you need to install the programs: latex and imagemagick."
  2726. :image-input-type "pdf"
  2727. :image-output-type "png"
  2728. :image-size-adjust (1.0 . 1.0)
  2729. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  2730. :image-converter
  2731. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  2732. "Definitions of external processes for LaTeX previewing.
  2733. Org mode can use some external commands to generate TeX snippet's images for
  2734. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  2735. `org-create-formula-image' how to call them.
  2736. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  2737. PROPERTIES accepts the following attributes:
  2738. :programs list of strings, required programs.
  2739. :description string, describe the process.
  2740. :message string, message it when required programs cannot be found.
  2741. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  2742. :image-output-type string, output file type of image converter (e.g., \"png\").
  2743. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  2744. image size showed in buffer and the cdr element is for
  2745. HTML file. This option is only useful for process
  2746. developers, users should use variable
  2747. `org-format-latex-options' instead.
  2748. :post-clean list of strings, files matched are to be cleaned up once
  2749. the image is generated. When nil, the files with \".dvi\",
  2750. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  2751. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  2752. be cleaned up.
  2753. :latex-header list of strings, the LaTeX header of the snippet file.
  2754. When nil, the fallback value is used instead, which is
  2755. controlled by `org-format-latex-header',
  2756. `org-latex-default-packages-alist' and
  2757. `org-latex-packages-alist', which see.
  2758. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  2759. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  2760. replaced with values defined below.
  2761. :image-converter list of image converter commands strings. Each of them is
  2762. given to the shell and supports any of the following
  2763. place-holders defined below.
  2764. If set, :transparent-image-converter is used instead of :image-converter to
  2765. convert an image when the background color is nil or \"Transparent\".
  2766. Place-holders used by `:image-converter' and `:latex-compiler':
  2767. %f input file name
  2768. %b base name of input file
  2769. %o base directory of input file
  2770. %O absolute output file name
  2771. Place-holders only used by `:image-converter':
  2772. %D dpi, which is used to adjust image size by some processing commands.
  2773. %S the image size scale ratio, which is used to adjust image size by some
  2774. processing commands."
  2775. :group 'org-latex
  2776. :version "26.1"
  2777. :package-version '(Org . "9.0")
  2778. :type '(alist :tag "LaTeX to image backends"
  2779. :value-type (plist)))
  2780. (defcustom org-preview-latex-image-directory "ltximg/"
  2781. "Path to store latex preview images.
  2782. A relative path here creates many directories relative to the
  2783. processed Org files paths. An absolute path puts all preview
  2784. images at the same place."
  2785. :group 'org-latex
  2786. :version "26.1"
  2787. :package-version '(Org . "9.0")
  2788. :type 'string)
  2789. (defun org-format-latex-mathml-available-p ()
  2790. "Return t if `org-latex-to-mathml-convert-command' is usable."
  2791. (save-match-data
  2792. (when (and (boundp 'org-latex-to-mathml-convert-command)
  2793. org-latex-to-mathml-convert-command)
  2794. (let ((executable (car (split-string
  2795. org-latex-to-mathml-convert-command))))
  2796. (when (executable-find executable)
  2797. (if (string-match
  2798. "%j" org-latex-to-mathml-convert-command)
  2799. (file-readable-p org-latex-to-mathml-jar-file)
  2800. t))))))
  2801. (defcustom org-format-latex-header "\\documentclass{article}
  2802. \\usepackage[usenames]{color}
  2803. \[DEFAULT-PACKAGES]
  2804. \[PACKAGES]
  2805. \\pagestyle{empty} % do not remove
  2806. % The settings below are copied from fullpage.sty
  2807. \\setlength{\\textwidth}{\\paperwidth}
  2808. \\addtolength{\\textwidth}{-3cm}
  2809. \\setlength{\\oddsidemargin}{1.5cm}
  2810. \\addtolength{\\oddsidemargin}{-2.54cm}
  2811. \\setlength{\\evensidemargin}{\\oddsidemargin}
  2812. \\setlength{\\textheight}{\\paperheight}
  2813. \\addtolength{\\textheight}{-\\headheight}
  2814. \\addtolength{\\textheight}{-\\headsep}
  2815. \\addtolength{\\textheight}{-\\footskip}
  2816. \\addtolength{\\textheight}{-3cm}
  2817. \\setlength{\\topmargin}{1.5cm}
  2818. \\addtolength{\\topmargin}{-2.54cm}"
  2819. "The document header used for processing LaTeX fragments.
  2820. It is imperative that this header make sure that no page number
  2821. appears on the page. The package defined in the variables
  2822. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  2823. will either replace the placeholder \"[PACKAGES]\" in this
  2824. header, or they will be appended."
  2825. :group 'org-latex
  2826. :type 'string)
  2827. (defun org-set-packages-alist (var val)
  2828. "Set the packages alist and make sure it has 3 elements per entry."
  2829. (set-default-toplevel-value var (mapcar (lambda (x)
  2830. (if (and (consp x) (= (length x) 2))
  2831. (list (car x) (nth 1 x) t)
  2832. x))
  2833. val)))
  2834. (defun org-get-packages-alist (var)
  2835. "Get the packages alist and make sure it has 3 elements per entry."
  2836. (mapcar (lambda (x)
  2837. (if (and (consp x) (= (length x) 2))
  2838. (list (car x) (nth 1 x) t)
  2839. x))
  2840. (default-value var)))
  2841. (defcustom org-latex-default-packages-alist
  2842. '(("AUTO" "inputenc" t ("pdflatex"))
  2843. ("T1" "fontenc" t ("pdflatex"))
  2844. ("" "graphicx" t)
  2845. ("" "longtable" nil)
  2846. ("" "wrapfig" nil)
  2847. ("" "rotating" nil)
  2848. ("normalem" "ulem" t)
  2849. ("" "amsmath" t)
  2850. ("" "amssymb" t)
  2851. ("" "capt-of" nil)
  2852. ("" "hyperref" nil))
  2853. "Alist of default packages to be inserted in the header.
  2854. Change this only if one of the packages here causes an
  2855. incompatibility with another package you are using.
  2856. The packages in this list are needed by one part or another of
  2857. Org mode to function properly:
  2858. - inputenc, fontenc: for basic font and character selection
  2859. - graphicx: for including images
  2860. - longtable: For multipage tables
  2861. - wrapfig: for figure placement
  2862. - rotating: for sideways figures and tables
  2863. - ulem: for underline and strike-through
  2864. - amsmath: for subscript and superscript and math environments
  2865. - amssymb: for various symbols used for interpreting the entities
  2866. in `org-entities'. You can skip some of this package if you don't
  2867. use any of the symbols.
  2868. - capt-of: for captions outside of floats
  2869. - hyperref: for cross references
  2870. Therefore you should not modify this variable unless you know
  2871. what you are doing. The one reason to change it anyway is that
  2872. you might be loading some other package that conflicts with one
  2873. of the default packages. Each element is either a cell or
  2874. a string.
  2875. A cell is of the format
  2876. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  2877. If SNIPPET-FLAG is non-nil, the package also needs to be included
  2878. when compiling LaTeX snippets into images for inclusion into
  2879. non-LaTeX output.
  2880. COMPILERS is a list of compilers that should include the package,
  2881. see `org-latex-compiler'. If the document compiler is not in the
  2882. list, and the list is non-nil, the package will not be inserted
  2883. in the final document.
  2884. A string will be inserted as-is in the header of the document."
  2885. :group 'org-latex
  2886. :group 'org-export-latex
  2887. :set 'org-set-packages-alist
  2888. :get 'org-get-packages-alist
  2889. :version "26.1"
  2890. :package-version '(Org . "8.3")
  2891. :type '(repeat
  2892. (choice
  2893. (list :tag "options/package pair"
  2894. (string :tag "options")
  2895. (string :tag "package")
  2896. (boolean :tag "Snippet")
  2897. (choice
  2898. (const :tag "For all compilers" nil)
  2899. (repeat :tag "Allowed compiler" string)))
  2900. (string :tag "A line of LaTeX"))))
  2901. (defcustom org-latex-packages-alist nil
  2902. "Alist of packages to be inserted in every LaTeX header.
  2903. These will be inserted after `org-latex-default-packages-alist'.
  2904. Each element is either a cell or a string.
  2905. A cell is of the format:
  2906. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  2907. SNIPPET-FLAG, when non-nil, indicates that this package is also
  2908. needed when turning LaTeX snippets into images for inclusion into
  2909. non-LaTeX output.
  2910. COMPILERS is a list of compilers that should include the package,
  2911. see `org-latex-compiler'. If the document compiler is not in the
  2912. list, and the list is non-nil, the package will not be inserted
  2913. in the final document.
  2914. A string will be inserted as-is in the header of the document.
  2915. Make sure that you only list packages here which:
  2916. - you want in every file;
  2917. - do not conflict with the setup in `org-format-latex-header';
  2918. - do not conflict with the default packages in
  2919. `org-latex-default-packages-alist'."
  2920. :group 'org-latex
  2921. :group 'org-export-latex
  2922. :set 'org-set-packages-alist
  2923. :get 'org-get-packages-alist
  2924. :type '(repeat
  2925. (choice
  2926. (list :tag "options/package pair"
  2927. (string :tag "options")
  2928. (string :tag "package")
  2929. (boolean :tag "Snippet"))
  2930. (string :tag "A line of LaTeX"))))
  2931. (defgroup org-appearance nil
  2932. "Settings for Org mode appearance."
  2933. :tag "Org Appearance"
  2934. :group 'org)
  2935. (defcustom org-level-color-stars-only nil
  2936. "Non-nil means fontify only the stars in each headline.
  2937. When nil, the entire headline is fontified.
  2938. Changing it requires restart of `font-lock-mode' to become effective
  2939. also in regions already fontified."
  2940. :group 'org-appearance
  2941. :type 'boolean)
  2942. (defcustom org-hide-leading-stars nil
  2943. "Non-nil means hide the first N-1 stars in a headline.
  2944. This works by using the face `org-hide' for these stars. This
  2945. face is white for a light background, and black for a dark
  2946. background. You may have to customize the face `org-hide' to
  2947. make this work.
  2948. Changing it requires restart of `font-lock-mode' to become effective
  2949. also in regions already fontified.
  2950. You may also set this on a per-file basis by adding one of the following
  2951. lines to the buffer:
  2952. #+STARTUP: hidestars
  2953. #+STARTUP: showstars"
  2954. :group 'org-appearance
  2955. :type 'boolean)
  2956. (defcustom org-hidden-keywords nil
  2957. "List of symbols corresponding to keywords to be hidden in the Org buffer.
  2958. For example, a value \\='(title) for this list makes the document's title
  2959. appear in the buffer without the initial \"#+TITLE:\" part."
  2960. :group 'org-appearance
  2961. :package-version '(Org . "9.5")
  2962. :type '(set (const :tag "#+AUTHOR" author)
  2963. (const :tag "#+DATE" date)
  2964. (const :tag "#+EMAIL" email)
  2965. (const :tag "#+SUBTITLE" subtitle)
  2966. (const :tag "#+TITLE" title)))
  2967. (defcustom org-custom-properties nil
  2968. "List of properties (as strings) with a special meaning.
  2969. The default use of these custom properties is to let the user
  2970. hide them with `org-toggle-custom-properties-visibility'."
  2971. :group 'org-properties
  2972. :group 'org-appearance
  2973. :version "24.3"
  2974. :type '(repeat (string :tag "Property Name")))
  2975. (defcustom org-fontify-todo-headline nil
  2976. "Non-nil means change the face of a headline if it is marked as TODO.
  2977. Normally, only the TODO/DONE keyword indicates the state of a headline.
  2978. When this is non-nil, the headline after the keyword is set to the
  2979. `org-headline-todo' as an additional indication."
  2980. :group 'org-appearance
  2981. :package-version '(Org . "9.4")
  2982. :type 'boolean
  2983. :safe #'booleanp)
  2984. (defcustom org-fontify-done-headline t
  2985. "Non-nil means change the face of a headline if it is marked DONE.
  2986. Normally, only the TODO/DONE keyword indicates the state of a headline.
  2987. When this is non-nil, the headline after the keyword is set to the
  2988. `org-headline-done' as an additional indication."
  2989. :group 'org-appearance
  2990. :package-version '(Org . "9.4")
  2991. :type 'boolean)
  2992. (defcustom org-fontify-emphasized-text t
  2993. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  2994. Changing this variable requires a restart of Emacs to take effect."
  2995. :group 'org-appearance
  2996. :type 'boolean)
  2997. (defcustom org-fontify-whole-heading-line nil
  2998. "Non-nil means fontify the whole line for headings.
  2999. This is useful when setting a background color for the
  3000. org-level-* faces."
  3001. :group 'org-appearance
  3002. :type 'boolean)
  3003. (defcustom org-fontify-whole-block-delimiter-line t
  3004. "Non-nil means fontify the whole line for begin/end lines of blocks.
  3005. This is useful when setting a background color for the
  3006. org-block-begin-line and org-block-end-line faces."
  3007. :group 'org-appearance
  3008. :type 'boolean)
  3009. (defcustom org-highlight-latex-and-related nil
  3010. "Non-nil means highlight LaTeX related syntax in the buffer.
  3011. When non-nil, the value should be a list containing any of the
  3012. following symbols:
  3013. `native' Highlight LaTeX snippets and environments natively.
  3014. `latex' Highlight LaTeX snippets and environments.
  3015. `script' Highlight subscript and superscript.
  3016. `entities' Highlight entities."
  3017. :group 'org-appearance
  3018. :version "24.4"
  3019. :package-version '(Org . "8.0")
  3020. :type '(choice
  3021. (const :tag "No highlighting" nil)
  3022. (set :greedy t :tag "Highlight"
  3023. (const :tag "LaTeX snippets and environments (native)" native)
  3024. (const :tag "LaTeX snippets and environments" latex)
  3025. (const :tag "Subscript and superscript" script)
  3026. (const :tag "Entities" entities))))
  3027. (defcustom org-hide-emphasis-markers nil
  3028. "Non-nil mean font-lock should hide the emphasis marker characters."
  3029. :group 'org-appearance
  3030. :type 'boolean
  3031. :safe #'booleanp)
  3032. (defcustom org-hide-macro-markers nil
  3033. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3034. :group 'org-appearance
  3035. :type 'boolean)
  3036. (defcustom org-pretty-entities nil
  3037. "Non-nil means show entities as UTF8 characters.
  3038. When nil, the \\name form remains in the buffer."
  3039. :group 'org-appearance
  3040. :version "24.1"
  3041. :type 'boolean)
  3042. (defcustom org-pretty-entities-include-sub-superscripts t
  3043. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3044. :group 'org-appearance
  3045. :version "24.1"
  3046. :type 'boolean)
  3047. (defvar org-emph-re nil
  3048. "Regular expression for matching emphasis.
  3049. After a match, the match groups contain these elements:
  3050. 0 The match of the full regular expression, including the characters
  3051. before and after the proper match
  3052. 1 The character before the proper match, or empty at beginning of line
  3053. 2 The proper match, including the leading and trailing markers
  3054. 3 The leading marker like * or /, indicating the type of highlighting
  3055. 4 The text between the emphasis markers, not including the markers
  3056. 5 The character after the match, empty at the end of a line")
  3057. (defvar org-verbatim-re nil
  3058. "Regular expression for matching verbatim text.")
  3059. (defvar org-emphasis-regexp-components) ; defined just below
  3060. (defvar org-emphasis-alist) ; defined just below
  3061. (defun org-set-emph-re (var val)
  3062. "Set variable and compute the emphasis regular expression."
  3063. (set-default-toplevel-value var val)
  3064. (when (and (boundp 'org-emphasis-alist)
  3065. (boundp 'org-emphasis-regexp-components)
  3066. org-emphasis-alist org-emphasis-regexp-components)
  3067. (pcase-let*
  3068. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3069. (body (if (<= nl 0) body
  3070. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3071. (template
  3072. (format (concat "\\([%s]\\|^\\)" ;before markers
  3073. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3074. "\\([%s]\\|$\\)") ;after markers
  3075. pre border border body border post)))
  3076. (setq org-emph-re (format template "*/_+"))
  3077. (setq org-verbatim-re (format template "=~")))))
  3078. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3079. ;; set this option proved cumbersome. See this message/thread:
  3080. ;; https://orgmode.org/list/B72CDC2B-72F6-43A8-AC70-E6E6295766EC@gmail.com
  3081. (defvar org-emphasis-regexp-components
  3082. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3083. "Components used to build the regular expression for emphasis.
  3084. This is a list with five entries. Terminology: In an emphasis string
  3085. like \" *strong word* \", we call the initial space PREMATCH, the final
  3086. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3087. and \"trong wor\" is the body. The different components in this variable
  3088. specify what is allowed/forbidden in each part:
  3089. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3090. post Chars allowed as postmatch. End of line will be allowed too.
  3091. border The chars *forbidden* as border characters.
  3092. body-regexp A regexp like \".\" to match a body character. Don't use
  3093. non-shy groups here, and don't allow newline here.
  3094. newline The maximum number of newlines allowed in an emphasis exp.
  3095. You need to reload Org or to restart Emacs after setting this.")
  3096. (defcustom org-emphasis-alist
  3097. '(("*" bold)
  3098. ("/" italic)
  3099. ("_" underline)
  3100. ("=" org-verbatim verbatim)
  3101. ("~" org-code verbatim)
  3102. ("+" (:strike-through t)))
  3103. "Alist of characters and faces to emphasize text.
  3104. Text starting and ending with a special character will be emphasized,
  3105. for example *bold*, _underlined_ and /italic/. This variable sets the
  3106. marker characters and the face to be used by font-lock for highlighting
  3107. in Org buffers.
  3108. You need to reload Org or to restart Emacs after customizing this."
  3109. :group 'org-appearance
  3110. :set 'org-set-emph-re
  3111. :version "24.4"
  3112. :package-version '(Org . "8.0")
  3113. :type '(repeat
  3114. (list
  3115. (string :tag "Marker character")
  3116. (choice
  3117. (face :tag "Font-lock-face")
  3118. (plist :tag "Face property list"))
  3119. (option (const verbatim)))))
  3120. (defvar org-protecting-blocks '("src" "example" "export")
  3121. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3122. This is needed for font-lock setup.")
  3123. ;;; Functions and variables from their packages
  3124. ;; Declared here to avoid compiler warnings
  3125. (defvar mark-active)
  3126. ;; Various packages
  3127. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3128. (declare-function calendar-forward-day "cal-move" (arg))
  3129. (declare-function calendar-goto-date "cal-move" (date))
  3130. (declare-function calendar-goto-today "cal-move" ())
  3131. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3132. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3133. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3134. (declare-function cdlatex-tab "ext:cdlatex" ())
  3135. (declare-function dired-get-filename
  3136. "dired"
  3137. (&optional localp no-error-if-not-filep))
  3138. (declare-function iswitchb-read-buffer
  3139. "iswitchb"
  3140. (prompt &optional
  3141. default require-match _predicate start matches-set))
  3142. (declare-function org-agenda-change-all-lines
  3143. "org-agenda"
  3144. (newhead hdmarker &optional fixface just-this))
  3145. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3146. "org-agenda"
  3147. (&optional end))
  3148. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3149. (declare-function org-agenda-format-item
  3150. "org-agenda"
  3151. (extra txt &optional level category tags dotime
  3152. remove-re habitp))
  3153. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3154. (declare-function org-agenda-save-markers-for-cut-and-paste
  3155. "org-agenda"
  3156. (beg end))
  3157. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3158. (declare-function org-agenda-skip "org-agenda" (&optional element))
  3159. (declare-function org-attach-expand "org-attach" (file))
  3160. (declare-function org-attach-reveal "org-attach" ())
  3161. (declare-function org-attach-reveal-in-emacs "org-attach" ())
  3162. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3163. (declare-function org-indent-mode "org-indent" (&optional arg))
  3164. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3165. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3166. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3167. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3168. (declare-function parse-time-string "parse-time" (string))
  3169. (defvar align-mode-rules-list)
  3170. (defvar calc-embedded-close-formula)
  3171. (defvar calc-embedded-open-formula)
  3172. (defvar calc-embedded-open-mode)
  3173. (defvar font-lock-unfontify-region-function)
  3174. (defvar iswitchb-temp-buflist)
  3175. (defvar org-agenda-tags-todo-honor-ignore-options)
  3176. (defvar remember-data-file)
  3177. (defvar texmathp-why)
  3178. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3179. (declare-function org-clock-update-mode-line "org-clock" (&optional refresh))
  3180. (declare-function org-resolve-clocks "org-clock"
  3181. (&optional also-non-dangling-p prompt last-valid))
  3182. (defvar org-clock-start-time)
  3183. (defvar org-clock-marker (make-marker)
  3184. "Marker recording the last clock-in.")
  3185. (defvar org-clock-hd-marker (make-marker)
  3186. "Marker recording the last clock-in, but the headline position.")
  3187. (defvar org-clock-heading ""
  3188. "The heading of the current clock entry.")
  3189. (defun org-clocking-buffer ()
  3190. "Return the buffer where the clock is currently running.
  3191. Return nil if no clock is running."
  3192. (marker-buffer org-clock-marker))
  3193. (defalias 'org-clock-is-active #'org-clocking-buffer)
  3194. (defun org-check-running-clock ()
  3195. "Check if the current buffer contains the running clock.
  3196. If yes, offer to stop it and to save the buffer with the changes."
  3197. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3198. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3199. (buffer-name))))
  3200. (org-clock-out)
  3201. (when (y-or-n-p "Save changed buffer?")
  3202. (save-buffer))))
  3203. (defun org-clocktable-try-shift (dir n)
  3204. "Check if this line starts a clock table, if yes, shift the time block."
  3205. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3206. (org-clocktable-shift dir n)))
  3207. ;;;###autoload
  3208. (defun org-clock-persistence-insinuate ()
  3209. "Set up hooks for clock persistence."
  3210. (require 'org-clock)
  3211. (add-hook 'org-mode-hook 'org-clock-load)
  3212. (add-hook 'kill-emacs-hook 'org-clock-save))
  3213. (defun org-clock-auto-clockout-insinuate ()
  3214. "Set up hook for auto clocking out when Emacs is idle.
  3215. See `org-clock-auto-clockout-timer'.
  3216. This function is meant to be added to the user configuration."
  3217. (require 'org-clock)
  3218. (add-hook 'org-clock-in-hook #'org-clock-auto-clockout t))
  3219. (defgroup org-archive nil
  3220. "Options concerning archiving in Org mode."
  3221. :tag "Org Archive"
  3222. :group 'org-structure)
  3223. (defcustom org-archive-location "%s_archive::"
  3224. "The location where subtrees should be archived.
  3225. The value of this variable is a string, consisting of two parts,
  3226. separated by a double-colon. The first part is a filename and
  3227. the second part is a headline.
  3228. When the filename is omitted, archiving happens in the same file.
  3229. %s in the filename will be replaced by the current file
  3230. name (without the directory part). Archiving to a different file
  3231. is useful to keep archived entries from contributing to the
  3232. Org Agenda.
  3233. The archived entries will be filed as subtrees of the specified
  3234. headline. When the headline is omitted, the subtrees are simply
  3235. filed away at the end of the file, as top-level entries. Also in
  3236. the heading you can use %s to represent the file name, this can be
  3237. useful when using the same archive for a number of different files.
  3238. Here are a few examples:
  3239. \"%s_archive::\"
  3240. If the current file is Projects.org, archive in file
  3241. Projects.org_archive, as top-level trees. This is the default.
  3242. \"::* Archived Tasks\"
  3243. Archive in the current file, under the top-level headline
  3244. \"* Archived Tasks\".
  3245. \"~/org/archive.org::\"
  3246. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3247. \"~/org/archive.org::* From %s\"
  3248. Archive in file ~/org/archive.org (absolute path), under headlines
  3249. \"From FILENAME\" where file name is the current file name.
  3250. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3251. The \"datetree/\" string is special, signifying to archive
  3252. items to the datetree. Items are placed in either the CLOSED
  3253. date of the item, or the current date if there is no CLOSED date.
  3254. The heading will be a subentry to the current date. There doesn't
  3255. need to be a heading, but there always needs to be a slash after
  3256. datetree. For example, to store archived items directly in the
  3257. datetree, use \"~/org/datetree.org::datetree/\".
  3258. \"basement::** Finished Tasks\"
  3259. Archive in file ./basement (relative path), as level 3 trees
  3260. below the level 2 heading \"** Finished Tasks\".
  3261. You may define it locally by setting an ARCHIVE property. If
  3262. such a property is found in the file or in an entry, and anywhere
  3263. up the hierarchy, it will be used.
  3264. You can also set it for the whole file using the keyword-syntax:
  3265. #+ARCHIVE: basement::** Finished Tasks"
  3266. :group 'org-archive
  3267. :type 'string)
  3268. (defcustom org-agenda-skip-archived-trees t
  3269. "Non-nil means the agenda will skip any items located in archived trees.
  3270. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3271. variable is no longer recommended, you should leave it at the value t.
  3272. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3273. :group 'org-archive
  3274. :group 'org-agenda-skip
  3275. :type 'boolean)
  3276. (defcustom org-columns-skip-archived-trees t
  3277. "Non-nil means ignore archived trees when creating column view."
  3278. :group 'org-archive
  3279. :group 'org-properties
  3280. :type 'boolean)
  3281. (defcustom org-sparse-tree-open-archived-trees nil
  3282. "Non-nil means sparse tree construction shows matches in archived trees.
  3283. When nil, matches in these trees are highlighted, but the trees are kept in
  3284. collapsed state."
  3285. :group 'org-archive
  3286. :group 'org-sparse-trees
  3287. :type 'boolean)
  3288. (defcustom org-sparse-tree-default-date-type nil
  3289. "The default date type when building a sparse tree.
  3290. When this is nil, a date is a scheduled or a deadline timestamp.
  3291. Otherwise, these types are allowed:
  3292. all: all timestamps
  3293. active: only active timestamps (<...>)
  3294. inactive: only inactive timestamps ([...])
  3295. scheduled: only scheduled timestamps
  3296. deadline: only deadline timestamps"
  3297. :type '(choice (const :tag "Scheduled or deadline" nil)
  3298. (const :tag "All timestamps" all)
  3299. (const :tag "Only active timestamps" active)
  3300. (const :tag "Only inactive timestamps" inactive)
  3301. (const :tag "Only scheduled timestamps" scheduled)
  3302. (const :tag "Only deadline timestamps" deadline)
  3303. (const :tag "Only closed timestamps" closed))
  3304. :version "26.1"
  3305. :package-version '(Org . "8.3")
  3306. :group 'org-sparse-trees)
  3307. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  3308. ;; Declare Column View Code
  3309. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  3310. (declare-function org-columns-compute "org-colview" (property))
  3311. ;; Declare ID code
  3312. (declare-function org-id-store-link "org-id")
  3313. (declare-function org-id-locations-load "org-id")
  3314. (declare-function org-id-locations-save "org-id")
  3315. (defvar org-id-track-globally)
  3316. ;;; Variables for pre-computed regular expressions, all buffer local
  3317. (defvar-local org-todo-regexp nil
  3318. "Matches any of the TODO state keywords.
  3319. Since TODO keywords are case-sensitive, `case-fold-search' is
  3320. expected to be bound to nil when matching against this regexp.")
  3321. (defvar-local org-not-done-regexp nil
  3322. "Matches any of the TODO state keywords except the last one.
  3323. Since TODO keywords are case-sensitive, `case-fold-search' is
  3324. expected to be bound to nil when matching against this regexp.")
  3325. (defvar-local org-not-done-heading-regexp nil
  3326. "Matches a TODO headline that is not done.
  3327. Since TODO keywords are case-sensitive, `case-fold-search' is
  3328. expected to be bound to nil when matching against this regexp.")
  3329. (defvar-local org-todo-line-regexp nil
  3330. "Matches a headline and puts TODO state into group 2 if present.
  3331. Since TODO keywords are case-sensitive, `case-fold-search' is
  3332. expected to be bound to nil when matching against this regexp.")
  3333. (defvar-local org-complex-heading-regexp nil
  3334. "Matches a headline and puts everything into groups:
  3335. group 1: Stars
  3336. group 2: The TODO keyword, maybe
  3337. group 3: Priority cookie
  3338. group 4: True headline
  3339. group 5: Tags
  3340. Since TODO keywords are case-sensitive, `case-fold-search' is
  3341. expected to be bound to nil when matching against this regexp.")
  3342. (defvar-local org-complex-heading-regexp-format nil
  3343. "Printf format to make regexp to match an exact headline.
  3344. This regexp will match the headline of any node which has the
  3345. exact headline text that is put into the format, but may have any
  3346. TODO state, priority, tags, statistics cookies (at the beginning
  3347. or end of the headline title), or COMMENT keyword.")
  3348. (defvar-local org-todo-line-tags-regexp nil
  3349. "Matches a headline and puts TODO state into group 2 if present.
  3350. Also put tags into group 4 if tags are present.")
  3351. (defconst org-plain-time-of-day-regexp
  3352. (concat
  3353. "\\(\\<[012]?[0-9]"
  3354. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3355. "\\(--?"
  3356. "\\(\\<[012]?[0-9]"
  3357. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3358. "\\)?")
  3359. "Regular expression to match a plain time or time range.
  3360. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3361. groups carry important information:
  3362. 0 the full match
  3363. 1 the first time, range or not
  3364. 8 the second time, if it is a range.")
  3365. (defconst org-plain-time-extension-regexp
  3366. (concat
  3367. "\\(\\<[012]?[0-9]"
  3368. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3369. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  3370. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  3371. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3372. groups carry important information:
  3373. 0 the full match
  3374. 7 hours of duration
  3375. 9 minutes of duration")
  3376. (defconst org-stamp-time-of-day-regexp
  3377. (concat
  3378. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  3379. "\\([012][0-9]:[0-5][0-9]\\)\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?>"
  3380. "\\(--?"
  3381. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  3382. "Regular expression to match a timestamp time or time range.
  3383. After a match, the following groups carry important information:
  3384. 0 the full match
  3385. 1 date plus weekday, for back referencing to make sure
  3386. both times are on the same day
  3387. 2 the first time, range or not
  3388. 4 the second time, if it is a range.")
  3389. (defconst org-startup-options
  3390. '(("fold" org-startup-folded t)
  3391. ("overview" org-startup-folded t)
  3392. ("nofold" org-startup-folded nil)
  3393. ("showall" org-startup-folded nil)
  3394. ("show2levels" org-startup-folded show2levels)
  3395. ("show3levels" org-startup-folded show3levels)
  3396. ("show4levels" org-startup-folded show4levels)
  3397. ("show5levels" org-startup-folded show5levels)
  3398. ("showeverything" org-startup-folded showeverything)
  3399. ("content" org-startup-folded content)
  3400. ("indent" org-startup-indented t)
  3401. ("noindent" org-startup-indented nil)
  3402. ("num" org-startup-numerated t)
  3403. ("nonum" org-startup-numerated nil)
  3404. ("hidestars" org-hide-leading-stars t)
  3405. ("showstars" org-hide-leading-stars nil)
  3406. ("odd" org-odd-levels-only t)
  3407. ("oddeven" org-odd-levels-only nil)
  3408. ("align" org-startup-align-all-tables t)
  3409. ("noalign" org-startup-align-all-tables nil)
  3410. ("shrink" org-startup-shrink-all-tables t)
  3411. ("inlineimages" org-startup-with-inline-images t)
  3412. ("noinlineimages" org-startup-with-inline-images nil)
  3413. ("latexpreview" org-startup-with-latex-preview t)
  3414. ("nolatexpreview" org-startup-with-latex-preview nil)
  3415. ("customtime" org-display-custom-times t)
  3416. ("logdone" org-log-done time)
  3417. ("lognotedone" org-log-done note)
  3418. ("nologdone" org-log-done nil)
  3419. ("lognoteclock-out" org-log-note-clock-out t)
  3420. ("nolognoteclock-out" org-log-note-clock-out nil)
  3421. ("logrepeat" org-log-repeat state)
  3422. ("lognoterepeat" org-log-repeat note)
  3423. ("logdrawer" org-log-into-drawer t)
  3424. ("nologdrawer" org-log-into-drawer nil)
  3425. ("logstatesreversed" org-log-states-order-reversed t)
  3426. ("nologstatesreversed" org-log-states-order-reversed nil)
  3427. ("nologrepeat" org-log-repeat nil)
  3428. ("logreschedule" org-log-reschedule time)
  3429. ("lognotereschedule" org-log-reschedule note)
  3430. ("nologreschedule" org-log-reschedule nil)
  3431. ("logredeadline" org-log-redeadline time)
  3432. ("lognoteredeadline" org-log-redeadline note)
  3433. ("nologredeadline" org-log-redeadline nil)
  3434. ("logrefile" org-log-refile time)
  3435. ("lognoterefile" org-log-refile note)
  3436. ("nologrefile" org-log-refile nil)
  3437. ("fninline" org-footnote-define-inline t)
  3438. ("nofninline" org-footnote-define-inline nil)
  3439. ("fnlocal" org-footnote-section nil)
  3440. ("fnauto" org-footnote-auto-label t)
  3441. ("fnprompt" org-footnote-auto-label nil)
  3442. ("fnconfirm" org-footnote-auto-label confirm)
  3443. ("fnplain" org-footnote-auto-label plain)
  3444. ("fnadjust" org-footnote-auto-adjust t)
  3445. ("nofnadjust" org-footnote-auto-adjust nil)
  3446. ("constcgs" constants-unit-system cgs)
  3447. ("constSI" constants-unit-system SI)
  3448. ("noptag" org-tag-persistent-alist nil)
  3449. ("hideblocks" org-hide-block-startup t)
  3450. ("nohideblocks" org-hide-block-startup nil)
  3451. ("hidedrawers" org-hide-drawer-startup t)
  3452. ("nohidedrawers" org-hide-drawer-startup nil)
  3453. ("beamer" org-startup-with-beamer-mode t)
  3454. ("entitiespretty" org-pretty-entities t)
  3455. ("entitiesplain" org-pretty-entities nil))
  3456. "Variable associated with STARTUP options for Org.
  3457. Each element is a list of three items: the startup options (as written
  3458. in the #+STARTUP line), the corresponding variable, and the value to set
  3459. this variable to if the option is found. An optional fourth element PUSH
  3460. means to push this value onto the list in the variable.")
  3461. (defcustom org-group-tags t
  3462. "When non-nil (the default), use group tags.
  3463. This can be turned on/off through `org-toggle-tags-groups'."
  3464. :group 'org-tags
  3465. :group 'org-startup
  3466. :type 'boolean)
  3467. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  3468. (defun org-toggle-tags-groups ()
  3469. "Toggle support for group tags.
  3470. Support for group tags is controlled by the option
  3471. `org-group-tags', which is non-nil by default."
  3472. (interactive)
  3473. (setq org-group-tags (not org-group-tags))
  3474. (cond ((and (derived-mode-p 'org-agenda-mode)
  3475. org-group-tags)
  3476. (org-agenda-redo))
  3477. ((derived-mode-p 'org-mode)
  3478. (let ((org-inhibit-startup t)) (org-mode))))
  3479. (message "Groups tags support has been turned %s"
  3480. (if org-group-tags "on" "off")))
  3481. (defun org--tag-add-to-alist (alist1 alist2)
  3482. "Merge tags from ALIST1 into ALIST2.
  3483. Duplicates tags outside a group are removed. Keywords and order
  3484. are preserved.
  3485. The function assumes ALIST1 and ALIST2 are proper tag alists.
  3486. See `org-tag-alist' for their structure."
  3487. (cond
  3488. ((null alist2) alist1)
  3489. ((null alist1) alist2)
  3490. (t
  3491. (let ((to-add nil)
  3492. (group-flag nil))
  3493. (dolist (tag-pair alist1)
  3494. (pcase tag-pair
  3495. (`(,(or :startgrouptag :startgroup))
  3496. (setq group-flag t)
  3497. (push tag-pair to-add))
  3498. (`(,(or :endgrouptag :endgroup))
  3499. (setq group-flag nil)
  3500. (push tag-pair to-add))
  3501. (`(,(or :grouptags :newline))
  3502. (push tag-pair to-add))
  3503. (`(,tag . ,_)
  3504. ;; Remove duplicates from ALIST1, unless they are in
  3505. ;; a group. Indeed, it makes sense to have a tag appear in
  3506. ;; multiple groups.
  3507. (when (or group-flag (not (assoc tag alist2)))
  3508. (push tag-pair to-add)))
  3509. (_ (error "Invalid association in tag alist: %S" tag-pair))))
  3510. ;; Preserve order of ALIST1.
  3511. (append (nreverse to-add) alist2)))))
  3512. (defun org-priority-to-value (s)
  3513. "Convert priority string S to its numeric value."
  3514. (or (save-match-data
  3515. (and (string-match "\\([0-9]+\\)" s)
  3516. (string-to-number (match-string 1 s))))
  3517. (string-to-char s)))
  3518. (defun org-set-regexps-and-options (&optional tags-only)
  3519. "Precompute regular expressions used in the current buffer.
  3520. When optional argument TAGS-ONLY is non-nil, only compute tags
  3521. related expressions."
  3522. (when (derived-mode-p 'org-mode)
  3523. (let ((alist (org-collect-keywords
  3524. (append '("FILETAGS" "TAGS")
  3525. (and (not tags-only)
  3526. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  3527. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  3528. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))
  3529. '("ARCHIVE" "CATEGORY" "COLUMNS" "PRIORITIES"))))
  3530. ;; Startup options. Get this early since it does change
  3531. ;; behavior for other options (e.g., tags).
  3532. (let ((startup (cl-mapcan (lambda (value) (split-string value))
  3533. (cdr (assoc "STARTUP" alist)))))
  3534. (dolist (option startup)
  3535. (pcase (assoc-string option org-startup-options t)
  3536. (`(,_ ,variable ,value t)
  3537. (unless (listp (symbol-value variable))
  3538. (set (make-local-variable variable) nil))
  3539. (add-to-list variable value))
  3540. (`(,_ ,variable ,value . ,_)
  3541. (set (make-local-variable variable) value))
  3542. (_ nil))))
  3543. (setq-local org-file-tags
  3544. (mapcar #'org-add-prop-inherited
  3545. (cl-mapcan (lambda (value)
  3546. (cl-mapcan
  3547. (lambda (k) (org-split-string k ":"))
  3548. (split-string value)))
  3549. (cdr (assoc "FILETAGS" alist)))))
  3550. (setq org-current-tag-alist
  3551. (org--tag-add-to-alist
  3552. org-tag-persistent-alist
  3553. (let ((tags (cdr (assoc "TAGS" alist))))
  3554. (if tags
  3555. (org-tag-string-to-alist
  3556. (mapconcat #'identity tags "\n"))
  3557. org-tag-alist))))
  3558. (setq org-tag-groups-alist
  3559. (org-tag-alist-to-groups org-current-tag-alist))
  3560. (unless tags-only
  3561. ;; Properties.
  3562. (let ((properties nil))
  3563. (dolist (value (cdr (assoc "PROPERTY" alist)))
  3564. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  3565. (setq properties (org--update-property-plist
  3566. (match-string-no-properties 1 value)
  3567. (match-string-no-properties 2 value)
  3568. properties))))
  3569. (setq-local org-keyword-properties properties))
  3570. ;; Archive location.
  3571. (let ((archive (cdr (assoc "ARCHIVE" alist))))
  3572. (when archive (setq-local org-archive-location archive)))
  3573. ;; Category.
  3574. (let ((category (cdr (assoc "CATEGORY" alist))))
  3575. (when category
  3576. (setq-local org-category (intern category))
  3577. (setq-local org-keyword-properties
  3578. (org--update-property-plist
  3579. "CATEGORY" category org-keyword-properties))))
  3580. ;; Columns.
  3581. (let ((column (cdr (assoc "COLUMNS" alist))))
  3582. (when column (setq-local org-columns-default-format column)))
  3583. ;; Constants.
  3584. (let ((store nil))
  3585. (dolist (pair (cl-mapcan #'split-string
  3586. (cdr (assoc "CONSTANTS" alist))))
  3587. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" pair)
  3588. (let* ((name (match-string 1 pair))
  3589. (value (match-string 2 pair))
  3590. (old (assoc name store)))
  3591. (if old (setcdr old value)
  3592. (push (cons name value) store)))))
  3593. (setq org-table-formula-constants-local store))
  3594. ;; Link abbreviations.
  3595. (let ((links
  3596. (delq nil
  3597. (mapcar
  3598. (lambda (value)
  3599. (and (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  3600. (cons (match-string-no-properties 1 value)
  3601. (match-string-no-properties 2 value))))
  3602. (cdr (assoc "LINK" alist))))))
  3603. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  3604. ;; Priorities.
  3605. (let ((value (cdr (assoc "PRIORITIES" alist))))
  3606. (pcase (and value (split-string value))
  3607. (`(,high ,low ,default . ,_)
  3608. (setq-local org-priority-highest (org-priority-to-value high))
  3609. (setq-local org-priority-lowest (org-priority-to-value low))
  3610. (setq-local org-priority-default (org-priority-to-value default)))))
  3611. ;; Scripts.
  3612. (let ((value (cdr (assoc "OPTIONS" alist))))
  3613. (dolist (option value)
  3614. (when (string-match "\\^:\\(t\\|nil\\|{}\\)" option)
  3615. (setq-local org-use-sub-superscripts
  3616. (read (match-string 1 option))))))
  3617. ;; TODO keywords.
  3618. (setq-local org-todo-kwd-alist nil)
  3619. (setq-local org-todo-key-alist nil)
  3620. (setq-local org-todo-key-trigger nil)
  3621. (setq-local org-todo-keywords-1 nil)
  3622. (setq-local org-done-keywords nil)
  3623. (setq-local org-todo-heads nil)
  3624. (setq-local org-todo-sets nil)
  3625. (setq-local org-todo-log-states nil)
  3626. (let ((todo-sequences
  3627. (or (append (mapcar (lambda (value)
  3628. (cons 'type (split-string value)))
  3629. (cdr (assoc "TYP_TODO" alist)))
  3630. (mapcar (lambda (value)
  3631. (cons 'sequence (split-string value)))
  3632. (append (cdr (assoc "TODO" alist))
  3633. (cdr (assoc "SEQ_TODO" alist)))))
  3634. (let ((d (default-value 'org-todo-keywords)))
  3635. (if (not (stringp (car d))) d
  3636. ;; XXX: Backward compatibility code.
  3637. (list (cons org-todo-interpretation d)))))))
  3638. (dolist (sequence todo-sequences)
  3639. (let* ((sequence (or (run-hook-with-args-until-success
  3640. 'org-todo-setup-filter-hook sequence)
  3641. sequence))
  3642. (sequence-type (car sequence))
  3643. (keywords (cdr sequence))
  3644. (sep (member "|" keywords))
  3645. names alist)
  3646. (dolist (k (remove "|" keywords))
  3647. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  3648. k)
  3649. (error "Invalid TODO keyword %s" k))
  3650. (let ((name (match-string 1 k))
  3651. (key (match-string 2 k))
  3652. (log (org-extract-log-state-settings k)))
  3653. (push name names)
  3654. (push (cons name (and key (string-to-char key))) alist)
  3655. (when log (push log org-todo-log-states))))
  3656. (let* ((names (nreverse names))
  3657. (done (if sep (org-remove-keyword-keys (cdr sep))
  3658. (last names)))
  3659. (head (car names))
  3660. (tail (list sequence-type head (car done) (org-last done))))
  3661. (add-to-list 'org-todo-heads head 'append)
  3662. (push names org-todo-sets)
  3663. (setq org-done-keywords (append org-done-keywords done nil))
  3664. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  3665. (setq org-todo-key-alist
  3666. (append org-todo-key-alist
  3667. (and alist
  3668. (append '((:startgroup))
  3669. (nreverse alist)
  3670. '((:endgroup))))))
  3671. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  3672. (setq org-todo-sets (nreverse org-todo-sets)
  3673. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  3674. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  3675. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  3676. ;; Compute the regular expressions and other local variables.
  3677. ;; Using `org-outline-regexp-bol' would complicate them much,
  3678. ;; because of the fixed white space at the end of that string.
  3679. (unless org-done-keywords
  3680. (setq org-done-keywords
  3681. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  3682. (setq org-not-done-keywords
  3683. (org-delete-all org-done-keywords
  3684. (copy-sequence org-todo-keywords-1))
  3685. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  3686. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  3687. org-not-done-heading-regexp
  3688. (format org-heading-keyword-regexp-format org-not-done-regexp)
  3689. org-todo-line-regexp
  3690. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  3691. org-complex-heading-regexp
  3692. (concat "^\\(\\*+\\)"
  3693. "\\(?: +" org-todo-regexp "\\)?"
  3694. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3695. "\\(?: +\\(.*?\\)\\)??"
  3696. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  3697. "[ \t]*$")
  3698. org-complex-heading-regexp-format
  3699. (concat "^\\(\\*+\\)"
  3700. "\\(?: +" org-todo-regexp "\\)?"
  3701. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3702. "\\(?: +"
  3703. ;; Headline might be commented
  3704. "\\(?:" org-comment-string " +\\)?"
  3705. ;; Stats cookies can be stuck to body.
  3706. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  3707. "\\(%s\\)"
  3708. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  3709. "\\)"
  3710. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  3711. "[ \t]*$")
  3712. org-todo-line-tags-regexp
  3713. (concat "^\\(\\*+\\)"
  3714. "\\(?: +" org-todo-regexp "\\)?"
  3715. "\\(?: +\\(.*?\\)\\)??"
  3716. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  3717. "[ \t]*$"))
  3718. (org-compute-latex-and-related-regexp)))))
  3719. (defun org-collect-keywords (keywords &optional unique directory)
  3720. "Return values for KEYWORDS in current buffer, as an alist.
  3721. KEYWORDS is a list of strings. Return value is a list of
  3722. elements with the pattern:
  3723. (NAME . LIST-OF-VALUES)
  3724. where NAME is the upcase name of the keyword, and LIST-OF-VALUES
  3725. is a list of non-empty values, as strings, in order of appearance
  3726. in the buffer.
  3727. When KEYWORD appears in UNIQUE list, LIST-OF-VALUE is its first
  3728. value, empty or not, appearing in the buffer, as a string.
  3729. When KEYWORD appears in DIRECTORIES, each value is a cons cell:
  3730. (VALUE . DIRECTORY)
  3731. where VALUE is the regular value, and DIRECTORY is the variable
  3732. `default-directory' for the buffer containing the keyword. This
  3733. is important for values containing relative file names, since the
  3734. function follows SETUPFILE keywords, and may change its working
  3735. directory."
  3736. (let* ((keywords (cons "SETUPFILE" (mapcar #'upcase keywords)))
  3737. (unique (mapcar #'upcase unique))
  3738. (alist (org--collect-keywords-1
  3739. keywords unique directory
  3740. (and buffer-file-name (list buffer-file-name))
  3741. nil)))
  3742. ;; Re-order results.
  3743. (dolist (entry alist)
  3744. (pcase entry
  3745. (`(,_ . ,(and value (pred consp)))
  3746. (setcdr entry (nreverse value)))))
  3747. (nreverse alist)))
  3748. (defun org--collect-keywords-1 (keywords unique directory files alist)
  3749. (org-with-point-at 1
  3750. (let ((case-fold-search t)
  3751. (regexp (org-make-options-regexp keywords)))
  3752. (while (and keywords (re-search-forward regexp nil t))
  3753. (let ((element (org-element-at-point)))
  3754. (when (eq 'keyword (org-element-type element))
  3755. (let ((value (org-element-property :value element)))
  3756. (pcase (org-element-property :key element)
  3757. ("SETUPFILE"
  3758. (when (and (org-string-nw-p value)
  3759. (not buffer-read-only)) ;FIXME: bug in Gnus?
  3760. (let* ((uri (org-strip-quotes value))
  3761. (uri-is-url (org-url-p uri))
  3762. (uri (if uri-is-url
  3763. uri
  3764. (expand-file-name uri))))
  3765. (unless (member uri files)
  3766. (with-temp-buffer
  3767. (unless uri-is-url
  3768. (setq default-directory (file-name-directory uri)))
  3769. (let ((contents (org-file-contents uri :noerror)))
  3770. (when contents
  3771. (insert contents)
  3772. ;; Fake Org mode: `org-element-at-point'
  3773. ;; doesn't need full set-up.
  3774. (let ((major-mode 'org-mode))
  3775. (setq alist
  3776. (org--collect-keywords-1
  3777. keywords unique directory
  3778. (cons uri files)
  3779. alist))))))))))
  3780. (keyword
  3781. (let ((entry (assoc keyword alist))
  3782. (final
  3783. (cond ((not (member keyword directory)) value)
  3784. (buffer-file-name
  3785. (cons value
  3786. (file-name-directory buffer-file-name)))
  3787. (t (cons value default-directory)))))
  3788. (cond ((member keyword unique)
  3789. (push (cons keyword final) alist)
  3790. (setq keywords (remove keyword keywords))
  3791. (setq regexp (org-make-options-regexp keywords)))
  3792. ((null entry) (push (list keyword final) alist))
  3793. (t (push final (cdr entry)))))))))))
  3794. alist)))
  3795. (defun org-tag-string-to-alist (s)
  3796. "Return tag alist associated to string S.
  3797. S is a value for TAGS keyword or produced with
  3798. `org-tag-alist-to-string'. Return value is an alist suitable for
  3799. `org-tag-alist' or `org-tag-persistent-alist'."
  3800. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  3801. (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
  3802. "\\(?:(\\(.\\))\\)?\\'"))
  3803. alist group-flag)
  3804. (dolist (tokens lines (cdr (nreverse alist)))
  3805. (push '(:newline) alist)
  3806. (while tokens
  3807. (let ((token (pop tokens)))
  3808. (pcase token
  3809. ("{"
  3810. (push '(:startgroup) alist)
  3811. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3812. ("}"
  3813. (push '(:endgroup) alist)
  3814. (setq group-flag nil))
  3815. ("["
  3816. (push '(:startgrouptag) alist)
  3817. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3818. ("]"
  3819. (push '(:endgrouptag) alist)
  3820. (setq group-flag nil))
  3821. (":"
  3822. (push '(:grouptags) alist))
  3823. ((guard (string-match tag-re token))
  3824. (let ((tag (match-string 1 token))
  3825. (key (and (match-beginning 2)
  3826. (string-to-char (match-string 2 token)))))
  3827. ;; Push all tags in groups, no matter if they already
  3828. ;; appear somewhere else in the list.
  3829. (when (or group-flag (not (assoc tag alist)))
  3830. (push (cons tag key) alist))))))))))
  3831. (defun org-tag-alist-to-string (alist &optional skip-key)
  3832. "Return tag string associated to ALIST.
  3833. ALIST is an alist, as defined in `org-tag-alist' or
  3834. `org-tag-persistent-alist', or produced with
  3835. `org-tag-string-to-alist'.
  3836. Return value is a string suitable as a value for \"TAGS\"
  3837. keyword.
  3838. When optional argument SKIP-KEY is non-nil, skip selection keys
  3839. next to tags."
  3840. (mapconcat (lambda (token)
  3841. (pcase token
  3842. (`(:startgroup) "{")
  3843. (`(:endgroup) "}")
  3844. (`(:startgrouptag) "[")
  3845. (`(:endgrouptag) "]")
  3846. (`(:grouptags) ":")
  3847. (`(:newline) "\\n")
  3848. ((and
  3849. (guard (not skip-key))
  3850. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  3851. (format "%s(%c)" tag key))
  3852. (`(,(and tag (pred stringp)) . ,_) tag)
  3853. (_ (user-error "Invalid tag token: %S" token))))
  3854. alist
  3855. " "))
  3856. (defun org-tag-alist-to-groups (alist)
  3857. "Return group alist from tag ALIST.
  3858. ALIST is an alist, as defined in `org-tag-alist' or
  3859. `org-tag-persistent-alist', or produced with
  3860. `org-tag-string-to-alist'. Return value is an alist following
  3861. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  3862. a string, summarizing TAGS, as a list of strings."
  3863. (let (groups group-status current-group)
  3864. (dolist (token alist (nreverse groups))
  3865. (pcase token
  3866. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  3867. (`(,(or :endgroup :endgrouptag))
  3868. (when (eq group-status 'append)
  3869. (push (nreverse current-group) groups))
  3870. (setq group-status nil current-group nil))
  3871. (`(:grouptags) (setq group-status 'append))
  3872. ((and `(,tag . ,_) (guard group-status))
  3873. (if (eq group-status 'append) (push tag current-group)
  3874. (setq current-group (list tag))))
  3875. (_ nil)))))
  3876. (defvar org--file-cache (make-hash-table :test #'equal)
  3877. "Hash table to store contents of files referenced via a URL.
  3878. This is the cache of file URLs read using `org-file-contents'.")
  3879. (defun org-reset-file-cache ()
  3880. "Reset the cache of files downloaded by `org-file-contents'."
  3881. (clrhash org--file-cache))
  3882. (defun org-file-contents (file &optional noerror nocache)
  3883. "Return the contents of FILE, as a string.
  3884. FILE can be a file name or URL.
  3885. If FILE is a URL, download the contents. If the URL contents are
  3886. already cached in the `org--file-cache' hash table, the download step
  3887. is skipped.
  3888. If NOERROR is non-nil, ignore the error when unable to read the FILE
  3889. from file or URL, and return nil.
  3890. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  3891. is available. This option applies only if FILE is a URL."
  3892. (let* ((is-url (org-url-p file))
  3893. (cache (and is-url
  3894. (not nocache)
  3895. (gethash file org--file-cache))))
  3896. (cond
  3897. (cache)
  3898. (is-url
  3899. (if (org--should-fetch-remote-resource-p file)
  3900. (with-current-buffer (url-retrieve-synchronously file)
  3901. (goto-char (point-min))
  3902. ;; Move point to after the url-retrieve header.
  3903. (search-forward "\n\n" nil :move)
  3904. ;; Search for the success code only in the url-retrieve header.
  3905. (if (save-excursion
  3906. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  3907. ;; Update the cache `org--file-cache' and return contents.
  3908. (puthash file
  3909. (buffer-substring-no-properties (point) (point-max))
  3910. org--file-cache)
  3911. (funcall (if noerror #'message #'user-error)
  3912. "Unable to fetch file from %S"
  3913. file)
  3914. nil))
  3915. (funcall (if noerror #'message #'user-error)
  3916. "The remote resource %S is considered unsafe, and will not be downloaded."
  3917. file)))
  3918. (t
  3919. (with-temp-buffer
  3920. (condition-case nil
  3921. (progn
  3922. (insert-file-contents file)
  3923. (buffer-string))
  3924. (file-error
  3925. (funcall (if noerror #'message #'user-error)
  3926. "Unable to read file %S"
  3927. file)
  3928. nil)))))))
  3929. (defun org--should-fetch-remote-resource-p (uri)
  3930. "Return non-nil if the URI should be fetched."
  3931. (or (eq org-resource-download-policy t)
  3932. (org--safe-remote-resource-p uri)
  3933. (and (eq org-resource-download-policy 'prompt)
  3934. (org--confirm-resource-safe uri))))
  3935. (defun org--safe-remote-resource-p (uri)
  3936. "Return non-nil if URI is considered safe.
  3937. This checks every pattern in `org-safe-remote-resources', and
  3938. returns non-nil if any of them match."
  3939. (let ((uri-patterns org-safe-remote-resources)
  3940. (file-uri (and buffer-file-name
  3941. (concat "file://" (file-truename buffer-file-name))))
  3942. match-p)
  3943. (while (and (not match-p) uri-patterns)
  3944. (setq match-p (or (string-match-p (car uri-patterns) uri)
  3945. (and file-uri (string-match-p (car uri-patterns) file-uri)))
  3946. uri-patterns (cdr uri-patterns)))
  3947. match-p))
  3948. (defun org--confirm-resource-safe (uri)
  3949. "Ask the user if URI should be considered safe, returning non-nil if so."
  3950. (unless noninteractive
  3951. (let ((current-file (and buffer-file-name (file-truename buffer-file-name)))
  3952. (buf (get-buffer-create "*Org Remote Resource*")))
  3953. ;; Set up the contents of the *Org Remote Resource* buffer.
  3954. (with-current-buffer buf
  3955. (erase-buffer)
  3956. (insert "An org-mode document would like to download "
  3957. (propertize uri 'face '(:inherit org-link :weight normal))
  3958. ", which is not considered safe.\n\n"
  3959. "Do you want to download this? You can type\n "
  3960. (propertize "!" 'face 'success)
  3961. " to download this resource, and permanantly mark it as safe.\n "
  3962. (propertize "f" 'face 'success)
  3963. " to download this resource, and permanantly mark all resources in "
  3964. (propertize current-file 'face 'fixed-pitch-serif)
  3965. " as safe.\n "
  3966. (propertize "y" 'face 'warning)
  3967. " to download this resource, just this once.\n "
  3968. (propertize "n" 'face 'error)
  3969. " to skip this resource.\n")
  3970. (setq-local cursor-type nil)
  3971. (set-buffer-modified-p nil)
  3972. (goto-char (point-min)))
  3973. ;; Display the buffer and read a choice.
  3974. (save-window-excursion
  3975. (pop-to-buffer buf)
  3976. (let* ((exit-chars '(?y ?n ?! ?f ?\s))
  3977. (prompt (format "Please type y, n, f, or !%s: "
  3978. (if (< (line-number-at-pos (point-max))
  3979. (window-body-height))
  3980. ""
  3981. ", or C-v/M-v to scroll")))
  3982. char)
  3983. (setq char (read-char-choice prompt exit-chars))
  3984. (when (memq char '(?! ?f))
  3985. (customize-push-and-save
  3986. 'org-safe-remote-resources
  3987. (list (rx string-start
  3988. (literal
  3989. (if (and (= char ?f) current-file)
  3990. (concat "file://" current-file) uri))
  3991. string-end))))
  3992. (prog1 (memq char '(?! ?\s ?y ?f))
  3993. (quit-window t)))))))
  3994. (defun org-extract-log-state-settings (x)
  3995. "Extract the log state setting from a TODO keyword string.
  3996. This will extract info from a string like \"WAIT(w@/!)\"."
  3997. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  3998. (let ((kw (match-string 1 x))
  3999. (log1 (and (match-end 3) (match-string 3 x)))
  4000. (log2 (and (match-end 4) (match-string 4 x))))
  4001. (and (or log1 log2)
  4002. (list kw
  4003. (and log1 (if (equal log1 "!") 'time 'note))
  4004. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4005. (defun org-remove-keyword-keys (list)
  4006. "Remove a pair of parenthesis at the end of each string in LIST."
  4007. (mapcar (lambda (x)
  4008. (if (string-match "(.*)$" x)
  4009. (substring x 0 (match-beginning 0))
  4010. x))
  4011. list))
  4012. (defun org-assign-fast-keys (alist)
  4013. "Assign fast keys to a keyword-key alist.
  4014. Respect keys that are already there."
  4015. (let (new e (alt ?0))
  4016. (while (setq e (pop alist))
  4017. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4018. (cdr e)) ;; Key already assigned.
  4019. (push e new)
  4020. (let ((clist (string-to-list (downcase (car e))))
  4021. (used (append new alist)))
  4022. (when (= (car clist) ?@)
  4023. (pop clist))
  4024. (while (and clist (rassoc (car clist) used))
  4025. (pop clist))
  4026. (unless clist
  4027. (while (rassoc alt used)
  4028. (cl-incf alt)))
  4029. (push (cons (car e) (or (car clist) alt)) new))))
  4030. (nreverse new)))
  4031. ;;; Some variables used in various places
  4032. (defvar org-window-configuration nil
  4033. "Used in various places to store a window configuration.")
  4034. (defvar org-selected-window nil
  4035. "Used in various places to store a window configuration.")
  4036. (defvar org-finish-function nil
  4037. "Function to be called when `C-c C-c' is used.
  4038. This is for getting out of special buffers like capture.")
  4039. (defvar org-last-state)
  4040. ;; Defined somewhere in this file, but used before definition.
  4041. (defvar org-entities) ;; defined in org-entities.el
  4042. (defvar org-struct-menu)
  4043. (defvar org-org-menu)
  4044. (defvar org-tbl-menu)
  4045. ;;;; Define the Org mode
  4046. (defun org-before-change-function (_beg _end)
  4047. "Every change indicates that a table might need an update."
  4048. (setq org-table-may-need-update t))
  4049. (defvar org-mode-map)
  4050. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4051. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4052. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4053. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4054. (defvar bidi-paragraph-direction)
  4055. (defvar buffer-face-mode-face)
  4056. (require 'outline)
  4057. ;; Other stuff we need.
  4058. (require 'time-date)
  4059. (when (< emacs-major-version 28) ; preloaded in Emacs 28
  4060. (require 'easymenu))
  4061. (require 'org-entities)
  4062. (require 'org-faces)
  4063. (require 'org-list)
  4064. (require 'org-pcomplete)
  4065. (require 'org-src)
  4066. (require 'org-footnote)
  4067. (require 'org-macro)
  4068. ;; babel
  4069. (require 'ob)
  4070. (defvar org-element-cache-persistent); Defined in org-element.el
  4071. (defvar org-element-use-cache); Defined in org-element.el
  4072. (defvar org-mode-loading nil
  4073. "Non-nil during Org mode initialisation.")
  4074. ;;;###autoload
  4075. (define-derived-mode org-mode outline-mode "Org"
  4076. "Outline-based notes management and organizer, alias
  4077. \"Carsten's outline-mode for keeping track of everything.\"
  4078. Org mode develops organizational tasks around a NOTES file which
  4079. contains information about projects as plain text. Org mode is
  4080. implemented on top of Outline mode, which is ideal to keep the content
  4081. of large files well structured. It supports ToDo items, deadlines and
  4082. time stamps, which magically appear in the diary listing of the Emacs
  4083. calendar. Tables are easily created with a built-in table editor.
  4084. Plain text URL-like links connect to websites, emails (VM), Usenet
  4085. messages (Gnus), BBDB entries, and any files related to the project.
  4086. For printing and sharing of notes, an Org file (or a part of it)
  4087. can be exported as a structured ASCII or HTML file.
  4088. The following commands are available:
  4089. \\{org-mode-map}"
  4090. (setq-local org-mode-loading t)
  4091. (org-load-modules-maybe)
  4092. (org-install-agenda-files-menu)
  4093. (when (and org-link-descriptive
  4094. (eq org-fold-core-style 'overlays))
  4095. (add-to-invisibility-spec '(org-link)))
  4096. (org-fold-initialize (or (and (stringp org-ellipsis) (not (equal "" org-ellipsis)) org-ellipsis)
  4097. "..."))
  4098. (make-local-variable 'org-link-descriptive)
  4099. (when (eq org-fold-core-style 'overlays) (add-to-invisibility-spec '(org-hide-block . t)))
  4100. (if org-link-descriptive
  4101. (org-fold-core-set-folding-spec-property (car org-link--link-folding-spec) :visible nil)
  4102. (org-fold-core-set-folding-spec-property (car org-link--link-folding-spec) :visible t))
  4103. (setq-local outline-regexp org-outline-regexp)
  4104. (setq-local outline-level 'org-outline-level)
  4105. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4106. (unless org-display-table
  4107. (setq org-display-table (make-display-table)))
  4108. (set-display-table-slot
  4109. org-display-table 4
  4110. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4111. org-ellipsis)))
  4112. (setq buffer-display-table org-display-table))
  4113. (org-set-regexps-and-options)
  4114. (org-set-font-lock-defaults)
  4115. (when (and org-tag-faces (not org-tags-special-faces-re))
  4116. ;; tag faces set outside customize.... force initialization.
  4117. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4118. ;; Calc embedded
  4119. (setq-local calc-embedded-open-mode "# ")
  4120. ;; Modify a few syntax entries
  4121. (modify-syntax-entry ?\" "\"")
  4122. (modify-syntax-entry ?\\ "_")
  4123. (modify-syntax-entry ?~ "_")
  4124. (modify-syntax-entry ?< "(>")
  4125. (modify-syntax-entry ?> ")<")
  4126. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4127. ;; Activate before-change-function
  4128. (setq-local org-table-may-need-update t)
  4129. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4130. ;; Check for running clock before killing a buffer
  4131. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4132. ;; Initialize cache.
  4133. (org-element-cache-reset)
  4134. (when (and org-element-cache-persistent
  4135. org-element-use-cache)
  4136. (org-persist-load 'org-element--cache (current-buffer) t))
  4137. ;; Initialize macros templates.
  4138. (org-macro-initialize-templates)
  4139. ;; Initialize radio targets.
  4140. (org-update-radio-target-regexp)
  4141. ;; Indentation.
  4142. (setq-local indent-line-function 'org-indent-line)
  4143. (setq-local indent-region-function 'org-indent-region)
  4144. ;; Filling and auto-filling.
  4145. (org-setup-filling)
  4146. ;; Comments.
  4147. (org-setup-comments-handling)
  4148. ;; Beginning/end of defun
  4149. (setq-local beginning-of-defun-function 'org-backward-element)
  4150. (setq-local end-of-defun-function
  4151. (lambda ()
  4152. (if (not (org-at-heading-p))
  4153. (org-forward-element)
  4154. (org-forward-element)
  4155. (forward-char -1))))
  4156. ;; Next error for sparse trees
  4157. (setq-local next-error-function 'org-occur-next-match)
  4158. ;; Make commit log messages from Org documents easier.
  4159. (setq-local add-log-current-defun-function #'org-add-log-current-headline)
  4160. ;; Make sure dependence stuff works reliably, even for users who set it
  4161. ;; too late :-(
  4162. (if org-enforce-todo-dependencies
  4163. (add-hook 'org-blocker-hook
  4164. 'org-block-todo-from-children-or-siblings-or-parent)
  4165. (remove-hook 'org-blocker-hook
  4166. 'org-block-todo-from-children-or-siblings-or-parent))
  4167. (if org-enforce-todo-checkbox-dependencies
  4168. (add-hook 'org-blocker-hook
  4169. 'org-block-todo-from-checkboxes)
  4170. (remove-hook 'org-blocker-hook
  4171. 'org-block-todo-from-checkboxes))
  4172. ;; Align options lines
  4173. (setq-local
  4174. align-mode-rules-list
  4175. '((org-in-buffer-settings
  4176. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4177. (modes . '(org-mode)))))
  4178. ;; Setup the pcomplete hooks
  4179. (setq-local pcomplete-command-completion-function #'org-pcomplete-initial)
  4180. (setq-local pcomplete-command-name-function #'org-command-at-point)
  4181. (setq-local pcomplete-default-completion-function #'ignore)
  4182. (setq-local pcomplete-parse-arguments-function #'org-parse-arguments)
  4183. (setq-local pcomplete-termination-string "")
  4184. (add-hook 'completion-at-point-functions
  4185. #'pcomplete-completions-at-point nil t)
  4186. (setq-local buffer-face-mode-face 'org-default)
  4187. ;; If empty file that did not turn on Org mode automatically, make
  4188. ;; it to.
  4189. (when (and org-insert-mode-line-in-empty-file
  4190. (called-interactively-p 'any)
  4191. (= (point-min) (point-max)))
  4192. (insert "# -*- mode: org -*-\n\n"))
  4193. (unless org-inhibit-startup
  4194. (org-unmodified
  4195. (when org-startup-with-beamer-mode (org-beamer-mode))
  4196. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4197. (org-table-map-tables
  4198. (cond ((and org-startup-align-all-tables
  4199. org-startup-shrink-all-tables)
  4200. (lambda () (org-table-align) (org-table-shrink)))
  4201. (org-startup-align-all-tables #'org-table-align)
  4202. (t #'org-table-shrink))
  4203. t))
  4204. (when org-startup-with-inline-images (org-display-inline-images))
  4205. (when org-startup-with-latex-preview (org-latex-preview '(16)))
  4206. (unless org-inhibit-startup-visibility-stuff (org-cycle-set-startup-visibility))
  4207. (when org-startup-truncated (setq truncate-lines t))
  4208. (when org-startup-numerated (require 'org-num) (org-num-mode 1))
  4209. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))))
  4210. ;; Add a custom keymap for `visual-line-mode' so that activating
  4211. ;; this minor mode does not override Org's keybindings.
  4212. ;; FIXME: Probably `visual-line-mode' should take care of this.
  4213. (let ((oldmap (cdr (assoc 'visual-line-mode minor-mode-map-alist)))
  4214. (newmap (make-sparse-keymap)))
  4215. (set-keymap-parent newmap oldmap)
  4216. (define-key newmap [remap move-beginning-of-line] nil)
  4217. (define-key newmap [remap move-end-of-line] nil)
  4218. (define-key newmap [remap kill-line] nil)
  4219. (make-local-variable 'minor-mode-overriding-map-alist)
  4220. (push `(visual-line-mode . ,newmap) minor-mode-overriding-map-alist))
  4221. ;; Activate `org-table-header-line-mode'
  4222. (when org-table-header-line-p
  4223. (org-table-header-line-mode 1))
  4224. ;; Try to set `org-hide' face correctly.
  4225. (let ((foreground (org-find-invisible-foreground)))
  4226. (when foreground
  4227. (set-face-foreground 'org-hide foreground)))
  4228. ;; Set face extension as requested.
  4229. (org--set-faces-extend '(org-block-begin-line org-block-end-line)
  4230. org-fontify-whole-block-delimiter-line)
  4231. (org--set-faces-extend org-level-faces org-fontify-whole-heading-line)
  4232. (setq-local org-mode-loading nil))
  4233. ;; Update `customize-package-emacs-version-alist'
  4234. (add-to-list 'customize-package-emacs-version-alist
  4235. '(Org ("8.0" . "24.4")
  4236. ("8.1" . "24.4")
  4237. ("8.2" . "24.4")
  4238. ("8.2.7" . "24.4")
  4239. ("8.3" . "26.1")
  4240. ("9.0" . "26.1")
  4241. ("9.1" . "26.1")
  4242. ("9.2" . "27.1")
  4243. ("9.3" . "27.1")
  4244. ("9.4" . "27.2")
  4245. ("9.5" . "28.1")
  4246. ("9.6" . "29.1")))
  4247. (defvar org-mode-transpose-word-syntax-table
  4248. (let ((st (make-syntax-table text-mode-syntax-table)))
  4249. (dolist (c org-emphasis-alist st)
  4250. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4251. (when (fboundp 'abbrev-table-put)
  4252. (abbrev-table-put org-mode-abbrev-table
  4253. :parents (list text-mode-abbrev-table)))
  4254. (defun org-find-invisible-foreground ()
  4255. (let ((candidates (remove
  4256. "unspecified-bg"
  4257. (nconc
  4258. (list (face-background 'default)
  4259. (face-background 'org-default))
  4260. (mapcar
  4261. (lambda (alist)
  4262. (when (boundp alist)
  4263. (cdr (assq 'background-color (symbol-value alist)))))
  4264. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4265. (list (face-foreground 'org-hide))))))
  4266. (car (remove nil candidates))))
  4267. (defun org-current-time (&optional rounding-minutes past)
  4268. "Current time, possibly rounded to ROUNDING-MINUTES.
  4269. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4270. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4271. the rounding returns a past time."
  4272. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4273. (car org-time-stamp-rounding-minutes)))
  4274. (now (current-time)))
  4275. (if (< r 1)
  4276. now
  4277. (let* ((time (decode-time now))
  4278. (res (org-encode-time
  4279. (apply #'list
  4280. 0 (* r (round (nth 1 time) r))
  4281. (nthcdr 2 time)))))
  4282. (if (or (not past) (time-less-p res now))
  4283. res
  4284. (time-subtract res (* r 60)))))))
  4285. (defun org-today ()
  4286. "Return today date, considering `org-extend-today-until'."
  4287. (time-to-days
  4288. (time-since (* 3600 org-extend-today-until))))
  4289. ;;;; Font-Lock stuff, including the activators
  4290. (defconst org-match-sexp-depth 3
  4291. "Number of stacked braces for sub/superscript matching.")
  4292. (defun org-create-multibrace-regexp (left right n)
  4293. "Create a regular expression which will match a balanced sexp.
  4294. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4295. as single character strings.
  4296. The regexp returned will match the entire expression including the
  4297. delimiters. It will also define a single group which contains the
  4298. match except for the outermost delimiters. The maximum depth of
  4299. stacked delimiters is N. Escaping delimiters is not possible."
  4300. (let* ((nothing (concat "[^" left right "]*?"))
  4301. (or "\\|")
  4302. (re nothing)
  4303. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4304. (while (> n 1)
  4305. (setq n (1- n)
  4306. re (concat re or next)
  4307. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4308. (concat left "\\(" re "\\)" right)))
  4309. (defconst org-match-substring-regexp
  4310. (concat
  4311. "\\(\\S-\\)\\([_^]\\)\\("
  4312. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4313. "\\|"
  4314. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4315. "\\|"
  4316. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4317. "The regular expression matching a sub- or superscript.")
  4318. (defconst org-match-substring-with-braces-regexp
  4319. (concat
  4320. "\\(\\S-\\)\\([_^]\\)"
  4321. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4322. "The regular expression matching a sub- or superscript, forcing braces.")
  4323. (defvar org-emph-face nil)
  4324. (defun org-do-emphasis-faces (limit)
  4325. "Run through the buffer and emphasize strings."
  4326. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  4327. (car org-emphasis-regexp-components))))
  4328. (catch :exit
  4329. (while (re-search-forward quick-re limit t)
  4330. (let* ((marker (match-string 2))
  4331. (verbatim? (member marker '("~" "="))))
  4332. (when (save-excursion
  4333. (goto-char (match-beginning 0))
  4334. (and
  4335. ;; Do not match table hlines.
  4336. (not (and (equal marker "+")
  4337. (org-match-line
  4338. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  4339. ;; Do not match headline stars. Do not consider
  4340. ;; stars of a headline as closing marker for bold
  4341. ;; markup either.
  4342. (not (and (equal marker "*")
  4343. (save-excursion
  4344. (forward-char)
  4345. (skip-chars-backward "*")
  4346. (looking-at-p org-outline-regexp-bol))))
  4347. ;; Match full emphasis markup regexp.
  4348. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  4349. ;; Do not span over paragraph boundaries.
  4350. (not (string-match-p org-element-paragraph-separate
  4351. (match-string 2)))
  4352. ;; Do not span over cells in table rows.
  4353. (not (and (save-match-data (org-match-line "[ \t]*|"))
  4354. (string-match-p "|" (match-string 4))))))
  4355. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist))
  4356. (m (if org-hide-emphasis-markers 4 2)))
  4357. (font-lock-prepend-text-property
  4358. (match-beginning m) (match-end m) 'face face)
  4359. (when verbatim?
  4360. (org-remove-flyspell-overlays-in
  4361. (match-beginning 0) (match-end 0))
  4362. (when (and (org-fold-core-folding-spec-p 'org-link)
  4363. (org-fold-core-folding-spec-p 'org-link-description))
  4364. (org-fold-region (match-beginning 0) (match-end 0) nil 'org-link)
  4365. (org-fold-region (match-beginning 0) (match-end 0) nil 'org-link-description))
  4366. (remove-text-properties (match-beginning 2) (match-end 2)
  4367. '(display t invisible t intangible t)))
  4368. (add-text-properties (match-beginning 2) (match-end 2)
  4369. '(font-lock-multiline t org-emphasis t))
  4370. (when (and org-hide-emphasis-markers
  4371. (not (org-at-comment-p)))
  4372. (add-text-properties (match-end 4) (match-beginning 5)
  4373. '(invisible t))
  4374. (add-text-properties (match-beginning 3) (match-end 3)
  4375. '(invisible t)))
  4376. (throw :exit t))))))))
  4377. (defun org-emphasize (&optional char)
  4378. "Insert or change an emphasis, i.e. a font like bold or italic.
  4379. If there is an active region, change that region to a new emphasis.
  4380. If there is no region, just insert the marker characters and position
  4381. the cursor between them.
  4382. CHAR should be the marker character. If it is a space, it means to
  4383. remove the emphasis of the selected region.
  4384. If CHAR is not given (for example in an interactive call) it will be
  4385. prompted for."
  4386. (interactive)
  4387. (let ((erc org-emphasis-regexp-components)
  4388. (string "") beg end move s)
  4389. (if (org-region-active-p)
  4390. (setq beg (region-beginning)
  4391. end (region-end)
  4392. string (buffer-substring beg end))
  4393. (setq move t))
  4394. (unless char
  4395. (message "Emphasis marker or tag: [%s]"
  4396. (mapconcat #'car org-emphasis-alist ""))
  4397. (setq char (read-char-exclusive)))
  4398. (if (equal char ?\s)
  4399. (setq s ""
  4400. move nil)
  4401. (unless (assoc (char-to-string char) org-emphasis-alist)
  4402. (user-error "No such emphasis marker: \"%c\"" char))
  4403. (setq s (char-to-string char)))
  4404. (while (and (> (length string) 1)
  4405. (equal (substring string 0 1) (substring string -1))
  4406. (assoc (substring string 0 1) org-emphasis-alist))
  4407. (setq string (substring string 1 -1)))
  4408. (setq string (concat s string s))
  4409. (when beg (delete-region beg end))
  4410. (unless (or (bolp)
  4411. (string-match (concat "[" (nth 0 erc) "\n]")
  4412. (char-to-string (char-before (point)))))
  4413. (insert " "))
  4414. (unless (or (eobp)
  4415. (string-match (concat "[" (nth 1 erc) "\n]")
  4416. (char-to-string (char-after (point)))))
  4417. (insert " ") (backward-char 1))
  4418. (insert string)
  4419. (and move (backward-char 1))))
  4420. (defconst org-nonsticky-props
  4421. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  4422. (defsubst org-rear-nonsticky-at (pos)
  4423. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  4424. (defun org-activate-links--overlays (limit)
  4425. "Add link properties to links.
  4426. This includes angle, plain, and bracket links."
  4427. (catch :exit
  4428. (while (re-search-forward org-link-any-re limit t)
  4429. (let* ((start (match-beginning 0))
  4430. (end (match-end 0))
  4431. (visible-start (or (match-beginning 3) (match-beginning 2)))
  4432. (visible-end (or (match-end 3) (match-end 2)))
  4433. (style (cond ((eq ?< (char-after start)) 'angle)
  4434. ((eq ?\[ (char-after (1+ start))) 'bracket)
  4435. (t 'plain))))
  4436. (when (and (memq style org-highlight-links)
  4437. ;; Do not span over paragraph boundaries.
  4438. (not (string-match-p org-element-paragraph-separate
  4439. (match-string 0)))
  4440. ;; Do not confuse plain links with tags.
  4441. (not (and (eq style 'plain)
  4442. (let ((face (get-text-property
  4443. (max (1- start) (point-min)) 'face)))
  4444. (if (consp face) (memq 'org-tag face)
  4445. (eq 'org-tag face))))))
  4446. (let* ((link-object (save-excursion
  4447. (goto-char start)
  4448. (save-match-data (org-element-link-parser))))
  4449. (link (org-element-property :raw-link link-object))
  4450. (type (org-element-property :type link-object))
  4451. (path (org-element-property :path link-object))
  4452. (face-property (pcase (org-link-get-parameter type :face)
  4453. ((and (pred functionp) face) (funcall face path))
  4454. ((and (pred facep) face) face)
  4455. ((and (pred consp) face) face) ;anonymous
  4456. (_ 'org-link)))
  4457. (properties ;for link's visible part
  4458. (list 'mouse-face (or (org-link-get-parameter type :mouse-face)
  4459. 'highlight)
  4460. 'keymap (or (org-link-get-parameter type :keymap)
  4461. org-mouse-map)
  4462. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  4463. ((and (pred stringp) echo) echo)
  4464. ((and (pred functionp) echo) echo)
  4465. (_ (concat "LINK: " link)))
  4466. 'htmlize-link (pcase (org-link-get-parameter type
  4467. :htmlize-link)
  4468. ((and (pred functionp) f) (funcall f))
  4469. (_ `(:uri ,link)))
  4470. 'font-lock-multiline t)))
  4471. (org-remove-flyspell-overlays-in start end)
  4472. (org-rear-nonsticky-at end)
  4473. (if (not (eq 'bracket style))
  4474. (progn
  4475. (add-face-text-property start end face-property)
  4476. (add-text-properties start end properties))
  4477. ;; Handle invisible parts in bracket links.
  4478. (remove-text-properties start end '(invisible nil))
  4479. (let ((hidden
  4480. (append `(invisible
  4481. ,(or (org-link-get-parameter type :display)
  4482. 'org-link))
  4483. properties)))
  4484. (add-text-properties start visible-start hidden)
  4485. (add-face-text-property start end face-property)
  4486. (add-text-properties visible-start visible-end properties)
  4487. (add-text-properties visible-end end hidden)
  4488. (org-rear-nonsticky-at visible-start)
  4489. (org-rear-nonsticky-at visible-end)))
  4490. (let ((f (org-link-get-parameter type :activate-func)))
  4491. (when (functionp f)
  4492. (funcall f start end path (eq style 'bracket))))
  4493. (throw :exit t))))) ;signal success
  4494. nil))
  4495. (defun org-activate-links--text-properties (limit)
  4496. "Add link properties to links.
  4497. This includes angle, plain, and bracket links."
  4498. (catch :exit
  4499. (while (re-search-forward org-link-any-re limit t)
  4500. (let* ((start (match-beginning 0))
  4501. (end (match-end 0))
  4502. (visible-start (or (match-beginning 3) (match-beginning 2)))
  4503. (visible-end (or (match-end 3) (match-end 2)))
  4504. (style (cond ((eq ?< (char-after start)) 'angle)
  4505. ((eq ?\[ (char-after (1+ start))) 'bracket)
  4506. (t 'plain))))
  4507. (when (and (memq style org-highlight-links)
  4508. ;; Do not span over paragraph boundaries.
  4509. (not (string-match-p org-element-paragraph-separate
  4510. (match-string 0)))
  4511. ;; Do not confuse plain links with tags.
  4512. (not (and (eq style 'plain)
  4513. (let ((face (get-text-property
  4514. (max (1- start) (point-min)) 'face)))
  4515. (if (consp face) (memq 'org-tag face)
  4516. (eq 'org-tag face))))))
  4517. (let* ((link-object (save-excursion
  4518. (goto-char start)
  4519. (save-match-data (org-element-link-parser))))
  4520. (link (org-element-property :raw-link link-object))
  4521. (type (org-element-property :type link-object))
  4522. (path (org-element-property :path link-object))
  4523. (face-property (pcase (org-link-get-parameter type :face)
  4524. ((and (pred functionp) face) (funcall face path))
  4525. ((and (pred facep) face) face)
  4526. ((and (pred consp) face) face) ;anonymous
  4527. (_ 'org-link)))
  4528. (properties ;for link's visible part
  4529. (list 'mouse-face (or (org-link-get-parameter type :mouse-face)
  4530. 'highlight)
  4531. 'keymap (or (org-link-get-parameter type :keymap)
  4532. org-mouse-map)
  4533. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  4534. ((and (pred stringp) echo) echo)
  4535. ((and (pred functionp) echo) echo)
  4536. (_ (concat "LINK: " link)))
  4537. 'htmlize-link (pcase (org-link-get-parameter type
  4538. :htmlize-link)
  4539. ((and (pred functionp) f) (funcall f))
  4540. (_ `(:uri ,link)))
  4541. 'font-lock-multiline t)))
  4542. (org-remove-flyspell-overlays-in start end)
  4543. (org-rear-nonsticky-at end)
  4544. (if (not (eq 'bracket style))
  4545. (progn
  4546. (add-face-text-property start end face-property)
  4547. (add-text-properties start end properties))
  4548. ;; Initialise folding when used outside org-mode.
  4549. (unless (or (derived-mode-p 'org-mode)
  4550. (and (org-fold-folding-spec-p 'org-link-description)
  4551. (org-fold-folding-spec-p 'org-link)))
  4552. (org-fold-initialize (or (and (stringp org-ellipsis) (not (equal "" org-ellipsis)) org-ellipsis)
  4553. "...")))
  4554. ;; Handle invisible parts in bracket links.
  4555. (let ((spec (or (org-link-get-parameter type :display)
  4556. 'org-link)))
  4557. (unless (org-fold-folding-spec-p spec)
  4558. (org-fold-add-folding-spec spec
  4559. (cdr org-link--link-folding-spec)
  4560. nil
  4561. 'append)
  4562. (org-fold-core-set-folding-spec-property spec :visible t))
  4563. (org-fold-region start end nil 'org-link)
  4564. (org-fold-region start end nil 'org-link-description)
  4565. ;; We are folding the whole emphasised text with SPEC
  4566. ;; first. It makes everything invisible (or whatever
  4567. ;; the user wants).
  4568. (org-fold-region start end t spec)
  4569. ;; The visible part of the text is folded using
  4570. ;; 'org-link-description, which is forcing this part of
  4571. ;; the text to be visible.
  4572. (org-fold-region visible-start visible-end t 'org-link-description)
  4573. (add-text-properties start end properties)
  4574. (add-face-text-property start end face-property)
  4575. (org-rear-nonsticky-at visible-start)
  4576. (org-rear-nonsticky-at visible-end)))
  4577. (let ((f (org-link-get-parameter type :activate-func)))
  4578. (when (functionp f)
  4579. (funcall f start end path (eq style 'bracket))))
  4580. (throw :exit t))))) ;signal success
  4581. nil))
  4582. (defsubst org-activate-links (limit)
  4583. "Add link properties to links.
  4584. This includes angle, plain, and bracket links."
  4585. (if (eq org-fold-core-style 'text-properties)
  4586. (org-activate-links--text-properties limit)
  4587. (org-activate-links--overlays limit)))
  4588. (defun org-activate-code (limit)
  4589. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  4590. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4591. (remove-text-properties (match-beginning 0) (match-end 0)
  4592. '(display t invisible t intangible t))
  4593. t))
  4594. (defcustom org-src-fontify-natively t
  4595. "When non-nil, fontify code in code blocks.
  4596. See also the `org-block' face."
  4597. :type 'boolean
  4598. :version "26.1"
  4599. :package-version '(Org . "8.3")
  4600. :group 'org-appearance
  4601. :group 'org-babel)
  4602. (defcustom org-allow-promoting-top-level-subtree nil
  4603. "When non-nil, allow promoting a top level subtree.
  4604. The leading star of the top level headline will be replaced
  4605. by a #."
  4606. :type 'boolean
  4607. :version "24.1"
  4608. :group 'org-appearance)
  4609. (defun org-fontify-meta-lines-and-blocks (limit)
  4610. (condition-case nil
  4611. (org-fontify-meta-lines-and-blocks-1 limit)
  4612. (error (message "Org mode fontification error in %S at %d"
  4613. (current-buffer)
  4614. (line-number-at-pos)))))
  4615. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  4616. "Fontify #+ lines and blocks."
  4617. (let ((case-fold-search t))
  4618. (when (re-search-forward
  4619. (rx bol (group (zero-or-more (any " \t")) "#"
  4620. (group (group (or (seq "+" (one-or-more (any "a-zA-Z")) (optional ":"))
  4621. (any " \t")
  4622. eol))
  4623. (optional (group "_" (group (one-or-more (any "a-zA-Z"))))))
  4624. (zero-or-more (any " \t"))
  4625. (group (group (zero-or-more (not (any " \t\n"))))
  4626. (zero-or-more (any " \t"))
  4627. (group (zero-or-more any)))))
  4628. limit t)
  4629. (let ((beg (match-beginning 0))
  4630. (end-of-beginline (match-end 0))
  4631. ;; Including \n at end of #+begin line will include \n
  4632. ;; after the end of block content.
  4633. (block-start (match-end 0))
  4634. (block-end nil)
  4635. (lang (match-string 7)) ; The language, if it is a source block.
  4636. (bol-after-beginline (line-beginning-position 2))
  4637. (dc1 (downcase (match-string 2)))
  4638. (dc3 (downcase (match-string 3)))
  4639. (whole-blockline org-fontify-whole-block-delimiter-line)
  4640. beg-of-endline end-of-endline nl-before-endline quoting block-type)
  4641. (cond
  4642. ((and (match-end 4) (equal dc3 "+begin"))
  4643. ;; Truly a block
  4644. (setq block-type (downcase (match-string 5))
  4645. ;; Src, example, export, maybe more.
  4646. quoting (member block-type org-protecting-blocks))
  4647. (when (re-search-forward
  4648. (rx-to-string `(group bol (or (seq (one-or-more "*") space)
  4649. (seq (zero-or-more (any " \t"))
  4650. "#+end"
  4651. ,(match-string 4)
  4652. word-end
  4653. (zero-or-more any)))))
  4654. ;; We look further than LIMIT on purpose.
  4655. nil t)
  4656. ;; We do have a matching #+end line.
  4657. (setq beg-of-endline (match-beginning 0)
  4658. end-of-endline (match-end 0)
  4659. nl-before-endline (1- (match-beginning 0)))
  4660. (setq block-end (match-beginning 0)) ; Include the final newline.
  4661. (when quoting
  4662. (org-remove-flyspell-overlays-in bol-after-beginline nl-before-endline)
  4663. (remove-text-properties beg end-of-endline
  4664. '(display t invisible t intangible t)))
  4665. (add-text-properties
  4666. beg end-of-endline '(font-lock-fontified t font-lock-multiline t))
  4667. (org-remove-flyspell-overlays-in beg bol-after-beginline)
  4668. (org-remove-flyspell-overlays-in nl-before-endline end-of-endline)
  4669. (cond
  4670. ((and lang (not (string= lang "")) org-src-fontify-natively)
  4671. (save-match-data
  4672. (org-src-font-lock-fontify-block lang block-start block-end))
  4673. (add-text-properties bol-after-beginline block-end '(src-block t)))
  4674. (quoting
  4675. (add-text-properties
  4676. bol-after-beginline beg-of-endline
  4677. (list 'face
  4678. (list :inherit
  4679. (let ((face-name
  4680. (intern (format "org-block-%s" lang))))
  4681. (append (and (facep face-name) (list face-name))
  4682. '(org-block)))))))
  4683. ((not org-fontify-quote-and-verse-blocks))
  4684. ((string= block-type "quote")
  4685. (add-face-text-property
  4686. bol-after-beginline beg-of-endline 'org-quote t))
  4687. ((string= block-type "verse")
  4688. (add-face-text-property
  4689. bol-after-beginline beg-of-endline 'org-verse t)))
  4690. ;; Fontify the #+begin and #+end lines of the blocks
  4691. (add-text-properties
  4692. beg (if whole-blockline bol-after-beginline end-of-beginline)
  4693. '(face org-block-begin-line))
  4694. (unless (eq (char-after beg-of-endline) ?*)
  4695. (add-text-properties
  4696. beg-of-endline
  4697. (if whole-blockline
  4698. (let ((beg-of-next-line (1+ end-of-endline)))
  4699. (min (point-max) beg-of-next-line))
  4700. (min (point-max) end-of-endline))
  4701. '(face org-block-end-line)))
  4702. t))
  4703. ((member dc1 '("+title:" "+subtitle:" "+author:" "+email:" "+date:"))
  4704. (org-remove-flyspell-overlays-in
  4705. (match-beginning 0)
  4706. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  4707. (add-text-properties
  4708. beg (match-end 3)
  4709. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  4710. '(font-lock-fontified t invisible t)
  4711. '(font-lock-fontified t face org-document-info-keyword)))
  4712. (add-text-properties
  4713. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  4714. (if (string-equal dc1 "+title:")
  4715. '(font-lock-fontified t face org-document-title)
  4716. '(font-lock-fontified t face org-document-info))))
  4717. ((string-prefix-p "+caption" dc1)
  4718. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  4719. (remove-text-properties (match-beginning 0) (match-end 0)
  4720. '(display t invisible t intangible t))
  4721. ;; Handle short captions
  4722. (save-excursion
  4723. (beginning-of-line)
  4724. (looking-at (rx (group (zero-or-more (any " \t"))
  4725. "#+caption"
  4726. (optional "[" (zero-or-more any) "]")
  4727. ":")
  4728. (zero-or-more (any " \t")))))
  4729. (add-text-properties (line-beginning-position) (match-end 1)
  4730. '(font-lock-fontified t face org-meta-line))
  4731. (add-text-properties (match-end 0) (line-end-position)
  4732. '(font-lock-fontified t face org-block))
  4733. t)
  4734. ((member dc3 '(" " ""))
  4735. ;; Just a comment, the plus was not there
  4736. (org-remove-flyspell-overlays-in beg (match-end 0))
  4737. (add-text-properties
  4738. beg (match-end 0)
  4739. '(font-lock-fontified t face font-lock-comment-face)))
  4740. (t ;; Just any other in-buffer setting, but not indented
  4741. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4742. (remove-text-properties (match-beginning 0) (match-end 0)
  4743. '(display t invisible t intangible t))
  4744. (add-text-properties beg (match-end 0)
  4745. '(font-lock-fontified t face org-meta-line))
  4746. t))))))
  4747. (defun org-fontify-drawers (limit)
  4748. "Fontify drawers."
  4749. (when (re-search-forward org-drawer-regexp limit t)
  4750. (add-text-properties (1- (match-beginning 1)) (1+ (match-end 1))
  4751. '(font-lock-fontified t face org-drawer))
  4752. (org-remove-flyspell-overlays-in
  4753. (line-beginning-position) (line-beginning-position 2))
  4754. t))
  4755. (defun org-fontify-macros (limit)
  4756. "Fontify macros."
  4757. (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
  4758. (let ((begin (match-beginning 0))
  4759. (opening-end (match-beginning 1)))
  4760. (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
  4761. (match-string 1))
  4762. (let ((end (match-end 1))
  4763. (closing-start (match-beginning 1)))
  4764. (add-text-properties
  4765. begin end
  4766. '(font-lock-multiline t font-lock-fontified t face org-macro))
  4767. (org-remove-flyspell-overlays-in begin end)
  4768. (when org-hide-macro-markers
  4769. (add-text-properties begin opening-end '(invisible t))
  4770. (add-text-properties closing-start end '(invisible t)))
  4771. t)))))
  4772. (defun org-fontify-extend-region (beg end _old-len)
  4773. (let ((end (if (progn (goto-char end) (looking-at-p "^[*#]"))
  4774. (1+ end) end))
  4775. (begin-re "\\(\\\\\\[\\|\\(#\\+begin_\\|\\\\begin{\\)\\S-+\\)")
  4776. (end-re "\\(\\\\\\]\\|\\(#\\+end_\\|\\\\end{\\)\\S-+\\)")
  4777. (extend
  4778. (lambda (r1 r2 dir)
  4779. (let ((re (replace-regexp-in-string
  4780. "\\(begin\\|end\\)" r1
  4781. (replace-regexp-in-string
  4782. "[][]" r2
  4783. (match-string-no-properties 0)))))
  4784. (re-search-forward (regexp-quote re) nil t dir)))))
  4785. (goto-char beg)
  4786. (back-to-indentation)
  4787. (save-match-data
  4788. (cond ((looking-at end-re)
  4789. (cons (or (funcall extend "begin" "[" -1) beg) end))
  4790. ((looking-at begin-re)
  4791. (cons beg (or (funcall extend "end" "]" 1) end)))
  4792. (t (cons beg end))))))
  4793. (defun org-activate-footnote-links (limit)
  4794. "Add text properties for footnotes."
  4795. (let ((fn (org-footnote-next-reference-or-definition limit)))
  4796. (when fn
  4797. (let* ((beg (nth 1 fn))
  4798. (end (nth 2 fn))
  4799. (label (car fn))
  4800. (referencep (/= (line-beginning-position) beg)))
  4801. (when (and referencep (nth 3 fn))
  4802. (save-excursion
  4803. (goto-char beg)
  4804. (search-forward (or label "fn:"))
  4805. (org-remove-flyspell-overlays-in beg (match-end 0))))
  4806. (add-text-properties beg end
  4807. (list 'mouse-face 'highlight
  4808. 'keymap org-mouse-map
  4809. 'help-echo
  4810. (if referencep "Footnote reference"
  4811. "Footnote definition")
  4812. 'font-lock-fontified t
  4813. 'font-lock-multiline t
  4814. 'face 'org-footnote))))))
  4815. (defun org-activate-dates (limit)
  4816. "Add text properties for dates."
  4817. (when (and (re-search-forward org-tsr-regexp-both limit t)
  4818. (not (equal (char-before (match-beginning 0)) 91)))
  4819. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4820. (add-text-properties (match-beginning 0) (match-end 0)
  4821. (list 'mouse-face 'highlight
  4822. 'keymap org-mouse-map))
  4823. (org-rear-nonsticky-at (match-end 0))
  4824. (when org-display-custom-times
  4825. ;; If it's a date range, activate custom time for second date.
  4826. (when (match-end 3)
  4827. (org-display-custom-time (match-beginning 3) (match-end 3)))
  4828. (org-display-custom-time (match-beginning 1) (match-end 1)))
  4829. t))
  4830. (defun org-activate-target-links (limit)
  4831. "Add text properties for target matches."
  4832. (when org-target-link-regexp
  4833. (let ((case-fold-search t))
  4834. ;; `org-target-link-regexp' matches one character before the
  4835. ;; actual target.
  4836. (unless (bolp) (forward-char -1))
  4837. (when (re-search-forward org-target-link-regexp limit t)
  4838. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4839. (add-text-properties (match-beginning 1) (match-end 1)
  4840. (list 'mouse-face 'highlight
  4841. 'keymap org-mouse-map
  4842. 'help-echo "Radio target link"
  4843. 'org-linked-text t))
  4844. (org-rear-nonsticky-at (match-end 1))
  4845. t))))
  4846. (defvar org-latex-and-related-regexp nil
  4847. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  4848. (defun org-compute-latex-and-related-regexp ()
  4849. "Compute regular expression for LaTeX, entities and sub/superscript.
  4850. Result depends on variable `org-highlight-latex-and-related'."
  4851. (let ((re-sub
  4852. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  4853. ((eq org-use-sub-superscripts '{})
  4854. (list org-match-substring-with-braces-regexp))
  4855. (org-use-sub-superscripts (list org-match-substring-regexp))))
  4856. (re-latex
  4857. (when (or (memq 'latex org-highlight-latex-and-related)
  4858. (memq 'native org-highlight-latex-and-related))
  4859. (let ((matchers (plist-get org-format-latex-options :matchers)))
  4860. (delq nil
  4861. (mapcar (lambda (x)
  4862. (and (member (car x) matchers) (nth 1 x)))
  4863. org-latex-regexps)))))
  4864. (re-entities
  4865. (when (memq 'entities org-highlight-latex-and-related)
  4866. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\
  4867. \\($\\|{}\\|[^[:alpha:]]\\)"))))
  4868. (setq-local org-latex-and-related-regexp
  4869. (mapconcat #'identity
  4870. (append re-latex re-entities re-sub)
  4871. "\\|"))))
  4872. (defun org-do-latex-and-related (limit)
  4873. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  4874. Stop at first highlighted object, if any. Return t if some
  4875. highlighting was done, nil otherwise."
  4876. (when (org-string-nw-p org-latex-and-related-regexp)
  4877. (let ((latex-prefix-re (rx (or "$" "\\(" "\\[")))
  4878. (blank-line-re (rx (and "\n" (zero-or-more (or " " "\t")) "\n"))))
  4879. (catch 'found
  4880. (while (and (< (point) limit)
  4881. (re-search-forward org-latex-and-related-regexp nil t))
  4882. (cond
  4883. ((>= (match-beginning 0) limit)
  4884. (throw 'found nil))
  4885. ((cl-some (lambda (f)
  4886. (memq f '(org-code org-verbatim underline
  4887. org-special-keyword)))
  4888. (save-excursion
  4889. (goto-char (1+ (match-beginning 0)))
  4890. (face-at-point nil t))))
  4891. ;; Try to limit false positives. In this case, ignore
  4892. ;; $$...$$, \(...\), and \[...\] LaTeX constructs if they
  4893. ;; contain an empty line.
  4894. ((save-excursion
  4895. (goto-char (match-beginning 0))
  4896. (and (looking-at-p latex-prefix-re)
  4897. (save-match-data
  4898. (re-search-forward blank-line-re (1- (match-end 0)) t)))))
  4899. (t
  4900. (let* ((offset (if (memq (char-after (1+ (match-beginning 0)))
  4901. '(?_ ?^))
  4902. 1
  4903. 0))
  4904. (start (+ offset (match-beginning 0)))
  4905. (end (match-end 0)))
  4906. (if (memq 'native org-highlight-latex-and-related)
  4907. (org-src-font-lock-fontify-block "latex" start end)
  4908. (font-lock-prepend-text-property start end
  4909. 'face 'org-latex-and-related))
  4910. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  4911. '(font-lock-multiline t))
  4912. (throw 'found t)))))
  4913. nil))))
  4914. (defun org-restart-font-lock ()
  4915. "Restart `font-lock-mode', to force refontification."
  4916. (when font-lock-mode
  4917. (font-lock-mode -1)
  4918. (font-lock-mode 1)))
  4919. (defun org-activate-tags (limit)
  4920. (when (re-search-forward org-tag-line-re limit t)
  4921. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4922. (add-text-properties (match-beginning 1) (match-end 1)
  4923. (list 'mouse-face 'highlight
  4924. 'keymap org-mouse-map))
  4925. (org-rear-nonsticky-at (match-end 1))
  4926. t))
  4927. (defun org-outline-level ()
  4928. "Compute the outline level of the heading at point.
  4929. If this is called at a normal headline, the level is the number
  4930. of stars. Use `org-reduced-level' to remove the effect of
  4931. `org-odd-levels'. Unlike to `org-current-level', this function
  4932. takes into consideration inlinetasks."
  4933. (org-with-wide-buffer
  4934. (end-of-line)
  4935. (if (re-search-backward org-outline-regexp-bol nil t)
  4936. (1- (- (match-end 0) (match-beginning 0)))
  4937. 0)))
  4938. (defvar org-font-lock-keywords nil)
  4939. (defsubst org-re-property (property &optional literal allow-null value)
  4940. "Return a regexp matching a PROPERTY line.
  4941. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  4942. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  4943. non-nil, match properties even without a value.
  4944. Match group 3 is set to the value when it exists. If there is no
  4945. value and ALLOW-NULL is non-nil, it is set to the empty string.
  4946. With optional argument VALUE, match only property lines with
  4947. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  4948. unless LITERAL is non-nil."
  4949. (concat
  4950. "^\\(?4:[ \t]*\\)"
  4951. (format "\\(?1::\\(?2:%s\\):\\)"
  4952. (if literal property (regexp-quote property)))
  4953. (cond (value
  4954. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  4955. (if literal value (regexp-quote value))))
  4956. (allow-null
  4957. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  4958. (t
  4959. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  4960. (defconst org-property-re
  4961. (org-re-property "\\S-+" 'literal t)
  4962. "Regular expression matching a property line.
  4963. There are four matching groups:
  4964. 1: :PROPKEY: including the leading and trailing colon,
  4965. 2: PROPKEY without the leading and trailing colon,
  4966. 3: PROPVAL without leading or trailing spaces,
  4967. 4: the indentation of the current line,
  4968. 5: trailing whitespace.")
  4969. (defvar org-font-lock-hook nil
  4970. "Functions to be called for special font lock stuff.")
  4971. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  4972. (defvar org-font-lock-set-keywords-hook nil
  4973. "Functions that can manipulate `org-font-lock-extra-keywords'.
  4974. This is called after `org-font-lock-extra-keywords' is defined, but before
  4975. it is installed to be used by font lock. This can be useful if something
  4976. needs to be inserted at a specific position in the font-lock sequence.")
  4977. (defun org-font-lock-hook (limit)
  4978. "Run `org-font-lock-hook' within LIMIT."
  4979. (run-hook-with-args 'org-font-lock-hook limit))
  4980. (defun org-set-font-lock-defaults ()
  4981. "Set font lock defaults for the current buffer."
  4982. (let ((org-font-lock-extra-keywords
  4983. (list
  4984. ;; Call the hook
  4985. '(org-font-lock-hook)
  4986. ;; Headlines
  4987. `(,(if org-fontify-whole-heading-line
  4988. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  4989. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  4990. (1 (org-get-level-face 1))
  4991. (2 (org-get-level-face 2))
  4992. (3 (org-get-level-face 3)))
  4993. ;; Table lines
  4994. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  4995. (1 'org-table t))
  4996. ;; Table internals
  4997. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  4998. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  4999. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  5000. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  5001. ;; Properties
  5002. (list org-property-re
  5003. '(1 'org-special-keyword t)
  5004. '(3 'org-property-value t))
  5005. ;; Drawers
  5006. '(org-fontify-drawers)
  5007. ;; Link related fontification.
  5008. '(org-activate-links)
  5009. (when (memq 'tag org-highlight-links) '(org-activate-tags (1 'org-tag prepend)))
  5010. (when (memq 'radio org-highlight-links) '(org-activate-target-links (1 'org-link t)))
  5011. (when (memq 'date org-highlight-links) '(org-activate-dates (0 'org-date t)))
  5012. (when (memq 'footnote org-highlight-links) '(org-activate-footnote-links))
  5013. ;; Targets.
  5014. (list org-radio-target-regexp '(0 'org-target t))
  5015. (list org-target-regexp '(0 'org-target t))
  5016. ;; Diary sexps.
  5017. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5018. ;; Macro
  5019. '(org-fontify-macros)
  5020. ;; TODO keyword
  5021. (list (format org-heading-keyword-regexp-format
  5022. org-todo-regexp)
  5023. '(2 (org-get-todo-face 2) prepend))
  5024. ;; TODO
  5025. (when org-fontify-todo-headline
  5026. (list (format org-heading-keyword-regexp-format
  5027. (concat
  5028. "\\(?:"
  5029. (mapconcat 'regexp-quote org-not-done-keywords "\\|")
  5030. "\\)"))
  5031. '(2 'org-headline-todo prepend)))
  5032. ;; DONE
  5033. (when org-fontify-done-headline
  5034. (list (format org-heading-keyword-regexp-format
  5035. (concat
  5036. "\\(?:"
  5037. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5038. "\\)"))
  5039. '(2 'org-headline-done prepend)))
  5040. ;; Priorities
  5041. '(org-font-lock-add-priority-faces)
  5042. ;; Tags
  5043. '(org-font-lock-add-tag-faces)
  5044. ;; Tags groups
  5045. (when (and org-group-tags org-tag-groups-alist)
  5046. (list (concat org-outline-regexp-bol ".+\\(:"
  5047. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5048. ":\\).*$")
  5049. '(1 'org-tag-group prepend)))
  5050. ;; Special keywords
  5051. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5052. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5053. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5054. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5055. ;; Emphasis
  5056. (when org-fontify-emphasized-text '(org-do-emphasis-faces))
  5057. ;; Checkboxes
  5058. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5059. 1 'org-checkbox prepend)
  5060. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5061. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5062. (0 (org-get-checkbox-statistics-face) prepend)))
  5063. ;; Description list items
  5064. '("\\(?:^[ \t]*[-+]\\|^[ \t]+[*]\\)[ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5065. 1 'org-list-dt prepend)
  5066. ;; Inline export snippets
  5067. '("\\(@@\\)\\([a-z-]+:\\).*?\\(@@\\)"
  5068. (1 'font-lock-comment-face t)
  5069. (2 'org-tag t)
  5070. (3 'font-lock-comment-face t))
  5071. ;; ARCHIVEd headings
  5072. (list (concat
  5073. org-outline-regexp-bol
  5074. "\\(.*:" org-archive-tag ":.*\\)")
  5075. '(1 'org-archived prepend))
  5076. ;; Specials
  5077. '(org-do-latex-and-related)
  5078. '(org-fontify-entities)
  5079. '(org-raise-scripts)
  5080. ;; Code
  5081. '(org-activate-code (1 'org-code t))
  5082. ;; COMMENT
  5083. (list (format
  5084. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5085. org-todo-regexp
  5086. org-comment-string)
  5087. '(9 'org-special-keyword t))
  5088. ;; Blocks and meta lines
  5089. '(org-fontify-meta-lines-and-blocks)
  5090. '(org-fontify-inline-src-blocks)
  5091. ;; Citations. When an activate processor is specified, if
  5092. ;; specified, try loading it beforehand.
  5093. (progn
  5094. (unless (null org-cite-activate-processor)
  5095. (org-cite-try-load-processor org-cite-activate-processor))
  5096. '(org-cite-activate)))))
  5097. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5098. (run-hooks 'org-font-lock-set-keywords-hook)
  5099. ;; Now set the full font-lock-keywords
  5100. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5101. (setq-local font-lock-defaults
  5102. '(org-font-lock-keywords t nil nil backward-paragraph))
  5103. (setq-local font-lock-extend-after-change-region-function
  5104. #'org-fontify-extend-region)
  5105. (kill-local-variable 'font-lock-keywords)
  5106. nil))
  5107. (defun org-toggle-pretty-entities ()
  5108. "Toggle the composition display of entities as UTF8 characters."
  5109. (interactive)
  5110. (setq-local org-pretty-entities (not org-pretty-entities))
  5111. (org-restart-font-lock)
  5112. (if org-pretty-entities
  5113. (message "Entities are now displayed as UTF8 characters")
  5114. (save-restriction
  5115. (widen)
  5116. (decompose-region (point-min) (point-max))
  5117. (message "Entities are now displayed as plain text"))))
  5118. (defvar-local org-custom-properties-overlays nil
  5119. "List of overlays used for custom properties.")
  5120. (defun org-toggle-custom-properties-visibility ()
  5121. "Display or hide properties in `org-custom-properties'."
  5122. (interactive)
  5123. (if org-custom-properties-overlays
  5124. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5125. (setq org-custom-properties-overlays nil))
  5126. (when org-custom-properties
  5127. (org-with-wide-buffer
  5128. (goto-char (point-min))
  5129. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5130. (while (re-search-forward regexp nil t)
  5131. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5132. (when (and end (< (point) end))
  5133. ;; Hide first custom property in current drawer.
  5134. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5135. (overlay-put o 'invisible t)
  5136. (overlay-put o 'org-custom-property t)
  5137. (push o org-custom-properties-overlays))
  5138. ;; Hide additional custom properties in the same drawer.
  5139. (while (re-search-forward regexp end t)
  5140. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5141. (overlay-put o 'invisible t)
  5142. (overlay-put o 'org-custom-property t)
  5143. (push o org-custom-properties-overlays)))))
  5144. ;; Each entry is limited to a single property drawer.
  5145. (outline-next-heading)))))))
  5146. (defun org-fontify-entities (limit)
  5147. "Find an entity to fontify."
  5148. (let (ee)
  5149. (when org-pretty-entities
  5150. (catch 'match
  5151. ;; "\_ "-family is left out on purpose. Only the first one,
  5152. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5153. ;; confusing when adding a second white space character.
  5154. (while (re-search-forward
  5155. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5156. limit t)
  5157. (when (and (not (org-at-comment-p))
  5158. (setq ee (org-entity-get (match-string 1)))
  5159. (= (length (nth 6 ee)) 1))
  5160. (let* ((end (if (equal (match-string 2) "{}")
  5161. (match-end 2)
  5162. (match-end 1))))
  5163. (add-text-properties
  5164. (match-beginning 0) end
  5165. (list 'font-lock-fontified t))
  5166. (compose-region (match-beginning 0) end
  5167. (nth 6 ee) nil)
  5168. (backward-char 1)
  5169. (throw 'match t))))
  5170. nil))))
  5171. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5172. "Fontify string S like in Org mode."
  5173. (with-temp-buffer
  5174. (insert s)
  5175. (let ((org-odd-levels-only odd-levels))
  5176. (org-mode)
  5177. (font-lock-ensure)
  5178. (if org-link-descriptive
  5179. (org-link-display-format
  5180. (buffer-string))
  5181. (buffer-string)))))
  5182. (defun org-get-level-face (n)
  5183. "Get the right face for match N in font-lock matching of headlines."
  5184. (let* ((org-l0 (- (match-end 2) (match-beginning 1) 1))
  5185. (org-l (if org-odd-levels-only (1+ (/ org-l0 2)) org-l0))
  5186. (org-f (if org-cycle-level-faces
  5187. (nth (% (1- org-l) org-n-level-faces) org-level-faces)
  5188. (nth (1- (min org-l org-n-level-faces)) org-level-faces))))
  5189. (cond
  5190. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5191. ((eq n 2) org-f)
  5192. (t (unless org-level-color-stars-only org-f)))))
  5193. (defun org-face-from-face-or-color (context inherit face-or-color)
  5194. "Create a face list that inherits INHERIT, but sets the foreground color.
  5195. When FACE-OR-COLOR is not a string, just return it."
  5196. (if (stringp face-or-color)
  5197. (list :inherit inherit
  5198. (cdr (assoc context org-faces-easy-properties))
  5199. face-or-color)
  5200. face-or-color))
  5201. (defun org-get-todo-face (kwd)
  5202. "Get the right face for a TODO keyword KWD.
  5203. If KWD is a number, get the corresponding match group."
  5204. (when (numberp kwd) (setq kwd (match-string kwd)))
  5205. (or (org-face-from-face-or-color
  5206. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5207. (and (member kwd org-done-keywords) 'org-done)
  5208. 'org-todo))
  5209. (defun org-get-priority-face (priority)
  5210. "Get the right face for PRIORITY.
  5211. PRIORITY is a character."
  5212. (or (org-face-from-face-or-color
  5213. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5214. 'org-priority))
  5215. (defun org-get-tag-face (tag)
  5216. "Get the right face for TAG.
  5217. If TAG is a number, get the corresponding match group."
  5218. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5219. (or (org-face-from-face-or-color
  5220. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5221. 'org-tag)))
  5222. (defvar org-priority-regexp) ; defined later in the file
  5223. (defun org-font-lock-add-priority-faces (limit)
  5224. "Add the special priority faces."
  5225. (while (re-search-forward (concat "^\\*+" org-priority-regexp) limit t)
  5226. (let ((beg (match-beginning 1))
  5227. (end (1+ (match-end 2))))
  5228. (add-face-text-property
  5229. beg end
  5230. (org-get-priority-face (string-to-char (match-string 2))))
  5231. (add-text-properties
  5232. beg end
  5233. (list 'font-lock-fontified t)))))
  5234. (defun org-font-lock-add-tag-faces (limit)
  5235. "Add the special tag faces."
  5236. (when (and org-tag-faces org-tags-special-faces-re)
  5237. (while (re-search-forward org-tags-special-faces-re limit t)
  5238. (add-face-text-property
  5239. (match-beginning 1)
  5240. (match-end 1)
  5241. (org-get-tag-face 1))
  5242. (add-text-properties (match-beginning 1) (match-end 1)
  5243. (list 'font-lock-fontified t))
  5244. (backward-char 1))))
  5245. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5246. "Remove fontification and activation overlays from links."
  5247. (font-lock-default-unfontify-region beg end)
  5248. (let* ((buffer-undo-list t)
  5249. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5250. (inhibit-modification-hooks t)
  5251. deactivate-mark buffer-file-name buffer-file-truename)
  5252. (decompose-region beg end)
  5253. (remove-text-properties beg end
  5254. '(mouse-face t keymap t org-linked-text t
  5255. invisible t intangible t
  5256. org-emphasis t))
  5257. (org-fold-region beg end nil 'org-link)
  5258. (org-fold-region beg end nil 'org-link-description)
  5259. (org-fold-core-update-optimisation beg end)
  5260. (org-remove-font-lock-display-properties beg end)))
  5261. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5262. ((raise 0.3) (height 0.7))
  5263. ((raise -0.5))
  5264. ((raise 0.5)))
  5265. "Display properties for showing superscripts and subscripts.")
  5266. (defun org-remove-font-lock-display-properties (beg end)
  5267. "Remove specific display properties that have been added by font lock.
  5268. The will remove the raise properties that are used to show superscripts
  5269. and subscripts."
  5270. (let (next prop)
  5271. (while (< beg end)
  5272. (setq next (next-single-property-change beg 'display nil end)
  5273. prop (get-text-property beg 'display))
  5274. (when (member prop org-script-display)
  5275. (put-text-property beg next 'display nil))
  5276. (setq beg next))))
  5277. (defun org-raise-scripts (limit)
  5278. "Add raise properties to sub/superscripts."
  5279. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5280. (re-search-forward
  5281. (if (eq org-use-sub-superscripts t)
  5282. org-match-substring-regexp
  5283. org-match-substring-with-braces-regexp)
  5284. limit t))
  5285. (let* ((pos (point)) table-p comment-p
  5286. (mpos (match-beginning 3))
  5287. (emph-p (get-text-property mpos 'org-emphasis))
  5288. (link-p (get-text-property mpos 'mouse-face))
  5289. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5290. (goto-char (point-at-bol))
  5291. (setq table-p (looking-at-p org-table-dataline-regexp)
  5292. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5293. (goto-char pos)
  5294. ;; Handle a_b^c
  5295. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5296. (unless (or comment-p emph-p link-p keyw-p)
  5297. (put-text-property (match-beginning 3) (match-end 0)
  5298. 'display
  5299. (if (equal (char-after (match-beginning 2)) ?^)
  5300. (nth (if table-p 3 1) org-script-display)
  5301. (nth (if table-p 2 0) org-script-display)))
  5302. (put-text-property (match-beginning 2) (match-end 3)
  5303. 'org-emphasis t)
  5304. (add-text-properties (match-beginning 2) (match-end 2)
  5305. (list 'invisible t))
  5306. (when (and (eq (char-after (match-beginning 3)) ?{)
  5307. (eq (char-before (match-end 3)) ?}))
  5308. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5309. (list 'invisible t))
  5310. (add-text-properties (1- (match-end 3)) (match-end 3)
  5311. (list 'invisible t))))
  5312. t)))
  5313. (defun org-remove-empty-overlays-at (pos)
  5314. "Remove outline overlays that do not contain non-white stuff."
  5315. (dolist (o (overlays-at pos))
  5316. (and (eq 'outline (overlay-get o 'invisible))
  5317. (not (string-match-p
  5318. "\\S-" (buffer-substring (overlay-start o)
  5319. (overlay-end o))))
  5320. (delete-overlay o))))
  5321. ;; FIXME: This function is unused.
  5322. (defun org-show-empty-lines-in-parent ()
  5323. "Move to the parent and re-show empty lines before visible headlines."
  5324. (save-excursion
  5325. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  5326. (org-cycle-show-empty-lines context))))
  5327. (defun org-files-list ()
  5328. "Return `org-agenda-files' list, plus all open Org files.
  5329. This is useful for operations that need to scan all of a user's
  5330. open and agenda-wise Org files."
  5331. (let ((files (mapcar #'expand-file-name (org-agenda-files))))
  5332. (dolist (buf (buffer-list))
  5333. (with-current-buffer buf
  5334. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  5335. (cl-pushnew (expand-file-name (buffer-file-name)) files
  5336. :test #'equal))))
  5337. files))
  5338. (defsubst org-entry-beginning-position ()
  5339. "Return the beginning position of the current entry."
  5340. (save-excursion (org-back-to-heading t) (point)))
  5341. (defsubst org-entry-end-position ()
  5342. "Return the end position of the current entry."
  5343. (save-excursion (outline-next-heading) (point)))
  5344. (defun org-subtree-end-visible-p ()
  5345. "Is the end of the current subtree visible?"
  5346. (pos-visible-in-window-p
  5347. (save-excursion (org-end-of-subtree t) (point))))
  5348. (defun org-first-headline-recenter ()
  5349. "Move cursor to the first headline and recenter the headline."
  5350. (let ((window (get-buffer-window)))
  5351. (when window
  5352. (goto-char (point-min))
  5353. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  5354. (set-window-start window (line-beginning-position))))))
  5355. ;; FIXME: It was in the middle of visibility section. Where should it go to?
  5356. (defvar org-called-with-limited-levels nil
  5357. "Non-nil when `org-with-limited-levels' is currently active.")
  5358. ;;; Indirect buffer display of subtrees
  5359. (defvar org-indirect-dedicated-frame nil
  5360. "This is the frame being used for indirect tree display.")
  5361. (defvar org-last-indirect-buffer nil)
  5362. (defun org-tree-to-indirect-buffer (&optional arg)
  5363. "Create indirect buffer and narrow it to current subtree.
  5364. With a numerical prefix ARG, go up to this level and then take that tree.
  5365. If ARG is negative, go up that many levels.
  5366. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  5367. indirect buffer previously made with this command, to avoid proliferation of
  5368. indirect buffers. However, when you call the command with a \
  5369. `\\[universal-argument]' prefix, or
  5370. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  5371. so that you can work with several indirect buffers at the same time. If
  5372. `org-indirect-buffer-display' is `dedicated-frame', the \
  5373. `\\[universal-argument]' prefix also
  5374. requests that a new frame be made for the new buffer, so that the dedicated
  5375. frame is not changed."
  5376. (interactive "P")
  5377. (let ((cbuf (current-buffer))
  5378. (cwin (selected-window))
  5379. (pos (point))
  5380. beg end level heading ibuf)
  5381. (save-excursion
  5382. (org-back-to-heading t)
  5383. (when (numberp arg)
  5384. (setq level (org-outline-level))
  5385. (when (< arg 0) (setq arg (+ level arg)))
  5386. (while (> (setq level (org-outline-level)) arg)
  5387. (org-up-heading-safe)))
  5388. (setq beg (point)
  5389. heading (org-get-heading 'no-tags))
  5390. (org-end-of-subtree t t)
  5391. (when (and (not (eobp)) (org-at-heading-p)) (backward-char 1))
  5392. (setq end (point)))
  5393. (when (and (buffer-live-p org-last-indirect-buffer)
  5394. (not (eq org-indirect-buffer-display 'new-frame))
  5395. (not arg))
  5396. (kill-buffer org-last-indirect-buffer))
  5397. (setq ibuf (org-get-indirect-buffer cbuf heading)
  5398. org-last-indirect-buffer ibuf)
  5399. (cond
  5400. ((or (eq org-indirect-buffer-display 'new-frame)
  5401. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  5402. (select-frame (make-frame))
  5403. (delete-other-windows)
  5404. (pop-to-buffer-same-window ibuf)
  5405. (org-set-frame-title heading))
  5406. ((eq org-indirect-buffer-display 'dedicated-frame)
  5407. (raise-frame
  5408. (select-frame (or (and org-indirect-dedicated-frame
  5409. (frame-live-p org-indirect-dedicated-frame)
  5410. org-indirect-dedicated-frame)
  5411. (setq org-indirect-dedicated-frame (make-frame)))))
  5412. (delete-other-windows)
  5413. (pop-to-buffer-same-window ibuf)
  5414. (org-set-frame-title (concat "Indirect: " heading)))
  5415. ((eq org-indirect-buffer-display 'current-window)
  5416. (pop-to-buffer-same-window ibuf))
  5417. ((eq org-indirect-buffer-display 'other-window)
  5418. (pop-to-buffer ibuf))
  5419. (t (error "Invalid value")))
  5420. (narrow-to-region beg end)
  5421. (org-fold-show-all '(headings drawers blocks))
  5422. (goto-char pos)
  5423. (run-hook-with-args 'org-cycle-hook 'all)
  5424. (and (window-live-p cwin) (select-window cwin))))
  5425. (defun org-get-indirect-buffer (&optional buffer heading)
  5426. (setq buffer (or buffer (current-buffer)))
  5427. (let ((n 1) (base (buffer-name buffer)) bname)
  5428. (while (buffer-live-p
  5429. (get-buffer
  5430. (setq bname
  5431. (concat base "-"
  5432. (if heading (concat heading "-" (number-to-string n))
  5433. (number-to-string n))))))
  5434. (setq n (1+ n)))
  5435. (condition-case nil
  5436. (let ((indirect-buffer (make-indirect-buffer buffer bname 'clone)))
  5437. ;; Decouple folding state. We need to do it manually since
  5438. ;; `make-indirect-buffer' does not run
  5439. ;; `clone-indirect-buffer-hook'.
  5440. (org-fold-core-decouple-indirect-buffer-folds)
  5441. ;; Return the buffer.
  5442. indirect-buffer)
  5443. (error (make-indirect-buffer buffer bname)))))
  5444. (defun org-set-frame-title (title)
  5445. "Set the title of the current frame to the string TITLE."
  5446. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  5447. ;;;; Structure editing
  5448. ;;; Inserting headlines
  5449. (defun org--blank-before-heading-p (&optional parent)
  5450. "Non-nil when an empty line should precede a new heading here.
  5451. When optional argument PARENT is non-nil, consider parent
  5452. headline instead of current one."
  5453. (pcase (assq 'heading org-blank-before-new-entry)
  5454. (`(heading . auto)
  5455. (save-excursion
  5456. (org-with-limited-levels
  5457. (unless (and (org-before-first-heading-p)
  5458. (not (outline-next-heading)))
  5459. (org-back-to-heading t)
  5460. (when parent (org-up-heading-safe))
  5461. (cond ((not (bobp))
  5462. (org-previous-line-empty-p))
  5463. ((outline-next-heading)
  5464. (org-previous-line-empty-p))
  5465. ;; Ignore trailing spaces on last buffer line.
  5466. ((progn (skip-chars-backward " \t") (bolp))
  5467. (org-previous-line-empty-p))
  5468. (t nil))))))
  5469. (`(heading . ,value) value)
  5470. (_ nil)))
  5471. (defun org-insert-heading (&optional arg invisible-ok top)
  5472. "Insert a new heading or an item with the same depth at point.
  5473. If point is at the beginning of a heading, insert a new heading
  5474. or a new headline above the current one. When at the beginning
  5475. of a regular line of text, turn it into a heading.
  5476. If point is in the middle of a line, split it and create a new
  5477. headline with the text in the current line after point (see
  5478. `org-M-RET-may-split-line' on how to modify this behavior). As
  5479. a special case, on a headline, splitting can only happen on the
  5480. title itself. E.g., this excludes breaking stars or tags.
  5481. With a `\\[universal-argument]' prefix, set \
  5482. `org-insert-heading-respect-content' to
  5483. a non-nil value for the duration of the command. This forces the
  5484. insertion of a heading after the current subtree, independently
  5485. on the location of point.
  5486. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  5487. insert the heading at the end of the tree
  5488. above the current heading. For example, if point is within a
  5489. 2nd-level heading, then it will insert a 2nd-level heading at
  5490. the end of the 1st-level parent subtree.
  5491. When INVISIBLE-OK is set, stop at invisible headlines when going
  5492. back. This is important for non-interactive uses of the
  5493. command.
  5494. When optional argument TOP is non-nil, insert a level 1 heading,
  5495. unconditionally."
  5496. (interactive "P")
  5497. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  5498. (level (org-current-level))
  5499. (stars (make-string (if (and level (not top)) level 1) ?*)))
  5500. (cond
  5501. ((or org-insert-heading-respect-content
  5502. (member arg '((4) (16)))
  5503. (and (not invisible-ok)
  5504. (invisible-p (max (1- (point)) (point-min)))))
  5505. ;; Position point at the location of insertion. Make sure we
  5506. ;; end up on a visible headline if INVISIBLE-OK is nil.
  5507. (org-with-limited-levels
  5508. (if (not level) (outline-next-heading) ;before first headline
  5509. (org-back-to-heading invisible-ok)
  5510. (when (equal arg '(16)) (org-up-heading-safe))
  5511. (org-end-of-subtree)))
  5512. (unless (bolp) (insert "\n"))
  5513. (when (and blank? (save-excursion
  5514. (backward-char)
  5515. (org-before-first-heading-p)))
  5516. (insert "\n")
  5517. (backward-char))
  5518. (when (and (not level) (not (eobp)) (not (bobp)))
  5519. (when (org-at-heading-p) (insert "\n"))
  5520. (backward-char))
  5521. (unless (and blank? (org-previous-line-empty-p))
  5522. (org-N-empty-lines-before-current (if blank? 1 0)))
  5523. (insert stars " ")
  5524. ;; When INVISIBLE-OK is non-nil, ensure newly created headline
  5525. ;; is visible.
  5526. (unless invisible-ok
  5527. (if (eq org-fold-core-style 'text-properties)
  5528. (cond
  5529. ((org-fold-folded-p
  5530. (max (point-min)
  5531. (1- (line-beginning-position)))
  5532. 'headline)
  5533. (org-fold-region (line-end-position 0) (line-end-position) nil 'headline))
  5534. (t nil))
  5535. (pcase (get-char-property-and-overlay (point) 'invisible)
  5536. (`(outline . ,o)
  5537. (move-overlay o (overlay-start o) (line-end-position 0)))
  5538. (_ nil)))))
  5539. ;; At a headline...
  5540. ((org-at-heading-p)
  5541. (cond ((bolp)
  5542. (when blank? (save-excursion (insert "\n")))
  5543. (save-excursion (insert stars " \n"))
  5544. (unless (and blank? (org-previous-line-empty-p))
  5545. (org-N-empty-lines-before-current (if blank? 1 0)))
  5546. (end-of-line))
  5547. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  5548. (org-match-line org-complex-heading-regexp)
  5549. (org-pos-in-match-range (point) 4))
  5550. ;; Grab the text that should moved to the new headline.
  5551. ;; Preserve tags.
  5552. (let ((split (delete-and-extract-region (point) (match-end 4))))
  5553. (if (looking-at "[ \t]*$") (replace-match "")
  5554. (org-align-tags))
  5555. (end-of-line)
  5556. (when blank? (insert "\n"))
  5557. (insert "\n" stars " ")
  5558. (when (org-string-nw-p split) (insert split))))
  5559. (t
  5560. (end-of-line)
  5561. (when blank? (insert "\n"))
  5562. (insert "\n" stars " "))))
  5563. ;; On regular text, turn line into a headline or split, if
  5564. ;; appropriate.
  5565. ((bolp)
  5566. (insert stars " ")
  5567. (unless (and blank? (org-previous-line-empty-p))
  5568. (org-N-empty-lines-before-current (if blank? 1 0))))
  5569. (t
  5570. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  5571. (end-of-line))
  5572. (insert "\n" stars " ")
  5573. (unless (and blank? (org-previous-line-empty-p))
  5574. (org-N-empty-lines-before-current (if blank? 1 0))))))
  5575. (run-hooks 'org-insert-heading-hook))
  5576. (defun org-N-empty-lines-before-current (n)
  5577. "Make the number of empty lines before current exactly N.
  5578. So this will delete or add empty lines."
  5579. (let ((column (current-column)))
  5580. (beginning-of-line)
  5581. (unless (bobp)
  5582. (let ((start (save-excursion
  5583. (skip-chars-backward " \r\t\n")
  5584. (line-end-position))))
  5585. (delete-region start (line-end-position 0))))
  5586. (insert (make-string n ?\n))
  5587. (move-to-column column)))
  5588. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  5589. "Return the heading of the current entry, without the stars.
  5590. When NO-TAGS is non-nil, don't include tags.
  5591. When NO-TODO is non-nil, don't include TODO keywords.
  5592. When NO-PRIORITY is non-nil, don't include priority cookie.
  5593. When NO-COMMENT is non-nil, don't include COMMENT string.
  5594. Return nil before first heading."
  5595. (unless (org-before-first-heading-p)
  5596. (save-excursion
  5597. (org-back-to-heading t)
  5598. (let ((case-fold-search nil))
  5599. (looking-at org-complex-heading-regexp)
  5600. ;; When using `org-fold-core--optimise-for-huge-buffers',
  5601. ;; returned text will be invisible. Clear it up.
  5602. (save-match-data
  5603. (org-fold-core-remove-optimisation (match-beginning 0) (match-end 0)))
  5604. (let ((todo (and (not no-todo) (match-string 2)))
  5605. (priority (and (not no-priority) (match-string 3)))
  5606. (headline (pcase (match-string 4)
  5607. (`nil "")
  5608. ((and (guard no-comment) h)
  5609. (replace-regexp-in-string
  5610. (eval-when-compile
  5611. (format "\\`%s[ \t]+" org-comment-string))
  5612. "" h))
  5613. (h h)))
  5614. (tags (and (not no-tags) (match-string 5))))
  5615. ;; Restore cleared optimisation.
  5616. (org-fold-core-update-optimisation (match-beginning 0) (match-end 0))
  5617. (mapconcat #'identity
  5618. (delq nil (list todo priority headline tags))
  5619. " "))))))
  5620. (defun org-heading-components ()
  5621. "Return the components of the current heading.
  5622. This is a list with the following elements:
  5623. - the level as an integer
  5624. - the reduced level, different if `org-odd-levels-only' is set.
  5625. - the TODO keyword, or nil
  5626. - the priority character, like ?A, or nil if no priority is given
  5627. - the headline text itself, or the tags string if no headline text
  5628. - the tags string, or nil."
  5629. (save-excursion
  5630. (org-back-to-heading t)
  5631. (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
  5632. (org-fold-core-remove-optimisation (match-beginning 0) (match-end 0))
  5633. (prog1
  5634. (list (length (match-string 1))
  5635. (org-reduced-level (length (match-string 1)))
  5636. (match-string-no-properties 2)
  5637. (and (match-end 3) (aref (match-string 3) 2))
  5638. (match-string-no-properties 4)
  5639. (match-string-no-properties 5))
  5640. (org-fold-core-update-optimisation (match-beginning 0) (match-end 0))))))
  5641. (defun org-get-entry ()
  5642. "Get the entry text, after heading, entire subtree."
  5643. (save-excursion
  5644. (org-back-to-heading t)
  5645. (filter-buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  5646. (defun org-edit-headline (&optional heading)
  5647. "Edit the current headline.
  5648. Set it to HEADING when provided."
  5649. (interactive)
  5650. (org-with-wide-buffer
  5651. (org-back-to-heading t)
  5652. (let ((case-fold-search nil))
  5653. (when (looking-at org-complex-heading-regexp)
  5654. (let* ((old (match-string-no-properties 4))
  5655. (new (save-match-data
  5656. (org-trim (or heading (read-string "Edit: " old))))))
  5657. (unless (equal old new)
  5658. (if old (replace-match new t t nil 4)
  5659. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  5660. (insert " " new))
  5661. (org-align-tags)
  5662. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  5663. (defun org-insert-heading-after-current ()
  5664. "Insert a new heading with same level as current, after current subtree."
  5665. (interactive)
  5666. (org-back-to-heading)
  5667. (org-insert-heading)
  5668. (org-move-subtree-down)
  5669. (end-of-line 1))
  5670. (defun org-insert-heading-respect-content (&optional invisible-ok)
  5671. "Insert heading with `org-insert-heading-respect-content' set to t."
  5672. (interactive)
  5673. (org-insert-heading '(4) invisible-ok))
  5674. (defun org-insert-todo-heading-respect-content (&optional force-state)
  5675. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  5676. (interactive)
  5677. (org-insert-todo-heading force-state '(4)))
  5678. (defun org-insert-todo-heading (arg &optional force-heading)
  5679. "Insert a new heading with the same level and TODO state as current heading.
  5680. If the heading has no TODO state, or if the state is DONE, use
  5681. the first state (TODO by default). Also with one prefix arg,
  5682. force first state. With two prefix args, force inserting at the
  5683. end of the parent subtree.
  5684. When called at a plain list item, insert a new item with an
  5685. unchecked check box."
  5686. (interactive "P")
  5687. (when (or force-heading (not (org-insert-item 'checkbox)))
  5688. (org-insert-heading (or (and (equal arg '(16)) '(16))
  5689. force-heading))
  5690. (save-excursion
  5691. (org-forward-heading-same-level -1)
  5692. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  5693. (let* ((new-mark-x
  5694. (if (or (equal arg '(4))
  5695. (not (match-beginning 2))
  5696. (member (match-string 2) org-done-keywords))
  5697. (car org-todo-keywords-1)
  5698. (match-string 2)))
  5699. (new-mark
  5700. (or
  5701. (run-hook-with-args-until-success
  5702. 'org-todo-get-default-hook new-mark-x nil)
  5703. new-mark-x)))
  5704. (beginning-of-line 1)
  5705. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  5706. (if org-treat-insert-todo-heading-as-state-change
  5707. (org-todo new-mark)
  5708. (insert new-mark " "))))
  5709. (when org-provide-todo-statistics
  5710. (org-update-parent-todo-statistics))))
  5711. (defun org-insert-subheading (arg)
  5712. "Insert a new subheading and demote it.
  5713. Works for outline headings and for plain lists alike."
  5714. (interactive "P")
  5715. (org-insert-heading arg)
  5716. (cond
  5717. ((org-at-heading-p) (org-do-demote))
  5718. ((org-at-item-p) (org-indent-item))))
  5719. (defun org-insert-todo-subheading (arg)
  5720. "Insert a new subheading with TODO keyword or checkbox and demote it.
  5721. Works for outline headings and for plain lists alike."
  5722. (interactive "P")
  5723. (org-insert-todo-heading arg)
  5724. (cond
  5725. ((org-at-heading-p) (org-do-demote))
  5726. ((org-at-item-p) (org-indent-item))))
  5727. ;;; Promotion and Demotion
  5728. (defvar org-after-demote-entry-hook nil
  5729. "Hook run after an entry has been demoted.
  5730. The cursor will be at the beginning of the entry.
  5731. When a subtree is being demoted, the hook will be called for each node.")
  5732. (defvar org-after-promote-entry-hook nil
  5733. "Hook run after an entry has been promoted.
  5734. The cursor will be at the beginning of the entry.
  5735. When a subtree is being promoted, the hook will be called for each node.")
  5736. (defun org-promote-subtree ()
  5737. "Promote the entire subtree.
  5738. See also `org-promote'."
  5739. (interactive)
  5740. (save-excursion
  5741. (org-back-to-heading t)
  5742. (combine-change-calls (point) (save-excursion (org-end-of-subtree t))
  5743. (org-with-limited-levels (org-map-tree 'org-promote))))
  5744. (org-fix-position-after-promote))
  5745. (defun org-demote-subtree ()
  5746. "Demote the entire subtree.
  5747. See `org-demote' and `org-promote'."
  5748. (interactive)
  5749. (save-excursion
  5750. (org-back-to-heading t)
  5751. (combine-change-calls (point) (save-excursion (org-end-of-subtree t))
  5752. (org-with-limited-levels (org-map-tree 'org-demote))))
  5753. (org-fix-position-after-promote))
  5754. (defun org-do-promote ()
  5755. "Promote the current heading higher up the tree.
  5756. If the region is active in `transient-mark-mode', promote all
  5757. headings in the region."
  5758. (interactive)
  5759. (save-excursion
  5760. (if (org-region-active-p)
  5761. (org-map-region 'org-promote (region-beginning) (region-end))
  5762. (org-promote)))
  5763. (org-fix-position-after-promote))
  5764. (defun org-do-demote ()
  5765. "Demote the current heading lower down the tree.
  5766. If the region is active in `transient-mark-mode', demote all
  5767. headings in the region."
  5768. (interactive)
  5769. (save-excursion
  5770. (if (org-region-active-p)
  5771. (org-map-region 'org-demote (region-beginning) (region-end))
  5772. (org-demote)))
  5773. (org-fix-position-after-promote))
  5774. (defun org-fix-position-after-promote ()
  5775. "Fix cursor position and indentation after demoting/promoting."
  5776. (let ((pos (point)))
  5777. (when (save-excursion
  5778. (beginning-of-line)
  5779. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  5780. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  5781. (cond ((eobp) (insert " "))
  5782. ((eolp) (insert " "))
  5783. ((equal (char-after) ?\s) (forward-char 1))))))
  5784. (defun org-current-level ()
  5785. "Return the level of the current entry, or nil if before the first headline.
  5786. The level is the number of stars at the beginning of the
  5787. headline. Use `org-reduced-level' to remove the effect of
  5788. `org-odd-levels'. Unlike to `org-outline-level', this function
  5789. ignores inlinetasks."
  5790. (let ((level (org-with-limited-levels (org-outline-level))))
  5791. (and (> level 0) level)))
  5792. (defun org-get-previous-line-level ()
  5793. "Return the outline depth of the last headline before the current line.
  5794. Returns 0 for the first headline in the buffer, and nil if before the
  5795. first headline."
  5796. (and (org-current-level)
  5797. (or (and (/= (line-beginning-position) (point-min))
  5798. (save-excursion (beginning-of-line 0) (org-current-level)))
  5799. 0)))
  5800. (defun org-reduced-level (l)
  5801. "Compute the effective level of a heading.
  5802. This takes into account the setting of `org-odd-levels-only'."
  5803. (cond
  5804. ((zerop l) 0)
  5805. (org-odd-levels-only (1+ (floor (/ l 2))))
  5806. (t l)))
  5807. (defun org-level-increment ()
  5808. "Return the number of stars that will be added or removed at a
  5809. time to headlines when structure editing, based on the value of
  5810. `org-odd-levels-only'."
  5811. (if org-odd-levels-only 2 1))
  5812. (defun org-get-valid-level (level &optional change)
  5813. "Rectify a level change under the influence of `org-odd-levels-only'.
  5814. LEVEL is a current level, CHANGE is by how much the level should
  5815. be modified. Even if CHANGE is nil, LEVEL may be returned
  5816. modified because even level numbers will become the next higher
  5817. odd number. Returns values greater than 0."
  5818. (if org-odd-levels-only
  5819. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  5820. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  5821. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  5822. (max 1 (+ level (or change 0)))))
  5823. (defun org-promote ()
  5824. "Promote the current heading higher up the tree."
  5825. (org-with-wide-buffer
  5826. (org-back-to-heading t)
  5827. (let* ((after-change-functions (remq 'flyspell-after-change-function
  5828. after-change-functions))
  5829. (level (save-match-data (funcall outline-level)))
  5830. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  5831. (diff (abs (- level (length up-head) -1))))
  5832. (cond
  5833. ((and (= level 1) org-allow-promoting-top-level-subtree)
  5834. (replace-match "# " nil t))
  5835. ((= level 1)
  5836. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  5837. (t (replace-match (apply #'propertize up-head (text-properties-at (match-beginning 0))) t)))
  5838. (unless (= level 1)
  5839. (when org-auto-align-tags (org-align-tags))
  5840. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  5841. (run-hooks 'org-after-promote-entry-hook))))
  5842. (defun org-demote ()
  5843. "Demote the current heading lower down the tree."
  5844. (org-with-wide-buffer
  5845. (org-back-to-heading t)
  5846. (let* ((after-change-functions (remq 'flyspell-after-change-function
  5847. after-change-functions))
  5848. (level (save-match-data (funcall outline-level)))
  5849. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  5850. (diff (abs (- level (length down-head) -1))))
  5851. (org-fold-core-ignore-fragility-checks
  5852. (replace-match (apply #'propertize down-head (text-properties-at (match-beginning 0))) t)
  5853. (when org-auto-align-tags (org-align-tags))
  5854. (when org-adapt-indentation (org-fixup-indentation diff)))
  5855. (run-hooks 'org-after-demote-entry-hook))))
  5856. (defun org-cycle-level ()
  5857. "Cycle the level of an empty headline through possible states.
  5858. This goes first to child, then to parent, level, then up the hierarchy.
  5859. After top level, it switches back to sibling level."
  5860. (interactive)
  5861. (let ((org-adapt-indentation nil))
  5862. (when (org-point-at-end-of-empty-headline)
  5863. (setq this-command 'org-cycle-level) ; Only needed for caching
  5864. (let ((cur-level (org-current-level))
  5865. (prev-level (org-get-previous-line-level)))
  5866. (cond
  5867. ;; If first headline in file, promote to top-level.
  5868. ((= prev-level 0)
  5869. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  5870. do (org-do-promote)))
  5871. ;; If same level as prev, demote one.
  5872. ((= prev-level cur-level)
  5873. (org-do-demote))
  5874. ;; If parent is top-level, promote to top level if not already.
  5875. ((= prev-level 1)
  5876. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  5877. do (org-do-promote)))
  5878. ;; If top-level, return to prev-level.
  5879. ((= cur-level 1)
  5880. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  5881. do (org-do-demote)))
  5882. ;; If less than prev-level, promote one.
  5883. ((< cur-level prev-level)
  5884. (org-do-promote))
  5885. ;; If deeper than prev-level, promote until higher than
  5886. ;; prev-level.
  5887. ((> cur-level prev-level)
  5888. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  5889. do (org-do-promote))))
  5890. t))))
  5891. (defun org-map-tree (fun)
  5892. "Call FUN for every heading underneath the current one."
  5893. (org-back-to-heading t)
  5894. (let ((level (funcall outline-level)))
  5895. (save-excursion
  5896. (funcall fun)
  5897. (while (and (progn
  5898. (outline-next-heading)
  5899. (> (funcall outline-level) level))
  5900. (not (eobp)))
  5901. (funcall fun)))))
  5902. (defun org-map-region (fun beg end)
  5903. "Call FUN for every heading between BEG and END."
  5904. (let ((org-ignore-region t))
  5905. (save-excursion
  5906. (setq end (copy-marker end))
  5907. (goto-char beg)
  5908. (when (and (re-search-forward org-outline-regexp-bol nil t)
  5909. (< (point) end))
  5910. (funcall fun))
  5911. (while (and (progn
  5912. (outline-next-heading)
  5913. (< (point) end))
  5914. (not (eobp)))
  5915. (funcall fun)))))
  5916. (defun org-fixup-indentation (diff)
  5917. "Change the indentation in the current entry by DIFF.
  5918. DIFF is an integer. Indentation is done according to the
  5919. following rules:
  5920. - Planning information and property drawers are always indented
  5921. according to the new level of the headline;
  5922. - Footnote definitions and their contents are ignored;
  5923. - Inlinetasks' boundaries are not shifted;
  5924. - Empty lines are ignored;
  5925. - Other lines' indentation are shifted by DIFF columns, unless
  5926. it would introduce a structural change in the document, in
  5927. which case no shifting is done at all.
  5928. Assume point is at a heading or an inlinetask beginning."
  5929. (org-with-wide-buffer
  5930. (narrow-to-region (line-beginning-position)
  5931. (save-excursion
  5932. (if (org-with-limited-levels (org-at-heading-p))
  5933. (org-with-limited-levels (outline-next-heading))
  5934. (org-inlinetask-goto-end))
  5935. (point)))
  5936. (forward-line)
  5937. ;; Indent properly planning info and property drawer.
  5938. (when (looking-at-p org-planning-line-re)
  5939. (org-indent-line)
  5940. (forward-line))
  5941. (when (looking-at org-property-drawer-re)
  5942. (goto-char (match-end 0))
  5943. (forward-line)
  5944. (org-indent-region (match-beginning 0) (match-end 0)))
  5945. (when (looking-at org-logbook-drawer-re)
  5946. (let ((end-marker (move-marker (make-marker) (match-end 0)))
  5947. (col (+ (current-indentation) diff)))
  5948. (when (wholenump col)
  5949. (while (< (point) end-marker)
  5950. (if (natnump diff)
  5951. (insert (make-string diff 32))
  5952. (delete-char (abs diff)))
  5953. (forward-line)))))
  5954. (catch 'no-shift
  5955. (when (or (zerop diff) (not (eq org-adapt-indentation t)))
  5956. (throw 'no-shift nil))
  5957. ;; If DIFF is negative, first check if a shift is possible at all
  5958. ;; (e.g., it doesn't break structure). This can only happen if
  5959. ;; some contents are not properly indented.
  5960. (let ((case-fold-search t))
  5961. (when (< diff 0)
  5962. (let ((diff (- diff))
  5963. (forbidden-re (concat org-outline-regexp
  5964. "\\|"
  5965. (substring org-footnote-definition-re 1))))
  5966. (save-excursion
  5967. (while (not (eobp))
  5968. (cond
  5969. ((looking-at-p "[ \t]*$") (forward-line))
  5970. ((and (looking-at-p org-footnote-definition-re)
  5971. (let ((e (org-element-at-point)))
  5972. (and (eq (org-element-type e) 'footnote-definition)
  5973. (goto-char (org-element-property :end e))))))
  5974. ((looking-at-p org-outline-regexp) (forward-line))
  5975. ;; Give up if shifting would move before column 0 or
  5976. ;; if it would introduce a headline or a footnote
  5977. ;; definition.
  5978. (t
  5979. (skip-chars-forward " \t")
  5980. (let ((ind (current-column)))
  5981. (when (or (< ind diff)
  5982. (and (= ind diff) (looking-at-p forbidden-re)))
  5983. (throw 'no-shift nil)))
  5984. ;; Ignore contents of example blocks and source
  5985. ;; blocks if their indentation is meant to be
  5986. ;; preserved. Jump to block's closing line.
  5987. (beginning-of-line)
  5988. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  5989. (let ((e (org-element-at-point)))
  5990. (and (memq (org-element-type e)
  5991. '(example-block src-block))
  5992. (or org-src-preserve-indentation
  5993. (org-element-property :preserve-indent e))
  5994. (goto-char (org-element-property :end e))
  5995. (progn (skip-chars-backward " \r\t\n")
  5996. (beginning-of-line)
  5997. t))))
  5998. (forward-line))))))))
  5999. ;; Shift lines but footnote definitions, inlinetasks boundaries
  6000. ;; by DIFF. Also skip contents of source or example blocks
  6001. ;; when indentation is meant to be preserved.
  6002. (while (not (eobp))
  6003. (cond
  6004. ((and (looking-at-p org-footnote-definition-re)
  6005. (let ((e (org-element-at-point)))
  6006. (and (eq (org-element-type e) 'footnote-definition)
  6007. (goto-char (org-element-property :end e))))))
  6008. ((looking-at-p org-outline-regexp) (forward-line))
  6009. ((looking-at-p "[ \t]*$") (forward-line))
  6010. (t
  6011. (indent-line-to (+ (current-indentation) diff))
  6012. (beginning-of-line)
  6013. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6014. (let ((e (org-element-at-point)))
  6015. (and (memq (org-element-type e)
  6016. '(example-block src-block))
  6017. (or org-src-preserve-indentation
  6018. (org-element-property :preserve-indent e))
  6019. (goto-char (org-element-property :end e))
  6020. (progn (skip-chars-backward " \r\t\n")
  6021. (beginning-of-line)
  6022. t))))
  6023. (forward-line)))))))))
  6024. (defun org-convert-to-odd-levels ()
  6025. "Convert an Org file with all levels allowed to one with odd levels.
  6026. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  6027. level 5 etc."
  6028. (interactive)
  6029. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  6030. (let ((outline-level 'org-outline-level)
  6031. (org-odd-levels-only nil) n)
  6032. (save-excursion
  6033. (goto-char (point-min))
  6034. (while (re-search-forward "^\\*\\*+ " nil t)
  6035. (setq n (- (length (match-string 0)) 2))
  6036. (while (>= (setq n (1- n)) 0)
  6037. (org-demote))
  6038. (end-of-line 1))))))
  6039. (defun org-convert-to-oddeven-levels ()
  6040. "Convert an Org file with only odd levels to one with odd/even levels.
  6041. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  6042. file contains a section with an even level, conversion would
  6043. destroy the structure of the file. An error is signaled in this
  6044. case."
  6045. (interactive)
  6046. (goto-char (point-min))
  6047. ;; First check if there are no even levels
  6048. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  6049. (org-fold-show-set-visibility 'canonical)
  6050. (error "Not all levels are odd in this file. Conversion not possible"))
  6051. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  6052. (let ((outline-regexp org-outline-regexp)
  6053. (outline-level 'org-outline-level)
  6054. (org-odd-levels-only nil) n)
  6055. (save-excursion
  6056. (goto-char (point-min))
  6057. (while (re-search-forward "^\\*\\*+ " nil t)
  6058. (setq n (/ (1- (length (match-string 0))) 2))
  6059. (while (>= (setq n (1- n)) 0)
  6060. (org-promote))
  6061. (end-of-line 1))))))
  6062. (defun org-tr-level (n)
  6063. "Make N odd if required."
  6064. (if org-odd-levels-only (1+ (/ n 2)) n))
  6065. ;;; Vertical tree motion, cutting and pasting of subtrees
  6066. (defun org-move-subtree-up (&optional arg)
  6067. "Move the current subtree up past ARG headlines of the same level."
  6068. (interactive "p")
  6069. (org-move-subtree-down (- (prefix-numeric-value arg))))
  6070. (defun org-clean-visibility-after-subtree-move ()
  6071. "Fix visibility issues after moving a subtree."
  6072. ;; First, find a reasonable region to look at:
  6073. ;; Start two siblings above, end three below
  6074. (let* ((beg (save-excursion
  6075. (and (org-get-previous-sibling)
  6076. (org-get-previous-sibling))
  6077. (point)))
  6078. (end (save-excursion
  6079. (and (org-get-next-sibling)
  6080. (org-get-next-sibling)
  6081. (org-get-next-sibling))
  6082. (if (org-at-heading-p)
  6083. (point-at-eol)
  6084. (point))))
  6085. (level (looking-at "\\*+"))
  6086. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  6087. (save-excursion
  6088. (save-restriction
  6089. (narrow-to-region beg end)
  6090. (when re
  6091. ;; Properly fold already folded siblings
  6092. (goto-char (point-min))
  6093. (while (re-search-forward re nil t)
  6094. (when (and (not (org-invisible-p))
  6095. (org-invisible-p (line-end-position)))
  6096. (org-fold-heading nil))))
  6097. (org-cycle-hide-drawers 'all)
  6098. (org-cycle-show-empty-lines 'overview)))))
  6099. (defun org-move-subtree-down (&optional arg)
  6100. "Move the current subtree down past ARG headlines of the same level."
  6101. (interactive "p")
  6102. (setq arg (prefix-numeric-value arg))
  6103. (org-preserve-local-variables
  6104. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  6105. 'org-get-previous-sibling))
  6106. (ins-point (make-marker))
  6107. (cnt (abs arg))
  6108. (col (current-column))
  6109. beg end txt folded)
  6110. ;; Select the tree
  6111. (org-back-to-heading)
  6112. (setq beg (point))
  6113. (save-match-data
  6114. (save-excursion (outline-end-of-heading)
  6115. (setq folded (org-invisible-p)))
  6116. (progn (org-end-of-subtree nil t)
  6117. (unless (eobp) (backward-char))))
  6118. (outline-next-heading)
  6119. (setq end (point))
  6120. (goto-char beg)
  6121. ;; Find insertion point, with error handling
  6122. (while (> cnt 0)
  6123. (unless (and (funcall movfunc) (looking-at org-outline-regexp))
  6124. (goto-char beg)
  6125. (user-error "Cannot move past superior level or buffer limit"))
  6126. (setq cnt (1- cnt)))
  6127. (when (> arg 0)
  6128. ;; Moving forward - still need to move over subtree
  6129. (org-end-of-subtree t t)
  6130. (save-excursion
  6131. (org-back-over-empty-lines)
  6132. (or (bolp) (newline))))
  6133. (move-marker ins-point (point))
  6134. (setq txt (buffer-substring beg end))
  6135. (org-save-markers-in-region beg end)
  6136. (delete-region beg end)
  6137. (when (eq org-fold-core-style 'overlays) (org-remove-empty-overlays-at beg))
  6138. (unless (= beg (point-min)) (org-fold-region (1- beg) beg nil 'outline))
  6139. (unless (bobp) (org-fold-region (1- (point)) (point) nil 'outline))
  6140. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  6141. (let ((bbb (point)))
  6142. (insert-before-markers txt)
  6143. (org-reinstall-markers-in-region bbb)
  6144. (move-marker ins-point bbb))
  6145. (or (bolp) (insert "\n"))
  6146. (goto-char ins-point)
  6147. (org-skip-whitespace)
  6148. (move-marker ins-point nil)
  6149. (if folded
  6150. (org-fold-subtree t)
  6151. (org-fold-show-entry)
  6152. (org-fold-show-children))
  6153. (org-clean-visibility-after-subtree-move)
  6154. ;; move back to the initial column we were at
  6155. (move-to-column col))))
  6156. (defvar org-subtree-clip ""
  6157. "Clipboard for cut and paste of subtrees.
  6158. This is actually only a copy of the kill, because we use the normal kill
  6159. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  6160. (defvar org-subtree-clip-folded nil
  6161. "Was the last copied subtree folded?
  6162. This is used to fold the tree back after pasting.")
  6163. (defun org-cut-subtree (&optional n)
  6164. "Cut the current subtree into the clipboard.
  6165. With prefix arg N, cut this many sequential subtrees.
  6166. This is a short-hand for marking the subtree and then cutting it."
  6167. (interactive "p")
  6168. (org-copy-subtree n 'cut))
  6169. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  6170. "Copy the current subtree into the clipboard.
  6171. With prefix arg N, copy this many sequential subtrees.
  6172. This is a short-hand for marking the subtree and then copying it.
  6173. If CUT is non-nil, actually cut the subtree.
  6174. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  6175. of some markers in the region, even if CUT is non-nil. This is
  6176. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  6177. (interactive "p")
  6178. (org-preserve-local-variables
  6179. (let (beg end folded (beg0 (point)))
  6180. (if (called-interactively-p 'any)
  6181. (org-back-to-heading nil) ; take what looks like a subtree
  6182. (org-back-to-heading t)) ; take what is really there
  6183. (setq beg (point))
  6184. (skip-chars-forward " \t\r\n")
  6185. (save-match-data
  6186. (if nosubtrees
  6187. (outline-next-heading)
  6188. (save-excursion (outline-end-of-heading)
  6189. (setq folded (org-invisible-p)))
  6190. (ignore-errors (org-forward-heading-same-level (1- n) t))
  6191. (org-end-of-subtree t t)))
  6192. ;; Include the end of an inlinetask
  6193. (when (and (featurep 'org-inlinetask)
  6194. (looking-at-p (concat (org-inlinetask-outline-regexp)
  6195. "END[ \t]*$")))
  6196. (end-of-line))
  6197. (setq end (point))
  6198. (goto-char beg0)
  6199. (when (> end beg)
  6200. (setq org-subtree-clip-folded folded)
  6201. (when (or cut force-store-markers)
  6202. (org-save-markers-in-region beg end))
  6203. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  6204. (setq org-subtree-clip (current-kill 0))
  6205. (message "%s: Subtree(s) with %d characters"
  6206. (if cut "Cut" "Copied")
  6207. (length org-subtree-clip))))))
  6208. (defun org-paste-subtree (&optional level tree for-yank remove)
  6209. "Paste the clipboard as a subtree, with modification of headline level.
  6210. The entire subtree is promoted or demoted in order to match a new headline
  6211. level.
  6212. If the cursor is at the beginning of a headline, the same level as
  6213. that headline is used to paste the tree.
  6214. If not, the new level is derived from the *visible* headings
  6215. before and after the insertion point, and taken to be the inferior headline
  6216. level of the two. So if the previous visible heading is level 3 and the
  6217. next is level 4 (or vice versa), level 4 will be used for insertion.
  6218. This makes sure that the subtree remains an independent subtree and does
  6219. not swallow low level entries.
  6220. You can also force a different level, either by using a numeric prefix
  6221. argument, or by inserting the heading marker by hand. For example, if the
  6222. cursor is after \"*****\", then the tree will be shifted to level 5.
  6223. If optional TREE is given, use this text instead of the kill ring.
  6224. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  6225. move back over whitespace before inserting, and move point to the end of
  6226. the inserted text when done.
  6227. When REMOVE is non-nil, remove the subtree from the clipboard."
  6228. (interactive "P")
  6229. (setq tree (or tree (and kill-ring (current-kill 0))))
  6230. (unless (org-kill-is-subtree-p tree)
  6231. (user-error
  6232. (substitute-command-keys
  6233. "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
  6234. (org-with-limited-levels
  6235. (org-fold-core-ignore-fragility-checks
  6236. (let* ((visp (not (org-invisible-p)))
  6237. (txt tree)
  6238. (old-level (if (string-match org-outline-regexp-bol txt)
  6239. (- (match-end 0) (match-beginning 0) 1)
  6240. -1))
  6241. (force-level
  6242. (cond
  6243. (level (prefix-numeric-value level))
  6244. ;; When point is after the stars in an otherwise empty
  6245. ;; headline, use the number of stars as the forced level.
  6246. ((and (org-match-line "^\\*+[ \t]*$")
  6247. (not (eq ?* (char-after))))
  6248. (org-outline-level))
  6249. ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
  6250. (previous-level
  6251. (save-excursion
  6252. (org-previous-visible-heading 1)
  6253. (if (org-at-heading-p) (org-outline-level) 1)))
  6254. (next-level
  6255. (save-excursion
  6256. (if (org-at-heading-p) (org-outline-level)
  6257. (org-next-visible-heading 1)
  6258. (if (org-at-heading-p) (org-outline-level) 1))))
  6259. (new-level (or force-level (max previous-level next-level)))
  6260. (shift (if (or (= old-level -1)
  6261. (= new-level -1)
  6262. (= old-level new-level))
  6263. 0
  6264. (- new-level old-level)))
  6265. (delta (if (> shift 0) -1 1))
  6266. (func (if (> shift 0) #'org-demote #'org-promote))
  6267. (org-odd-levels-only nil)
  6268. beg end newend)
  6269. ;; Remove the forced level indicator.
  6270. (when (and force-level (not level))
  6271. (delete-region (line-beginning-position) (point)))
  6272. ;; Paste before the next visible heading or at end of buffer,
  6273. ;; unless point is at the beginning of a headline.
  6274. (unless (and (bolp) (org-at-heading-p))
  6275. (org-next-visible-heading 1)
  6276. (unless (bolp) (insert "\n")))
  6277. (setq beg (point))
  6278. ;; Avoid re-parsing cache elements when i.e. level 1 heading
  6279. ;; is inserted and then promoted.
  6280. (combine-change-calls beg beg
  6281. (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  6282. (insert-before-markers txt)
  6283. (unless (string-suffix-p "\n" txt) (insert "\n"))
  6284. (setq newend (point))
  6285. (org-reinstall-markers-in-region beg)
  6286. (setq end (point))
  6287. (goto-char beg)
  6288. (skip-chars-forward " \t\n\r")
  6289. (setq beg (point))
  6290. (when (and (org-invisible-p) visp)
  6291. (save-excursion (org-fold-heading nil)))
  6292. ;; Shift if necessary.
  6293. (unless (= shift 0)
  6294. (save-restriction
  6295. (narrow-to-region beg end)
  6296. (while (not (= shift 0))
  6297. (org-map-region func (point-min) (point-max))
  6298. (setq shift (+ delta shift)))
  6299. (goto-char (point-min))
  6300. (setq newend (point-max)))))
  6301. (when (or for-yank (called-interactively-p 'interactive))
  6302. (message "Clipboard pasted as level %d subtree" new-level))
  6303. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  6304. kill-ring
  6305. (equal org-subtree-clip (current-kill 0))
  6306. org-subtree-clip-folded)
  6307. ;; The tree was folded before it was killed/copied
  6308. (org-fold-subtree t))
  6309. (when for-yank (goto-char newend))
  6310. (when remove (pop kill-ring))))))
  6311. (defun org-kill-is-subtree-p (&optional txt)
  6312. "Check if the current kill is an outline subtree, or a set of trees.
  6313. Returns nil if kill does not start with a headline, or if the first
  6314. headline level is not the largest headline level in the tree.
  6315. So this will actually accept several entries of equal levels as well,
  6316. which is OK for `org-paste-subtree'.
  6317. If optional TXT is given, check this string instead of the current kill."
  6318. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  6319. (re (org-get-limited-outline-regexp))
  6320. (^re (concat "^" re))
  6321. (start-level (and kill
  6322. (string-match
  6323. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  6324. kill)
  6325. (- (match-end 2) (match-beginning 2) 1)))
  6326. (start (1+ (or (match-beginning 2) -1))))
  6327. (if (not start-level)
  6328. (progn
  6329. nil) ;; does not even start with a heading
  6330. (catch 'exit
  6331. (while (setq start (string-match ^re kill (1+ start)))
  6332. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  6333. (throw 'exit nil)))
  6334. t))))
  6335. (defvar org-markers-to-move nil
  6336. "Markers that should be moved with a cut-and-paste operation.
  6337. Those markers are stored together with their positions relative to
  6338. the start of the region.")
  6339. (defun org-save-markers-in-region (beg end)
  6340. "Check markers in region.
  6341. If these markers are between BEG and END, record their position relative
  6342. to BEG, so that after moving the block of text, we can put the markers back
  6343. into place.
  6344. This function gets called just before an entry or tree gets cut from the
  6345. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  6346. called immediately, to move the markers with the entries."
  6347. (setq org-markers-to-move nil)
  6348. (when (featurep 'org-clock)
  6349. (org-clock-save-markers-for-cut-and-paste beg end))
  6350. (when (featurep 'org-agenda)
  6351. (org-agenda-save-markers-for-cut-and-paste beg end)))
  6352. (defun org-check-and-save-marker (marker beg end)
  6353. "Check if MARKER is between BEG and END.
  6354. If yes, remember the marker and the distance to BEG."
  6355. (when (and (marker-buffer marker)
  6356. (or (equal (marker-buffer marker) (current-buffer))
  6357. (equal (marker-buffer marker) (buffer-base-buffer (current-buffer))))
  6358. (>= marker beg) (< marker end))
  6359. (push (cons marker (- marker beg)) org-markers-to-move)))
  6360. (defun org-reinstall-markers-in-region (beg)
  6361. "Move all remembered markers to their position relative to BEG."
  6362. (dolist (x org-markers-to-move)
  6363. (move-marker (car x) (+ beg (cdr x))))
  6364. (setq org-markers-to-move nil))
  6365. (defun org-narrow-to-subtree (&optional element)
  6366. "Narrow buffer to the current subtree."
  6367. (interactive)
  6368. (if (org-element--cache-active-p)
  6369. (let* ((heading (org-element-lineage
  6370. (or element (org-element-at-point))
  6371. '(headline) t))
  6372. (end (org-element-property :end heading)))
  6373. (if (and heading end)
  6374. (narrow-to-region (org-element-property :begin heading)
  6375. (if (= end (point-max))
  6376. end (1- end)))
  6377. (signal 'outline-before-first-heading nil)))
  6378. (save-excursion
  6379. (save-match-data
  6380. (org-with-limited-levels
  6381. (narrow-to-region
  6382. (progn (org-back-to-heading t) (point))
  6383. (progn (org-end-of-subtree t t)
  6384. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  6385. (point))))))))
  6386. (defun org-toggle-narrow-to-subtree ()
  6387. "Narrow to the subtree at point or widen a narrowed buffer."
  6388. (interactive)
  6389. (if (buffer-narrowed-p)
  6390. (progn (widen) (message "Buffer widen"))
  6391. (org-narrow-to-subtree)
  6392. (message "Buffer narrowed to current subtree")))
  6393. (defun org-narrow-to-block ()
  6394. "Narrow buffer to the current block."
  6395. (interactive)
  6396. (let* ((case-fold-search t)
  6397. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  6398. "^[ \t]*#\\+end_.*")))
  6399. (if blockp
  6400. (narrow-to-region (car blockp) (cdr blockp))
  6401. (user-error "Not in a block"))))
  6402. (defun org-clone-subtree-with-time-shift (n &optional shift)
  6403. "Clone the task (subtree) at point N times.
  6404. The clones will be inserted as siblings.
  6405. In interactive use, the user will be prompted for the number of
  6406. clones to be produced. If the entry has a timestamp, the user
  6407. will also be prompted for a time shift, which may be a repeater
  6408. as used in time stamps, for example `+3d'. To disable this,
  6409. you can call the function with a universal prefix argument.
  6410. When a valid repeater is given and the entry contains any time
  6411. stamps, the clones will become a sequence in time, with time
  6412. stamps in the subtree shifted for each clone produced. If SHIFT
  6413. is nil or the empty string, time stamps will be left alone. The
  6414. ID property of the original subtree is removed.
  6415. In each clone, all the CLOCK entries will be removed. This
  6416. prevents Org from considering that the clocked times overlap.
  6417. If the original subtree did contain time stamps with a repeater,
  6418. the following will happen:
  6419. - the repeater will be removed in each clone
  6420. - an additional clone will be produced, with the current, unshifted
  6421. date(s) in the entry.
  6422. - the original entry will be placed *after* all the clones, with
  6423. repeater intact.
  6424. - the start days in the repeater in the original entry will be shifted
  6425. to past the last clone.
  6426. In this way you can spell out a number of instances of a repeating task,
  6427. and still retain the repeater to cover future instances of the task.
  6428. As described above, N+1 clones are produced when the original
  6429. subtree has a repeater. Setting N to 0, then, can be used to
  6430. remove the repeater from a subtree and create a shifted clone
  6431. with the original repeater."
  6432. (interactive "nNumber of clones to produce: ")
  6433. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  6434. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  6435. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  6436. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  6437. (shift
  6438. (or shift
  6439. (if (and (not (equal current-prefix-arg '(4)))
  6440. (save-excursion
  6441. (goto-char beg)
  6442. (re-search-forward org-ts-regexp-both end-of-tree t)))
  6443. (read-from-minibuffer
  6444. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  6445. ""))) ;No time shift
  6446. (doshift
  6447. (and (org-string-nw-p shift)
  6448. (or (string-match "\\`[ \t]*\\([+-]?[0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
  6449. shift)
  6450. (user-error "Invalid shift specification %s" shift)))))
  6451. (goto-char end-of-tree)
  6452. (unless (bolp) (insert "\n"))
  6453. (let* ((end (point))
  6454. (template (buffer-substring beg end))
  6455. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  6456. (shift-what (pcase (and doshift (match-string 2 shift))
  6457. (`nil nil)
  6458. ("h" 'hour)
  6459. ("d" 'day)
  6460. ("w" (setq shift-n (* 7 shift-n)) 'day)
  6461. ("m" 'month)
  6462. ("y" 'year)
  6463. (_ (error "Unsupported time unit"))))
  6464. (nmin 1)
  6465. (nmax n)
  6466. (n-no-remove -1)
  6467. (org-id-overriding-file-name (buffer-file-name (buffer-base-buffer)))
  6468. (idprop (org-entry-get beg "ID")))
  6469. (when (and doshift
  6470. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  6471. template))
  6472. (delete-region beg end)
  6473. (setq end beg)
  6474. (setq nmin 0)
  6475. (setq nmax (1+ nmax))
  6476. (setq n-no-remove nmax))
  6477. (goto-char end)
  6478. (cl-loop for n from nmin to nmax do
  6479. (insert
  6480. ;; Prepare clone.
  6481. (with-temp-buffer
  6482. (insert template)
  6483. (org-mode)
  6484. (goto-char (point-min))
  6485. (org-fold-show-subtree)
  6486. (and idprop (if org-clone-delete-id
  6487. (org-entry-delete nil "ID")
  6488. (org-id-get-create t)))
  6489. (unless (= n 0)
  6490. (while (re-search-forward org-clock-line-re nil t)
  6491. (delete-region (line-beginning-position)
  6492. (line-beginning-position 2)))
  6493. (goto-char (point-min))
  6494. (while (re-search-forward org-drawer-regexp nil t)
  6495. (org-remove-empty-drawer-at (point))))
  6496. (goto-char (point-min))
  6497. (when doshift
  6498. (while (re-search-forward org-ts-regexp-both nil t)
  6499. (org-timestamp-change (* n shift-n) shift-what))
  6500. (unless (= n n-no-remove)
  6501. (goto-char (point-min))
  6502. (while (re-search-forward org-ts-regexp nil t)
  6503. (save-excursion
  6504. (goto-char (match-beginning 0))
  6505. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  6506. (delete-region (match-beginning 1) (match-end 1)))))))
  6507. (buffer-string)))))
  6508. (goto-char beg)))
  6509. ;;; Outline path
  6510. (defvar org-outline-path-cache nil
  6511. "Alist between buffer positions and outline paths.
  6512. It value is an alist (POSITION . PATH) where POSITION is the
  6513. buffer position at the beginning of an entry and PATH is a list
  6514. of strings describing the outline path for that entry, in reverse
  6515. order.")
  6516. (defun org--get-outline-path-1 (&optional use-cache)
  6517. "Return outline path to current headline.
  6518. Outline path is a list of strings, in reverse order. When
  6519. optional argument USE-CACHE is non-nil, make use of a cache. See
  6520. `org-get-outline-path' for details.
  6521. Assume buffer is widened and point is on a headline."
  6522. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  6523. (let ((p (point))
  6524. (heading (let ((case-fold-search nil))
  6525. (looking-at org-complex-heading-regexp)
  6526. (if (not (match-end 4)) ""
  6527. ;; Remove statistics cookies.
  6528. (org-trim
  6529. (org-link-display-format
  6530. (replace-regexp-in-string
  6531. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  6532. (match-string-no-properties 4))))))))
  6533. (if (org-up-heading-safe)
  6534. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  6535. (when use-cache
  6536. (push (cons p path) org-outline-path-cache))
  6537. path)
  6538. ;; This is a new root node. Since we assume we are moving
  6539. ;; forward, we can drop previous cache so as to limit number
  6540. ;; of associations there.
  6541. (let ((path (list heading)))
  6542. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  6543. path)))))
  6544. (defun org-get-outline-path (&optional with-self use-cache)
  6545. "Return the outline path to the current entry.
  6546. An outline path is a list of ancestors for current headline, as
  6547. a list of strings. Statistics cookies are removed and links are
  6548. replaced with their description, if any, or their path otherwise.
  6549. When optional argument WITH-SELF is non-nil, the path also
  6550. includes the current headline.
  6551. When optional argument USE-CACHE is non-nil, cache outline paths
  6552. between calls to this function so as to avoid backtracking. This
  6553. argument is useful when planning to find more than one outline
  6554. path in the same document. In that case, there are two
  6555. conditions to satisfy:
  6556. - `org-outline-path-cache' is set to nil before starting the
  6557. process;
  6558. - outline paths are computed by increasing buffer positions."
  6559. (org-with-wide-buffer
  6560. (and (or (and with-self (org-back-to-heading t))
  6561. (org-up-heading-safe))
  6562. (reverse (org--get-outline-path-1 use-cache)))))
  6563. (defun org-format-outline-path (path &optional width prefix separator)
  6564. "Format the outline path PATH for display.
  6565. WIDTH is the maximum number of characters that is available.
  6566. PREFIX is a prefix to be included in the returned string,
  6567. such as the file name.
  6568. SEPARATOR is inserted between the different parts of the path,
  6569. the default is \"/\"."
  6570. (setq width (or width 79))
  6571. (setq path (delq nil path))
  6572. (unless (> width 0)
  6573. (user-error "Argument `width' must be positive"))
  6574. (setq separator (or separator "/"))
  6575. (let* ((org-odd-levels-only nil)
  6576. (fpath (concat
  6577. prefix (and prefix path separator)
  6578. (mapconcat
  6579. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  6580. (cl-loop for head in path
  6581. for n from 0
  6582. collect (org-add-props
  6583. head nil 'face
  6584. (nth (% n org-n-level-faces) org-level-faces)))
  6585. separator))))
  6586. (when (> (length fpath) width)
  6587. (if (< width 7)
  6588. ;; It's unlikely that `width' will be this small, but don't
  6589. ;; waste characters by adding ".." if it is.
  6590. (setq fpath (substring fpath 0 width))
  6591. (setf (substring fpath (- width 2)) "..")))
  6592. fpath))
  6593. (defun org-display-outline-path (&optional file current separator just-return-string)
  6594. "Display the current outline path in the echo area.
  6595. If FILE is non-nil, prepend the output with the file name.
  6596. If CURRENT is non-nil, append the current heading to the output.
  6597. SEPARATOR is passed through to `org-format-outline-path'. It separates
  6598. the different parts of the path and defaults to \"/\".
  6599. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  6600. (interactive "P")
  6601. (let* (case-fold-search
  6602. (bfn (buffer-file-name (buffer-base-buffer)))
  6603. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  6604. res)
  6605. (when current (setq path (append path
  6606. (save-excursion
  6607. (org-back-to-heading t)
  6608. (when (looking-at org-complex-heading-regexp)
  6609. (list (match-string 4)))))))
  6610. (setq res
  6611. (org-format-outline-path
  6612. path
  6613. (1- (frame-width))
  6614. (and file bfn (concat (file-name-nondirectory bfn) separator))
  6615. separator))
  6616. (add-face-text-property 0 (length res)
  6617. `(:height ,(face-attribute 'default :height))
  6618. nil res)
  6619. (if just-return-string
  6620. res
  6621. (org-unlogged-message "%s" res))))
  6622. ;;; Outline Sorting
  6623. (defun org-sort (&optional with-case)
  6624. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  6625. Optional argument WITH-CASE means sort case-sensitively."
  6626. (interactive "P")
  6627. (org-call-with-arg
  6628. (cond ((org-at-table-p) #'org-table-sort-lines)
  6629. ((org-at-item-p) #'org-sort-list)
  6630. (t #'org-sort-entries))
  6631. with-case))
  6632. (defun org-sort-remove-invisible (s)
  6633. "Remove emphasis markers and any invisible property from string S.
  6634. Assume S may contain only objects."
  6635. ;; org-element-interpret-data clears any text property, including
  6636. ;; invisible part.
  6637. (org-element-interpret-data
  6638. (let ((tree (org-element-parse-secondary-string
  6639. s (org-element-restriction 'paragraph))))
  6640. (org-element-map tree '(bold code italic link strike-through underline verbatim)
  6641. (lambda (o)
  6642. (pcase (org-element-type o)
  6643. ;; Terminal object. Replace it with its value.
  6644. ((or `code `verbatim)
  6645. (let ((new (org-element-property :value o)))
  6646. (org-element-insert-before new o)
  6647. (org-element-put-property
  6648. new :post-blank (org-element-property :post-blank o))))
  6649. ;; Non-terminal objects. Splice contents.
  6650. (type
  6651. (let ((contents
  6652. (or (org-element-contents o)
  6653. (and (eq type 'link)
  6654. (list (org-element-property :raw-link o)))))
  6655. (c nil))
  6656. (while contents
  6657. (setq c (pop contents))
  6658. (org-element-insert-before c o))
  6659. (org-element-put-property
  6660. c :post-blank (org-element-property :post-blank o)))))
  6661. (org-element-extract-element o)))
  6662. ;; Return modified tree.
  6663. tree)))
  6664. (defvar org-after-sorting-entries-or-items-hook nil
  6665. "Hook that is run after a bunch of entries or items have been sorted.
  6666. When children are sorted, the cursor is in the parent line when this
  6667. hook gets called. When a region or a plain list is sorted, the cursor
  6668. will be in the first entry of the sorted region/list.")
  6669. (defun org-sort-entries
  6670. (&optional with-case sorting-type getkey-func compare-func property
  6671. interactive?)
  6672. "Sort entries on a certain level of an outline tree.
  6673. If there is an active region, the entries in the region are sorted.
  6674. Else, if the cursor is before the first entry, sort the top-level items.
  6675. Else, the children of the entry at point are sorted.
  6676. Sorting can be alphabetically, numerically, by date/time as given by
  6677. a time stamp, by a property, by priority order, or by a custom function.
  6678. The command prompts for the sorting type unless it has been given to the
  6679. function through the SORTING-TYPE argument, which needs to be a character,
  6680. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  6681. the precise meaning of each character:
  6682. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  6683. c By creation time, which is assumed to be the first inactive time stamp
  6684. at the beginning of a line.
  6685. d By deadline date/time.
  6686. k By clocking time.
  6687. n Numerically, by converting the beginning of the entry/item to a number.
  6688. o By order of TODO keywords.
  6689. p By priority according to the cookie.
  6690. r By the value of a property.
  6691. s By scheduled date/time.
  6692. t By date/time, either the first active time stamp in the entry, or, if
  6693. none exist, by the first inactive one.
  6694. Capital letters will reverse the sort order.
  6695. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  6696. called with point at the beginning of the record. It must return a
  6697. value that is compatible with COMPARE-FUNC, the function used to
  6698. compare entries.
  6699. Comparing entries ignores case by default. However, with an optional argument
  6700. WITH-CASE, the sorting considers case as well.
  6701. Sorting is done against the visible part of the headlines, it ignores hidden
  6702. links.
  6703. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  6704. A non-nil value for INTERACTIVE? is used to signal that this
  6705. function is being called interactively."
  6706. (interactive (list current-prefix-arg nil nil nil nil t))
  6707. (let ((case-func (if with-case 'identity 'downcase))
  6708. start beg end stars re re2
  6709. txt what tmp)
  6710. ;; Find beginning and end of region to sort
  6711. (cond
  6712. ((org-region-active-p)
  6713. ;; we will sort the region
  6714. (setq end (region-end)
  6715. what "region")
  6716. (goto-char (region-beginning))
  6717. (unless (org-at-heading-p) (outline-next-heading))
  6718. (setq start (point)))
  6719. ((or (org-at-heading-p)
  6720. (ignore-errors (progn (org-back-to-heading) t)))
  6721. ;; we will sort the children of the current headline
  6722. (org-back-to-heading)
  6723. (setq start (point)
  6724. end (progn (org-end-of-subtree t t)
  6725. (or (bolp) (insert "\n"))
  6726. (when (>= (org-back-over-empty-lines) 1)
  6727. (forward-line 1))
  6728. (point))
  6729. what "children")
  6730. (goto-char start)
  6731. (org-fold-show-subtree)
  6732. (outline-next-heading))
  6733. (t
  6734. ;; we will sort the top-level entries in this file
  6735. (goto-char (point-min))
  6736. (or (org-at-heading-p) (outline-next-heading))
  6737. (setq start (point))
  6738. (goto-char (point-max))
  6739. (beginning-of-line 1)
  6740. (when (looking-at ".*?\\S-")
  6741. ;; File ends in a non-white line
  6742. (end-of-line 1)
  6743. (insert "\n"))
  6744. (setq end (point-max))
  6745. (setq what "top-level")
  6746. (goto-char start)
  6747. (org-fold-show-all '(headings drawers blocks))))
  6748. (setq beg (point))
  6749. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  6750. (looking-at "\\(\\*+\\)")
  6751. (setq stars (match-string 1)
  6752. re (concat "^" (regexp-quote stars) " +")
  6753. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  6754. txt (buffer-substring beg end))
  6755. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  6756. (when (and (not (equal stars "*")) (string-match re2 txt))
  6757. (user-error "Region to sort contains a level above the first entry"))
  6758. (unless sorting-type
  6759. (message
  6760. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  6761. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  6762. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  6763. what)
  6764. (setq sorting-type (read-char-exclusive)))
  6765. (unless getkey-func
  6766. (and (= (downcase sorting-type) ?f)
  6767. (setq getkey-func
  6768. (or (and interactive?
  6769. (org-read-function
  6770. "Function for extracting keys: "))
  6771. (error "Missing key extractor")))))
  6772. (and (= (downcase sorting-type) ?r)
  6773. (not property)
  6774. (setq property
  6775. (completing-read "Property: "
  6776. (mapcar #'list (org-buffer-property-keys t))
  6777. nil t)))
  6778. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  6779. (message "Sorting entries...")
  6780. (save-restriction
  6781. (narrow-to-region start end)
  6782. (let ((restore-clock?
  6783. ;; The clock marker is lost when using `sort-subr'; mark
  6784. ;; the clock with temporary `:org-clock-marker-backup'
  6785. ;; text property.
  6786. (when (and (eq (org-clocking-buffer) (current-buffer))
  6787. (<= start (marker-position org-clock-marker))
  6788. (>= end (marker-position org-clock-marker)))
  6789. (with-silent-modifications
  6790. (put-text-property (1- org-clock-marker) org-clock-marker
  6791. :org-clock-marker-backup t))
  6792. t))
  6793. (dcst (downcase sorting-type))
  6794. (case-fold-search nil)
  6795. (now (current-time)))
  6796. (org-preserve-local-variables
  6797. (sort-subr
  6798. (/= dcst sorting-type)
  6799. ;; This function moves to the beginning character of the
  6800. ;; "record" to be sorted.
  6801. (lambda nil
  6802. (if (re-search-forward re nil t)
  6803. (goto-char (match-beginning 0))
  6804. (goto-char (point-max))))
  6805. ;; This function moves to the last character of the "record" being
  6806. ;; sorted.
  6807. (lambda nil
  6808. (save-match-data
  6809. (condition-case nil
  6810. (outline-forward-same-level 1)
  6811. (error
  6812. (goto-char (point-max))))))
  6813. ;; This function returns the value that gets sorted against.
  6814. (lambda ()
  6815. (cond
  6816. ((= dcst ?n)
  6817. (string-to-number
  6818. (org-sort-remove-invisible (org-get-heading t t t t))))
  6819. ((= dcst ?a)
  6820. (funcall case-func
  6821. (org-sort-remove-invisible (org-get-heading t t t t))))
  6822. ((= dcst ?k)
  6823. (or (get-text-property (point) :org-clock-minutes) 0))
  6824. ((= dcst ?t)
  6825. (let ((end (save-excursion (outline-next-heading) (point))))
  6826. (if (or (re-search-forward org-ts-regexp end t)
  6827. (re-search-forward org-ts-regexp-both end t))
  6828. (org-time-string-to-seconds (match-string 0))
  6829. (float-time now))))
  6830. ((= dcst ?c)
  6831. (let ((end (save-excursion (outline-next-heading) (point))))
  6832. (if (re-search-forward
  6833. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  6834. end t)
  6835. (org-time-string-to-seconds (match-string 0))
  6836. (float-time now))))
  6837. ((= dcst ?s)
  6838. (let ((end (save-excursion (outline-next-heading) (point))))
  6839. (if (re-search-forward org-scheduled-time-regexp end t)
  6840. (org-time-string-to-seconds (match-string 1))
  6841. (float-time now))))
  6842. ((= dcst ?d)
  6843. (let ((end (save-excursion (outline-next-heading) (point))))
  6844. (if (re-search-forward org-deadline-time-regexp end t)
  6845. (org-time-string-to-seconds (match-string 1))
  6846. (float-time now))))
  6847. ((= dcst ?p)
  6848. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  6849. (string-to-char (match-string 2))
  6850. org-priority-default))
  6851. ((= dcst ?r)
  6852. (or (org-entry-get nil property) ""))
  6853. ((= dcst ?o)
  6854. (when (looking-at org-complex-heading-regexp)
  6855. (let* ((m (match-string 2))
  6856. (s (if (member m org-done-keywords) '- '+)))
  6857. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  6858. ((= dcst ?f)
  6859. (if getkey-func
  6860. (progn
  6861. (setq tmp (funcall getkey-func))
  6862. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  6863. tmp)
  6864. (error "Invalid key function `%s'" getkey-func)))
  6865. (t (error "Invalid sorting type `%c'" sorting-type))))
  6866. nil
  6867. (cond
  6868. ((= dcst ?a) 'string-collate-lessp)
  6869. ((= dcst ?f)
  6870. (or compare-func
  6871. (and interactive?
  6872. (org-read-function
  6873. (concat "Function for comparing keys "
  6874. "(empty for default `sort-subr' predicate): ")
  6875. 'allow-empty))))
  6876. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
  6877. (org-cycle-hide-drawers 'all)
  6878. (when restore-clock?
  6879. (move-marker org-clock-marker
  6880. (1+ (next-single-property-change
  6881. start :org-clock-marker-backup)))
  6882. (remove-text-properties (1- org-clock-marker) org-clock-marker
  6883. '(:org-clock-marker-backup t)))))
  6884. (run-hooks 'org-after-sorting-entries-or-items-hook)
  6885. (message "Sorting entries...done")))
  6886. (defun org-contextualize-keys (alist contexts)
  6887. "Return valid elements in ALIST depending on CONTEXTS.
  6888. `org-agenda-custom-commands' or `org-capture-templates' are the
  6889. values used for ALIST, and `org-agenda-custom-commands-contexts'
  6890. or `org-capture-templates-contexts' are the associated contexts
  6891. definitions."
  6892. (let ((contexts
  6893. ;; normalize contexts
  6894. (mapcar
  6895. (lambda(c) (cond ((listp (cadr c))
  6896. (list (car c) (car c) (nth 1 c)))
  6897. ((string= "" (cadr c))
  6898. (list (car c) (car c) (nth 2 c)))
  6899. (t c)))
  6900. contexts))
  6901. (a alist) r s)
  6902. ;; loop over all commands or templates
  6903. (dolist (c a)
  6904. (let (vrules repl)
  6905. (cond
  6906. ((not (assoc (car c) contexts))
  6907. (push c r))
  6908. ((and (assoc (car c) contexts)
  6909. (setq vrules (org-contextualize-validate-key
  6910. (car c) contexts)))
  6911. (mapc (lambda (vr)
  6912. (unless (equal (car vr) (cadr vr))
  6913. (setq repl vr)))
  6914. vrules)
  6915. (if (not repl) (push c r)
  6916. (push (cadr repl) s)
  6917. (push
  6918. (cons (car c)
  6919. (cdr (or (assoc (cadr repl) alist)
  6920. (error "Undefined key `%s' as contextual replacement for `%s'"
  6921. (cadr repl) (car c)))))
  6922. r))))))
  6923. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  6924. (delq
  6925. nil
  6926. (delete-dups
  6927. (mapcar (lambda (x)
  6928. (let ((tpl (car x)))
  6929. (unless (delq
  6930. nil
  6931. (mapcar (lambda (y)
  6932. (equal y tpl))
  6933. s))
  6934. x)))
  6935. (reverse r))))))
  6936. (defun org-contextualize-validate-key (key contexts)
  6937. "Check CONTEXTS for agenda or capture KEY."
  6938. (let (res)
  6939. (dolist (r contexts)
  6940. (dolist (rr (car (last r)))
  6941. (when
  6942. (and (equal key (car r))
  6943. (if (functionp rr) (funcall rr)
  6944. (or (and (eq (car rr) 'in-file)
  6945. (buffer-file-name)
  6946. (string-match (cdr rr) (buffer-file-name)))
  6947. (and (eq (car rr) 'in-mode)
  6948. (string-match (cdr rr) (symbol-name major-mode)))
  6949. (and (eq (car rr) 'in-buffer)
  6950. (string-match (cdr rr) (buffer-name)))
  6951. (when (and (eq (car rr) 'not-in-file)
  6952. (buffer-file-name))
  6953. (not (string-match (cdr rr) (buffer-file-name))))
  6954. (when (eq (car rr) 'not-in-mode)
  6955. (not (string-match (cdr rr) (symbol-name major-mode))))
  6956. (when (eq (car rr) 'not-in-buffer)
  6957. (not (string-match (cdr rr) (buffer-name)))))))
  6958. (push r res))))
  6959. (delete-dups (delq nil res))))
  6960. ;; Defined to provide a value for defcustom, since there is no
  6961. ;; string-collate-greaterp in Emacs.
  6962. (defun org-string-collate-greaterp (s1 s2)
  6963. "Return non-nil if S1 is greater than S2 in collation order."
  6964. (not (string-collate-lessp s1 s2)))
  6965. ;;;###autoload
  6966. (defun org-run-like-in-org-mode (cmd)
  6967. "Run a command, pretending that the current buffer is in Org mode.
  6968. This will temporarily bind local variables that are typically bound in
  6969. Org mode to the values they have in Org mode, and then interactively
  6970. call CMD."
  6971. (org-load-modules-maybe)
  6972. (let (vars vals)
  6973. (dolist (var (org-get-local-variables))
  6974. (when (or (not (boundp (car var)))
  6975. (eq (symbol-value (car var))
  6976. (default-value (car var))))
  6977. (push (car var) vars)
  6978. (push (cadr var) vals)))
  6979. (cl-progv vars vals
  6980. (call-interactively cmd))))
  6981. (defun org-get-category (&optional pos force-refresh)
  6982. "Get the category applying to position POS."
  6983. (save-match-data
  6984. (when force-refresh (org-refresh-category-properties))
  6985. (let ((pos (or pos (point))))
  6986. (if (org-element--cache-active-p)
  6987. ;; Sync cache.
  6988. (org-with-point-at (org-element-property :begin (org-element-at-point pos))
  6989. (or (org-entry-get-with-inheritance "CATEGORY")
  6990. "???"))
  6991. (or (get-text-property pos 'org-category)
  6992. (progn
  6993. (org-refresh-category-properties)
  6994. (get-text-property pos 'org-category)))))))
  6995. ;;; Refresh properties
  6996. (defun org-refresh-properties (dprop tprop)
  6997. "Refresh buffer text properties.
  6998. DPROP is the drawer property and TPROP is either the
  6999. corresponding text property to set, or an alist with each element
  7000. being a text property (as a symbol) and a function to apply to
  7001. the value of the drawer property."
  7002. (let* ((case-fold-search t)
  7003. (inhibit-read-only t)
  7004. (inherit? (org-property-inherit-p dprop))
  7005. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  7006. (global-or-keyword (and inherit?
  7007. (org--property-global-or-keyword-value dprop nil))))
  7008. (with-silent-modifications
  7009. (org-with-point-at 1
  7010. ;; Set global and keyword based values to the whole buffer.
  7011. (when global-or-keyword
  7012. (put-text-property (point-min) (point-max) tprop global-or-keyword))
  7013. ;; Set values based on property-drawers throughout the document.
  7014. (while (re-search-forward property-re nil t)
  7015. (when (org-at-property-p)
  7016. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  7017. (outline-next-heading))))))
  7018. (defun org-refresh-property (tprop p &optional inherit)
  7019. "Refresh the buffer text property TPROP from the drawer property P.
  7020. The refresh happens only for the current entry, or the whole
  7021. sub-tree if optional argument INHERIT is non-nil.
  7022. If point is before first headline, the function applies to the
  7023. part before the first headline. In that particular case, when
  7024. optional argument INHERIT is non-nil, it refreshes properties for
  7025. the whole buffer."
  7026. (save-excursion
  7027. (org-back-to-heading-or-point-min t)
  7028. (let ((start (point))
  7029. (end (save-excursion
  7030. (cond ((and inherit (org-before-first-heading-p))
  7031. (point-max))
  7032. (inherit
  7033. (org-end-of-subtree t t))
  7034. ((outline-next-heading))
  7035. ((point-max))))))
  7036. (with-silent-modifications
  7037. (if (symbolp tprop)
  7038. ;; TPROP is a text property symbol.
  7039. (put-text-property start end tprop p)
  7040. ;; TPROP is an alist with (property . function) elements.
  7041. (pcase-dolist (`(,prop . ,f) tprop)
  7042. (put-text-property start end prop (funcall f p))))))))
  7043. (defun org-refresh-category-properties ()
  7044. "Refresh category text properties in the buffer."
  7045. (unless (org-element--cache-active-p)
  7046. (let ((case-fold-search t)
  7047. (inhibit-read-only t)
  7048. (default-category
  7049. (cond ((null org-category)
  7050. (if buffer-file-name
  7051. (file-name-sans-extension
  7052. (file-name-nondirectory buffer-file-name))
  7053. "???"))
  7054. ((symbolp org-category) (symbol-name org-category))
  7055. (t org-category))))
  7056. (let ((category (catch 'buffer-category
  7057. (org-with-wide-buffer
  7058. (goto-char (point-max))
  7059. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  7060. (let ((element (org-element-at-point-no-context)))
  7061. (when (eq (org-element-type element) 'keyword)
  7062. (throw 'buffer-category
  7063. (org-element-property :value element))))))
  7064. default-category)))
  7065. (with-silent-modifications
  7066. (org-with-wide-buffer
  7067. ;; Set buffer-wide property from keyword. Search last #+CATEGORY
  7068. ;; keyword. If none is found, fall-back to `org-category' or
  7069. ;; buffer file name, or set it by the document property drawer.
  7070. (put-text-property (point-min) (point-max)
  7071. 'org-category category)
  7072. ;; Set categories from the document property drawer or
  7073. ;; property drawers in the outline. If category is found in
  7074. ;; the property drawer for the whole buffer that value
  7075. ;; overrides the keyword-based value set above.
  7076. (goto-char (point-min))
  7077. (let ((regexp (org-re-property "CATEGORY")))
  7078. (while (re-search-forward regexp nil t)
  7079. (let ((value (match-string-no-properties 3)))
  7080. (when (org-at-property-p)
  7081. (put-text-property
  7082. (save-excursion (org-back-to-heading-or-point-min t))
  7083. (save-excursion (if (org-before-first-heading-p)
  7084. (point-max)
  7085. (org-end-of-subtree t t)))
  7086. 'org-category
  7087. value)))))))))))
  7088. (defun org-refresh-stats-properties ()
  7089. "Refresh stats text properties in the buffer."
  7090. (with-silent-modifications
  7091. (org-with-point-at 1
  7092. (let ((regexp (concat org-outline-regexp-bol
  7093. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  7094. (while (re-search-forward regexp nil t)
  7095. (let* ((numerator (string-to-number (match-string 1)))
  7096. (denominator (and (match-end 2)
  7097. (string-to-number (match-string 2))))
  7098. (stats (cond ((not denominator) numerator) ;percent
  7099. ((= denominator 0) 0)
  7100. (t (/ (* numerator 100) denominator)))))
  7101. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  7102. 'org-stats stats)))))))
  7103. (defun org-refresh-effort-properties ()
  7104. "Refresh effort properties."
  7105. (org-refresh-properties
  7106. org-effort-property
  7107. '((effort . identity)
  7108. (effort-minutes . org-duration-to-minutes))))
  7109. (defun org-find-file-at-mouse (ev)
  7110. "Open file link or URL at mouse."
  7111. (interactive "e")
  7112. (mouse-set-point ev)
  7113. (org-open-at-point 'in-emacs))
  7114. (defun org-open-at-mouse (ev)
  7115. "Open file link or URL at mouse.
  7116. See the docstring of `org-open-file' for details."
  7117. (interactive "e")
  7118. (mouse-set-point ev)
  7119. (when (eq major-mode 'org-agenda-mode)
  7120. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  7121. (org-open-at-point))
  7122. (defvar org-window-config-before-follow-link nil
  7123. "The window configuration before following a link.
  7124. This is saved in case the need arises to restore it.")
  7125. (defun org--file-default-apps ()
  7126. "Return the default applications for this operating system."
  7127. (pcase system-type
  7128. (`darwin org-file-apps-macos)
  7129. (`windows-nt org-file-apps-windowsnt)
  7130. (_ org-file-apps-gnu)))
  7131. (defun org--file-apps-entry-dlink-p (entry)
  7132. "Non-nil if ENTRY should be matched against the link by `org-open-file'.
  7133. It assumes that is the case when the entry uses a regular
  7134. expression which has at least one grouping construct and the
  7135. action is either a Lisp form or a command string containing
  7136. \"%1\", i.e., using at least one subexpression match as
  7137. a parameter."
  7138. (pcase entry
  7139. (`(,selector . ,action)
  7140. (and (stringp selector)
  7141. (> (regexp-opt-depth selector) 0)
  7142. (or (and (stringp action)
  7143. (string-match "%[0-9]" action))
  7144. (consp action))))
  7145. (_ nil)))
  7146. (defun org--file-apps-regexp-alist (list &optional add-auto-mode)
  7147. "Convert extensions to regular expressions in the cars of LIST.
  7148. Also, weed out any non-string entries, because the return value
  7149. is used only for regexp matching.
  7150. When ADD-AUTO-MODE is non-nil, make all matches in `auto-mode-alist'
  7151. point to the symbol `emacs', indicating that the file should be
  7152. opened in Emacs."
  7153. (append
  7154. (delq nil
  7155. (mapcar (lambda (x)
  7156. (unless (not (stringp (car x)))
  7157. (if (string-match "\\W" (car x))
  7158. x
  7159. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  7160. list))
  7161. (when add-auto-mode
  7162. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  7163. ;;;###autoload
  7164. (defun org-open-file (path &optional in-emacs line search)
  7165. "Open the file at PATH.
  7166. First, this expands any special file name abbreviations. Then the
  7167. configuration variable `org-file-apps' is checked if it contains an
  7168. entry for this file type, and if yes, the corresponding command is launched.
  7169. If no application is found, Emacs simply visits the file.
  7170. With optional prefix argument IN-EMACS, Emacs will visit the file.
  7171. With a double \\[universal-argument] \\[universal-argument] \
  7172. prefix arg, Org tries to avoid opening in Emacs
  7173. and to use an external application to visit the file.
  7174. Optional LINE specifies a line to go to, optional SEARCH a string
  7175. to search for. If LINE or SEARCH is given, the file will be
  7176. opened in Emacs, unless an entry from `org-file-apps' that makes
  7177. use of groups in a regexp matches.
  7178. If you want to change the way frames are used when following a
  7179. link, please customize `org-link-frame-setup'.
  7180. If the file does not exist, throw an error."
  7181. (let* ((file (if (equal path "") buffer-file-name
  7182. (substitute-in-file-name (expand-file-name path))))
  7183. (file-apps (append org-file-apps (org--file-default-apps)))
  7184. (apps (cl-remove-if #'org--file-apps-entry-dlink-p file-apps))
  7185. (apps-dlink (cl-remove-if-not #'org--file-apps-entry-dlink-p
  7186. file-apps))
  7187. (remp (and (assq 'remote apps) (file-remote-p file)))
  7188. (dirp (unless remp (file-directory-p file)))
  7189. (file (if (and dirp org-open-directory-means-index-dot-org)
  7190. (concat (file-name-as-directory file) "index.org")
  7191. file))
  7192. (a-m-a-p (assq 'auto-mode apps))
  7193. (dfile (downcase file))
  7194. ;; Reconstruct the original link from the PATH, LINE and
  7195. ;; SEARCH args.
  7196. (link (cond (line (concat file "::" (number-to-string line)))
  7197. (search (concat file "::" search))
  7198. (t file)))
  7199. (dlink (downcase link))
  7200. (ext
  7201. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  7202. (match-string 1 dfile)))
  7203. (save-position-maybe
  7204. (let ((old-buffer (current-buffer))
  7205. (old-pos (point))
  7206. (old-mode major-mode))
  7207. (lambda ()
  7208. (and (derived-mode-p 'org-mode)
  7209. (eq old-mode 'org-mode)
  7210. (or (not (eq old-buffer (current-buffer)))
  7211. (not (eq old-pos (point))))
  7212. (org-mark-ring-push old-pos old-buffer)))))
  7213. cmd link-match-data)
  7214. (cond
  7215. ((member in-emacs '((16) system))
  7216. (setq cmd (cdr (assq 'system apps))))
  7217. (in-emacs (setq cmd 'emacs))
  7218. (t
  7219. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  7220. (and dirp (cdr (assq 'directory apps)))
  7221. ;; First, try matching against apps-dlink if we
  7222. ;; get a match here, store the match data for
  7223. ;; later.
  7224. (let ((match (assoc-default dlink apps-dlink
  7225. 'string-match)))
  7226. (if match
  7227. (progn (setq link-match-data (match-data))
  7228. match)
  7229. (progn (setq in-emacs (or in-emacs line search))
  7230. nil))) ; if we have no match in apps-dlink,
  7231. ; always open the file in emacs if line or search
  7232. ; is given (for backwards compatibility)
  7233. (assoc-default dfile
  7234. (org--file-apps-regexp-alist apps a-m-a-p)
  7235. 'string-match)
  7236. (cdr (assoc ext apps))
  7237. (cdr (assq t apps))))))
  7238. (when (eq cmd 'system)
  7239. (setq cmd (cdr (assq 'system apps))))
  7240. (when (eq cmd 'default)
  7241. (setq cmd (cdr (assoc t apps))))
  7242. (when (eq cmd 'mailcap)
  7243. (require 'mailcap)
  7244. (mailcap-parse-mailcaps)
  7245. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  7246. (command (mailcap-mime-info mime-type)))
  7247. (if (stringp command)
  7248. (setq cmd command)
  7249. (setq cmd 'emacs))))
  7250. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  7251. (not (file-exists-p file))
  7252. (not org-open-non-existing-files))
  7253. (user-error "No such file: %s" file))
  7254. (cond
  7255. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  7256. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  7257. (while (string-match "['\"]%s['\"]" cmd)
  7258. (setq cmd (replace-match "%s" t t cmd)))
  7259. (setq cmd (replace-regexp-in-string
  7260. "%s"
  7261. (shell-quote-argument (convert-standard-filename file))
  7262. cmd
  7263. nil t))
  7264. ;; Replace "%1", "%2" etc. in command with group matches from regex
  7265. (save-match-data
  7266. (let ((match-index 1)
  7267. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  7268. (set-match-data link-match-data)
  7269. (while (<= match-index number-of-groups)
  7270. (let ((regex (concat "%" (number-to-string match-index)))
  7271. (replace-with (match-string match-index dlink)))
  7272. (while (string-match regex cmd)
  7273. (setq cmd (replace-match replace-with t t cmd))))
  7274. (setq match-index (+ match-index 1)))))
  7275. (save-window-excursion
  7276. (message "Running %s...done" cmd)
  7277. ;; Handlers such as "gio open" and kde-open5 start viewer in background
  7278. ;; and exit immediately. Use pipe connection type instead of pty to
  7279. ;; avoid killing children processes with SIGHUP when temporary terminal
  7280. ;; session is finished.
  7281. ;;
  7282. ;; TODO: Once minimum Emacs version is 25.1 or above, consider using
  7283. ;; the `make-process' invocation from 5db61eb0f929 to get more helpful
  7284. ;; error messages.
  7285. (let ((process-connection-type nil))
  7286. (start-process-shell-command cmd nil cmd))
  7287. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  7288. ((or (stringp cmd)
  7289. (eq cmd 'emacs))
  7290. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  7291. (widen)
  7292. (cond (line (org-goto-line line)
  7293. (when (derived-mode-p 'org-mode) (org-fold-reveal)))
  7294. (search (condition-case err
  7295. (org-link-search search)
  7296. ;; Save position before error-ing out so user
  7297. ;; can easily move back to the original buffer.
  7298. (error (funcall save-position-maybe)
  7299. (error (nth 1 err)))))))
  7300. ((functionp cmd)
  7301. (save-match-data
  7302. (set-match-data link-match-data)
  7303. (condition-case nil
  7304. (funcall cmd file link)
  7305. ;; FIXME: Remove this check when most default installations
  7306. ;; of Emacs have at least Org 9.0.
  7307. ((debug wrong-number-of-arguments wrong-type-argument
  7308. invalid-function)
  7309. (user-error "Please see Org News for version 9.0 about \
  7310. `org-file-apps'--Lisp error: %S" cmd)))))
  7311. ((consp cmd)
  7312. ;; FIXME: Remove this check when most default installations of
  7313. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  7314. ;; fall back to `org-link-frame-setup' for an old usage of
  7315. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  7316. (user-error "Please see Org News for version 9.0 about \
  7317. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  7318. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  7319. (funcall save-position-maybe)))
  7320. ;;;###autoload
  7321. (defun org-open-at-point-global ()
  7322. "Follow a link or a time-stamp like Org mode does.
  7323. Also follow links and emails as seen by `thing-at-point'.
  7324. This command can be called in any mode to follow an external
  7325. link or a time-stamp that has Org mode syntax. Its behavior
  7326. is undefined when called on internal links like fuzzy links.
  7327. Raise a user error when there is nothing to follow."
  7328. (interactive)
  7329. (let ((tap-url (thing-at-point 'url))
  7330. (tap-email (thing-at-point 'email)))
  7331. (cond ((org-in-regexp org-link-any-re)
  7332. (org-link-open-from-string (match-string-no-properties 0)))
  7333. ((or (org-in-regexp org-ts-regexp-both nil t)
  7334. (org-in-regexp org-tsr-regexp-both nil t))
  7335. (org-follow-timestamp-link))
  7336. (tap-url (org-link-open-from-string tap-url))
  7337. (tap-email (org-link-open-from-string
  7338. (concat "mailto:" tap-email)))
  7339. (t (user-error "No link found")))))
  7340. (defvar org-open-at-point-functions nil
  7341. "Hook that is run when following a link at point.
  7342. Functions in this hook must return t if they identify and follow
  7343. a link at point. If they don't find anything interesting at point,
  7344. they must return nil.")
  7345. (defun org-open-at-point (&optional arg)
  7346. "Open link, timestamp, footnote or tags at point.
  7347. When point is on a link, follow it. Normally, files will be
  7348. opened by an appropriate application. If the optional prefix
  7349. argument ARG is non-nil, Emacs will visit the file. With
  7350. a double prefix argument, try to open outside of Emacs, in the
  7351. application the system uses for this file type.
  7352. When point is on a timestamp, open the agenda at the day
  7353. specified.
  7354. When point is a footnote definition, move to the first reference
  7355. found. If it is on a reference, move to the associated
  7356. definition.
  7357. When point is on a headline, display a list of every link in the
  7358. entry, so it is possible to pick one, or all, of them. If point
  7359. is on a tag, call `org-tags-view' instead.
  7360. On top of syntactically correct links, this function also tries
  7361. to open links and time-stamps in comments, node properties, and
  7362. keywords if point is on something looking like a timestamp or
  7363. a link."
  7364. (interactive "P")
  7365. (org-load-modules-maybe)
  7366. (setq org-window-config-before-follow-link (current-window-configuration))
  7367. (org-remove-occur-highlights nil nil t)
  7368. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  7369. (let* ((context
  7370. ;; Only consider supported types, even if they are not the
  7371. ;; closest one.
  7372. (org-element-lineage
  7373. (org-element-context)
  7374. '(citation citation-reference clock comment comment-block
  7375. footnote-definition footnote-reference headline
  7376. inline-src-block inlinetask keyword link node-property
  7377. planning src-block timestamp)
  7378. t))
  7379. (type (org-element-type context))
  7380. (value (org-element-property :value context)))
  7381. (cond
  7382. ((not type) (user-error "No link found"))
  7383. ;; No valid link at point. For convenience, look if something
  7384. ;; looks like a link under point in some specific places.
  7385. ((memq type '(comment comment-block node-property keyword))
  7386. (call-interactively #'org-open-at-point-global))
  7387. ;; On a headline or an inlinetask, but not on a timestamp,
  7388. ;; a link, a footnote reference or a citation.
  7389. ((memq type '(headline inlinetask))
  7390. (org-match-line org-complex-heading-regexp)
  7391. (let ((tags-beg (match-beginning 5))
  7392. (tags-end (match-end 5)))
  7393. (if (and tags-beg (>= (point) tags-beg) (< (point) tags-end))
  7394. ;; On tags.
  7395. (org-tags-view
  7396. arg
  7397. (save-excursion
  7398. (let* ((beg-tag (or (search-backward ":" tags-beg 'at-limit) (point)))
  7399. (end-tag (search-forward ":" tags-end nil 2)))
  7400. (buffer-substring (1+ beg-tag) (1- end-tag)))))
  7401. ;; Not on tags.
  7402. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  7403. (`(nil . ,_)
  7404. (require 'org-attach)
  7405. (when (org-attach-dir)
  7406. (message "Opening attachment")
  7407. (if (equal arg '(4))
  7408. (org-attach-reveal-in-emacs)
  7409. (org-attach-reveal))))
  7410. (`(,links . ,links-end)
  7411. (dolist (link (if (stringp links) (list links) links))
  7412. (search-forward link nil links-end)
  7413. (goto-char (match-beginning 0))
  7414. (org-open-at-point arg)))))))
  7415. ;; On a footnote reference or at definition's label.
  7416. ((or (eq type 'footnote-reference)
  7417. (and (eq type 'footnote-definition)
  7418. (save-excursion
  7419. ;; Do not validate action when point is on the
  7420. ;; spaces right after the footnote label, in order
  7421. ;; to be on par with behavior on links.
  7422. (skip-chars-forward " \t")
  7423. (let ((begin
  7424. (org-element-property :contents-begin context)))
  7425. (if begin (< (point) begin)
  7426. (= (org-element-property :post-affiliated context)
  7427. (line-beginning-position)))))))
  7428. (org-footnote-action))
  7429. ;; On a planning line. Check if we are really on a timestamp.
  7430. ((and (eq type 'planning)
  7431. (org-in-regexp org-ts-regexp-both nil t))
  7432. (org-follow-timestamp-link))
  7433. ;; On a clock line, make sure point is on the timestamp
  7434. ;; before opening it.
  7435. ((and (eq type 'clock)
  7436. value
  7437. (>= (point) (org-element-property :begin value))
  7438. (<= (point) (org-element-property :end value)))
  7439. (org-follow-timestamp-link))
  7440. ((eq type 'src-block) (org-babel-open-src-block-result))
  7441. ;; Do nothing on white spaces after an object.
  7442. ((>= (point)
  7443. (save-excursion
  7444. (goto-char (org-element-property :end context))
  7445. (skip-chars-backward " \t")
  7446. (point)))
  7447. (user-error "No link found"))
  7448. ((eq type 'inline-src-block) (org-babel-open-src-block-result))
  7449. ((eq type 'timestamp) (org-follow-timestamp-link))
  7450. ((eq type 'link) (org-link-open context arg))
  7451. ((memq type '(citation citation-reference)) (org-cite-follow context arg))
  7452. (t (user-error "No link found")))))
  7453. (run-hook-with-args 'org-follow-link-hook))
  7454. ;;;###autoload
  7455. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  7456. "Offer links in the current entry and return the selected link.
  7457. If there is only one link, return it.
  7458. If NTH is an integer, return the NTH link found.
  7459. If ZERO is a string, check also this string for a link, and if
  7460. there is one, return it."
  7461. (with-current-buffer buffer
  7462. (org-with-wide-buffer
  7463. (goto-char marker)
  7464. (let ((cnt ?0)
  7465. have-zero end links link c)
  7466. (when (and (stringp zero) (string-match org-link-bracket-re zero))
  7467. (push (match-string 0 zero) links)
  7468. (setq cnt (1- cnt) have-zero t))
  7469. (save-excursion
  7470. (org-back-to-heading t)
  7471. (setq end (save-excursion (outline-next-heading) (point)))
  7472. (while (re-search-forward org-link-any-re end t)
  7473. (push (match-string 0) links))
  7474. (setq links (org-uniquify (reverse links))))
  7475. (cond
  7476. ((null links)
  7477. (message "No links"))
  7478. ((equal (length links) 1)
  7479. (setq link (car links)))
  7480. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  7481. (setq link (nth (if have-zero nth (1- nth)) links)))
  7482. (t ; we have to select a link
  7483. (save-excursion
  7484. (save-window-excursion
  7485. (delete-other-windows)
  7486. (with-output-to-temp-buffer "*Select Link*"
  7487. (dolist (l links)
  7488. (cond
  7489. ((not (string-match org-link-bracket-re l))
  7490. (princ (format "[%c] %s\n" (cl-incf cnt)
  7491. (org-unbracket-string "<" ">" l))))
  7492. ((match-end 2)
  7493. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  7494. (match-string 2 l) (match-string 1 l))))
  7495. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  7496. (match-string 1 l)))))))
  7497. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  7498. (message "Select link to open, RET to open all:")
  7499. (setq c (read-char-exclusive))
  7500. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  7501. (when (equal c ?q) (user-error "Abort"))
  7502. (if (equal c ?\C-m)
  7503. (setq link links)
  7504. (setq nth (- c ?0))
  7505. (when have-zero (setq nth (1+ nth)))
  7506. (unless (and (integerp nth) (>= (length links) nth))
  7507. (user-error "Invalid link selection"))
  7508. (setq link (nth (1- nth) links)))))
  7509. (cons link end)))))
  7510. ;;; File search
  7511. (defun org-do-occur (regexp &optional cleanup)
  7512. "Call the Emacs command `occur'.
  7513. If CLEANUP is non-nil, remove the printout of the regular expression
  7514. in the *Occur* buffer. This is useful if the regex is long and not useful
  7515. to read."
  7516. (occur regexp)
  7517. (when cleanup
  7518. (let ((cwin (selected-window)) win beg end)
  7519. (when (setq win (get-buffer-window "*Occur*"))
  7520. (select-window win))
  7521. (goto-char (point-min))
  7522. (when (re-search-forward "match[a-z]+" nil t)
  7523. (setq beg (match-end 0))
  7524. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  7525. (setq end (1- (match-beginning 0)))))
  7526. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  7527. (goto-char (point-min))
  7528. (select-window cwin))))
  7529. ;;; The Mark Ring
  7530. (defvar org-mark-ring nil
  7531. "Mark ring for positions before jumps in Org mode.")
  7532. (defvar org-mark-ring-last-goto nil
  7533. "Last position in the mark ring used to go back.")
  7534. ;; Fill and close the ring
  7535. (setq org-mark-ring nil)
  7536. (setq org-mark-ring-last-goto nil) ;in case file is reloaded
  7537. (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
  7538. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  7539. org-mark-ring)
  7540. (defun org-mark-ring-push (&optional pos buffer)
  7541. "Put the current position into the mark ring and rotate it.
  7542. Also push position into the Emacs mark ring. If optional
  7543. argument POS and BUFFER are not nil, mark this location instead."
  7544. (interactive)
  7545. (let ((pos (or pos (point)))
  7546. (buffer (or buffer (current-buffer))))
  7547. (with-current-buffer buffer
  7548. (org-with-point-at pos (push-mark nil t)))
  7549. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  7550. (move-marker (car org-mark-ring) pos buffer))
  7551. (message
  7552. (substitute-command-keys
  7553. "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
  7554. (defun org-mark-ring-goto (&optional n)
  7555. "Jump to the previous position in the mark ring.
  7556. With prefix arg N, jump back that many stored positions. When
  7557. called several times in succession, walk through the entire ring.
  7558. Org mode commands jumping to a different position in the current file,
  7559. or to another Org file, automatically push the old position onto the ring."
  7560. (interactive "p")
  7561. (let (p m)
  7562. (if (eq last-command this-command)
  7563. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  7564. (setq p org-mark-ring))
  7565. (setq org-mark-ring-last-goto p)
  7566. (setq m (car p))
  7567. (pop-to-buffer-same-window (marker-buffer m))
  7568. (goto-char m)
  7569. (when (or (org-invisible-p) (org-invisible-p2)) (org-fold-show-context 'mark-goto))))
  7570. ;;; Following specific links
  7571. (defvar org-agenda-buffer-tmp-name)
  7572. (defvar org-agenda-start-on-weekday)
  7573. (defvar org-agenda-buffer-name)
  7574. (defun org-follow-timestamp-link ()
  7575. "Open an agenda view for the time-stamp date/range at point."
  7576. ;; Avoid changing the global value.
  7577. (let ((org-agenda-buffer-name org-agenda-buffer-name))
  7578. (cond
  7579. ((org-at-date-range-p t)
  7580. (let ((org-agenda-start-on-weekday)
  7581. (t1 (match-string 1))
  7582. (t2 (match-string 2)) tt1 tt2)
  7583. (setq tt1 (time-to-days (org-time-string-to-time t1))
  7584. tt2 (time-to-days (org-time-string-to-time t2)))
  7585. (let ((org-agenda-buffer-tmp-name
  7586. (format "*Org Agenda(a:%s)"
  7587. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  7588. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  7589. ((org-at-timestamp-p 'lax)
  7590. (let ((org-agenda-buffer-tmp-name
  7591. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  7592. (org-agenda-list nil (time-to-days (org-time-string-to-time
  7593. (substring (match-string 1) 0 10)))
  7594. 1)))
  7595. (t (error "This should not happen")))))
  7596. ;;; Following file links
  7597. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  7598. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  7599. (declare-function mailcap-mime-info
  7600. "mailcap" (string &optional request no-decode))
  7601. (defvar org-wait nil)
  7602. ;;;; Refiling
  7603. (defun org-get-org-file ()
  7604. "Read a filename, with default directory `org-directory'."
  7605. (let ((default (or org-default-notes-file remember-data-file)))
  7606. (read-file-name (format "File name [%s]: " default)
  7607. (file-name-as-directory org-directory)
  7608. default)))
  7609. (defun org-notes-order-reversed-p ()
  7610. "Check if the current file should receive notes in reversed order."
  7611. (cond
  7612. ((not org-reverse-note-order) nil)
  7613. ((eq t org-reverse-note-order) t)
  7614. ((not (listp org-reverse-note-order)) nil)
  7615. (t (catch 'exit
  7616. (dolist (entry org-reverse-note-order)
  7617. (when (string-match (car entry) buffer-file-name)
  7618. (throw 'exit (cdr entry))))))))
  7619. (defvar org-agenda-new-buffers nil
  7620. "Buffers created to visit agenda files.")
  7621. (declare-function org-string-nw-p "org-macs" (s))
  7622. ;;;; Dynamic blocks
  7623. (defun org-find-dblock (name)
  7624. "Find the first dynamic block with name NAME in the buffer.
  7625. If not found, stay at current position and return nil."
  7626. (let ((case-fold-search t) pos)
  7627. (save-excursion
  7628. (goto-char (point-min))
  7629. (setq pos (and (re-search-forward
  7630. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  7631. (match-beginning 0))))
  7632. (when pos (goto-char pos))
  7633. pos))
  7634. (defun org-create-dblock (plist)
  7635. "Create a dynamic block section, with parameters taken from PLIST.
  7636. PLIST must contain a :name entry which is used as the name of the block."
  7637. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  7638. (end-of-line 1)
  7639. (newline))
  7640. (let ((col (current-column))
  7641. (name (plist-get plist :name)))
  7642. (insert "#+BEGIN: " name)
  7643. (while plist
  7644. (if (eq (car plist) :name)
  7645. (setq plist (cddr plist))
  7646. (insert " " (prin1-to-string (pop plist)))))
  7647. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  7648. (beginning-of-line -2)))
  7649. (defun org-prepare-dblock ()
  7650. "Prepare dynamic block for refresh.
  7651. This empties the block, puts the cursor at the insert position and returns
  7652. the property list including an extra property :name with the block name."
  7653. (unless (looking-at org-dblock-start-re)
  7654. (user-error "Not at a dynamic block"))
  7655. (let* ((begdel (1+ (match-end 0)))
  7656. (name (org-no-properties (match-string 1)))
  7657. (params (append (list :name name)
  7658. (read (concat "(" (match-string 3) ")")))))
  7659. (save-excursion
  7660. (beginning-of-line 1)
  7661. (skip-chars-forward " \t")
  7662. (setq params (plist-put params :indentation-column (current-column))))
  7663. (unless (re-search-forward org-dblock-end-re nil t)
  7664. (error "Dynamic block not terminated"))
  7665. (setq params
  7666. (append params
  7667. (list :content (buffer-substring
  7668. begdel (match-beginning 0)))))
  7669. (delete-region begdel (match-beginning 0))
  7670. (goto-char begdel)
  7671. (open-line 1)
  7672. params))
  7673. (defun org-map-dblocks (&optional command)
  7674. "Apply COMMAND to all dynamic blocks in the current buffer.
  7675. If COMMAND is not given, use `org-update-dblock'."
  7676. (let ((cmd (or command 'org-update-dblock)))
  7677. (save-excursion
  7678. (goto-char (point-min))
  7679. (while (re-search-forward org-dblock-start-re nil t)
  7680. (goto-char (match-beginning 0))
  7681. (save-excursion
  7682. (condition-case nil
  7683. (funcall cmd)
  7684. (error (message "Error during update of dynamic block"))))
  7685. (unless (re-search-forward org-dblock-end-re nil t)
  7686. (error "Dynamic block not terminated"))))))
  7687. (defvar org-dynamic-block-alist nil
  7688. "Alist defining all the Org dynamic blocks.
  7689. The key is the dynamic block type name, as a string. The value
  7690. is the function used to insert the dynamic block.
  7691. Use `org-dynamic-block-define' to populate it.")
  7692. (defun org-dynamic-block-function (type)
  7693. "Return function associated to a given dynamic block type.
  7694. TYPE is the dynamic block type, as a string."
  7695. (cdr (assoc type org-dynamic-block-alist)))
  7696. (defun org-dynamic-block-types ()
  7697. "List all defined dynamic block types."
  7698. (mapcar #'car org-dynamic-block-alist))
  7699. (defun org-dynamic-block-define (type func)
  7700. "Define dynamic block TYPE with FUNC.
  7701. TYPE is a string. FUNC is the function creating the dynamic
  7702. block of such type."
  7703. (pcase (assoc type org-dynamic-block-alist)
  7704. (`nil (push (cons type func) org-dynamic-block-alist))
  7705. (def (setcdr def func))))
  7706. (defun org-dynamic-block-insert-dblock (type &optional interactive-p)
  7707. "Insert a dynamic block of type TYPE.
  7708. When used interactively, select the dynamic block types among
  7709. defined types, per `org-dynamic-block-define'. If INTERACTIVE-P
  7710. is non-nil, call the dynamic block function interactively."
  7711. (interactive (list (completing-read "Dynamic block: "
  7712. (org-dynamic-block-types))
  7713. t))
  7714. (pcase (org-dynamic-block-function type)
  7715. (`nil (error "No such dynamic block: %S" type))
  7716. ((and f (pred functionp))
  7717. (if interactive-p (call-interactively f) (funcall f)))
  7718. (_ (error "Invalid function for dynamic block %S" type))))
  7719. (defun org-dblock-update (&optional arg)
  7720. "User command for updating dynamic blocks.
  7721. Update the dynamic block at point. With prefix ARG, update all dynamic
  7722. blocks in the buffer."
  7723. (interactive "P")
  7724. (if arg
  7725. (org-update-all-dblocks)
  7726. (or (looking-at org-dblock-start-re)
  7727. (org-beginning-of-dblock))
  7728. (org-update-dblock)))
  7729. (defun org-update-dblock ()
  7730. "Update the dynamic block at point.
  7731. This means to empty the block, parse for parameters and then call
  7732. the correct writing function."
  7733. (interactive)
  7734. (save-excursion
  7735. (let* ((win (selected-window))
  7736. (pos (point))
  7737. (line (org-current-line))
  7738. (params (org-prepare-dblock))
  7739. (name (plist-get params :name))
  7740. (indent (plist-get params :indentation-column))
  7741. (cmd (intern (concat "org-dblock-write:" name))))
  7742. (message "Updating dynamic block `%s' at line %d..." name line)
  7743. (funcall cmd params)
  7744. (message "Updating dynamic block `%s' at line %d...done" name line)
  7745. (goto-char pos)
  7746. (when (and indent (> indent 0))
  7747. (setq indent (make-string indent ?\ ))
  7748. (save-excursion
  7749. (select-window win)
  7750. (org-beginning-of-dblock)
  7751. (forward-line 1)
  7752. (while (not (looking-at org-dblock-end-re))
  7753. (insert indent)
  7754. (beginning-of-line 2))
  7755. (when (looking-at org-dblock-end-re)
  7756. (and (looking-at "[ \t]+")
  7757. (replace-match ""))
  7758. (insert indent)))))))
  7759. (defun org-beginning-of-dblock ()
  7760. "Find the beginning of the dynamic block at point.
  7761. Error if there is no such block at point."
  7762. (let ((pos (point))
  7763. beg)
  7764. (end-of-line 1)
  7765. (if (and (re-search-backward org-dblock-start-re nil t)
  7766. (setq beg (match-beginning 0))
  7767. (re-search-forward org-dblock-end-re nil t)
  7768. (> (match-end 0) pos))
  7769. (goto-char beg)
  7770. (goto-char pos)
  7771. (error "Not in a dynamic block"))))
  7772. (defun org-update-all-dblocks ()
  7773. "Update all dynamic blocks in the buffer.
  7774. This function can be used in a hook."
  7775. (interactive)
  7776. (when (derived-mode-p 'org-mode)
  7777. (org-map-dblocks 'org-update-dblock)))
  7778. ;;;; Completion
  7779. (declare-function org-export-backend-options "ox" (cl-x) t)
  7780. (defun org-get-export-keywords ()
  7781. "Return a list of all currently understood export keywords.
  7782. Export keywords include options, block names, attributes and
  7783. keywords relative to each registered export back-end."
  7784. (let (keywords)
  7785. (dolist (backend
  7786. (bound-and-true-p org-export-registered-backends)
  7787. (delq nil keywords))
  7788. ;; Back-end name (for keywords, like #+LATEX:)
  7789. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  7790. (dolist (option-entry (org-export-backend-options backend))
  7791. ;; Back-end options.
  7792. (push (nth 1 option-entry) keywords)))))
  7793. (defconst org-options-keywords
  7794. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  7795. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  7796. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  7797. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  7798. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  7799. (defcustom org-structure-template-alist
  7800. '(("a" . "export ascii")
  7801. ("c" . "center")
  7802. ("C" . "comment")
  7803. ("e" . "example")
  7804. ("E" . "export")
  7805. ("h" . "export html")
  7806. ("l" . "export latex")
  7807. ("q" . "quote")
  7808. ("s" . "src")
  7809. ("v" . "verse"))
  7810. "An alist of keys and block types.
  7811. `org-insert-structure-template' will display a menu with this list of
  7812. templates to choose from. The block type is inserted, with
  7813. \"#+begin_\" and \"#+end_\" added automatically. If the block type
  7814. consists of just uppercase letters, \"#+BEGIN_\" and \"#+END_\" are
  7815. added instead.
  7816. The menu keys are defined by the car of each entry in this alist.
  7817. If two entries have the keys \"a\" and \"aa\" respectively, the
  7818. former will be inserted by typing \"a TAB/RET/SPC\" and the
  7819. latter will be inserted by typing \"aa\". If an entry with the
  7820. key \"aab\" is later added, it can be inserted by typing \"ab\".
  7821. If loaded, Org Tempo also uses `org-structure-template-alist'. A
  7822. block can be inserted by pressing TAB after the string \"<KEY\"."
  7823. :group 'org-edit-structure
  7824. :type '(repeat
  7825. (cons (string :tag "Key")
  7826. (string :tag "Template")))
  7827. :package-version '(Org . "9.2"))
  7828. (defun org--check-org-structure-template-alist (&optional checklist)
  7829. "Check whether `org-structure-template-alist' is set up correctly.
  7830. In particular, check if the Org 9.2 format is used as opposed to
  7831. previous format."
  7832. (let ((elm (cl-remove-if-not (lambda (x) (listp (cdr x)))
  7833. (or (symbol-value checklist)
  7834. org-structure-template-alist))))
  7835. (when elm
  7836. (org-display-warning
  7837. (format "
  7838. Please update the entries of `%s'.
  7839. In Org 9.2 the format was changed from something like
  7840. (\"s\" \"#+BEGIN_SRC ?\\n#+END_SRC\")
  7841. to something like
  7842. (\"s\" . \"src\")
  7843. Please refer to the documentation of `org-structure-template-alist'.
  7844. The following entries must be updated:
  7845. %s"
  7846. (or checklist 'org-structure-template-alist)
  7847. (pp-to-string elm))))))
  7848. (defun org--insert-structure-template-mks ()
  7849. "Present `org-structure-template-alist' with `org-mks'.
  7850. Menus are added if keys require more than one keystroke. Tabs
  7851. are added to single key entries when more than one stroke is
  7852. needed. Keys longer than two characters are reduced to two
  7853. characters."
  7854. (org--check-org-structure-template-alist)
  7855. (let* (case-fold-search
  7856. (templates (append org-structure-template-alist
  7857. '(("\t" . "Press TAB, RET or SPC to write block name"))))
  7858. (keys (mapcar #'car templates))
  7859. (start-letters
  7860. (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
  7861. ;; Sort each element of `org-structure-template-alist' into
  7862. ;; sublists according to the first letter.
  7863. (superlist
  7864. (mapcar (lambda (letter)
  7865. (list letter
  7866. (cl-remove-if-not
  7867. (apply-partially #'string-match-p (concat "^" letter))
  7868. templates :key #'car)))
  7869. start-letters)))
  7870. (org-mks
  7871. (apply #'append
  7872. ;; Make an `org-mks' table. If only one element is
  7873. ;; present in a sublist, make it part of the top-menu,
  7874. ;; otherwise make a submenu according to the starting
  7875. ;; letter and populate it.
  7876. (mapcar (lambda (sublist)
  7877. (if (eq 1 (length (cadr sublist)))
  7878. (mapcar (lambda (elm)
  7879. (list (substring (car elm) 0 1)
  7880. (cdr elm) ""))
  7881. (cadr sublist))
  7882. ;; Create submenu.
  7883. (let* ((topkey (car sublist))
  7884. (elms (cadr sublist))
  7885. (keys (mapcar #'car elms))
  7886. (long (> (length elms) 3)))
  7887. (append
  7888. (list
  7889. ;; Make a description of the submenu.
  7890. (list topkey
  7891. (concat
  7892. (mapconcat #'cdr
  7893. (cl-subseq elms 0 (if long 3 (length elms)))
  7894. ", ")
  7895. (when long ", ..."))))
  7896. ;; List of entries in submenu.
  7897. (cl-mapcar #'list
  7898. (org--insert-structure-template-unique-keys keys)
  7899. (mapcar #'cdr elms)
  7900. (make-list (length elms) ""))))))
  7901. superlist))
  7902. "Select a key\n============"
  7903. "Key: ")))
  7904. (defun org--insert-structure-template-unique-keys (keys)
  7905. "Make a list of unique, two characters long elements from KEYS.
  7906. Elements of length one have a tab appended. Elements of length
  7907. two are kept as is. Longer elements are truncated to length two.
  7908. If an element cannot be made unique, an error is raised."
  7909. (let ((ordered-keys (cl-sort (copy-sequence keys) #'< :key #'length))
  7910. menu-keys)
  7911. (dolist (key ordered-keys)
  7912. (let ((potential-key
  7913. (cl-case (length key)
  7914. (1 (concat key "\t"))
  7915. (2 key)
  7916. (otherwise
  7917. (cl-find-if-not (lambda (k) (assoc k menu-keys))
  7918. (mapcar (apply-partially #'concat (substring key 0 1))
  7919. (split-string (substring key 1) "" t)))))))
  7920. (if (or (not potential-key) (assoc potential-key menu-keys))
  7921. (user-error "Could not make unique key for `%s'" key)
  7922. (push (cons potential-key key) menu-keys))))
  7923. (mapcar #'car
  7924. (cl-sort menu-keys #'<
  7925. :key (lambda (elm) (cl-position (cdr elm) keys))))))
  7926. (defun org-insert-structure-template (type)
  7927. "Insert a block structure of the type #+begin_foo/#+end_foo.
  7928. Select a block from `org-structure-template-alist' then type
  7929. either RET, TAB or SPC to write the block type. With an active
  7930. region, wrap the region in the block. Otherwise, insert an empty
  7931. block.
  7932. When foo is written as FOO, upcase the #+BEGIN/END as well."
  7933. (interactive
  7934. (list (pcase (org--insert-structure-template-mks)
  7935. (`("\t" . ,_) (read-string "Structure type: "))
  7936. (`(,_ ,choice . ,_) choice))))
  7937. (let* ((case-fold-search t) ; Make sure that matches are case-insensitive.
  7938. (region? (use-region-p))
  7939. (region-start (and region? (region-beginning)))
  7940. (region-end (and region? (copy-marker (region-end))))
  7941. (extended? (string-match-p "\\`\\(src\\|export\\)\\'" type))
  7942. (verbatim? (string-match-p
  7943. (concat "\\`" (regexp-opt '("example" "export" "src")))
  7944. type))
  7945. (upcase? (string= (car (split-string type))
  7946. (upcase (car (split-string type))))))
  7947. (when region? (goto-char region-start))
  7948. (let ((column (current-indentation)))
  7949. (if (save-excursion (skip-chars-backward " \t") (bolp))
  7950. (beginning-of-line)
  7951. (insert "\n"))
  7952. (save-excursion
  7953. (indent-to column)
  7954. (insert (format "#+%s_%s%s\n" (if upcase? "BEGIN" "begin") type (if extended? " " "")))
  7955. (when region?
  7956. (when verbatim? (org-escape-code-in-region (point) region-end))
  7957. (goto-char region-end)
  7958. ;; Ignore empty lines at the end of the region.
  7959. (skip-chars-backward " \r\t\n")
  7960. (end-of-line))
  7961. (unless (bolp) (insert "\n"))
  7962. (indent-to column)
  7963. (insert (format "#+%s_%s" (if upcase? "END" "end") (car (split-string type))))
  7964. (if (looking-at "[ \t]*$") (replace-match "")
  7965. (insert "\n"))
  7966. (when (and (eobp) (not (bolp))) (insert "\n")))
  7967. (if extended? (end-of-line)
  7968. (forward-line)
  7969. (skip-chars-forward " \t")))))
  7970. ;;;; TODO, DEADLINE, Comments
  7971. (defun org-toggle-comment ()
  7972. "Change the COMMENT state of an entry."
  7973. (interactive)
  7974. (save-excursion
  7975. (org-back-to-heading)
  7976. (let ((case-fold-search nil))
  7977. (looking-at org-complex-heading-regexp))
  7978. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  7979. (skip-chars-forward " \t")
  7980. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  7981. (if (org-in-commented-heading-p t)
  7982. (delete-region (point)
  7983. (progn (search-forward " " (line-end-position) 'move)
  7984. (skip-chars-forward " \t")
  7985. (point)))
  7986. (insert org-comment-string)
  7987. (unless (eolp) (insert " ")))))
  7988. (defvar org-last-todo-state-is-todo nil
  7989. "This is non-nil when the last TODO state change led to a TODO state.
  7990. If the last change removed the TODO tag or switched to DONE, then
  7991. this is nil.")
  7992. (defvar org-todo-setup-filter-hook nil
  7993. "Hook for functions that pre-filter todo specs.
  7994. Each function takes a todo spec and returns either nil or the spec
  7995. transformed into canonical form." )
  7996. (defvar org-todo-get-default-hook nil
  7997. "Hook for functions that get a default item for todo.
  7998. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  7999. nil or a string to be used for the todo mark." )
  8000. (defvar org-agenda-headline-snapshot-before-repeat)
  8001. (defun org-current-effective-time ()
  8002. "Return current time adjusted for `org-extend-today-until' variable."
  8003. (let* ((ct (org-current-time))
  8004. (dct (decode-time ct))
  8005. (ct1
  8006. (cond
  8007. (org-use-last-clock-out-time-as-effective-time
  8008. (or (org-clock-get-last-clock-out-time) ct))
  8009. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  8010. (org-encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  8011. (t ct))))
  8012. ct1))
  8013. (defun org-todo-yesterday (&optional arg)
  8014. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  8015. (interactive "P")
  8016. (if (eq major-mode 'org-agenda-mode)
  8017. (org-agenda-todo-yesterday arg)
  8018. (let* ((org-use-effective-time t)
  8019. (hour (nth 2 (decode-time (org-current-time))))
  8020. (org-extend-today-until (1+ hour)))
  8021. (org-todo arg))))
  8022. (defvar org-block-entry-blocking ""
  8023. "First entry preventing the TODO state change.")
  8024. (defun org-cancel-repeater ()
  8025. "Cancel a repeater by setting its numeric value to zero."
  8026. (interactive)
  8027. (save-excursion
  8028. (org-back-to-heading t)
  8029. (let ((bound1 (point))
  8030. (bound0 (save-excursion (outline-next-heading) (point))))
  8031. (when (and (re-search-forward
  8032. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  8033. org-deadline-time-regexp "\\)\\|\\("
  8034. org-ts-regexp "\\)")
  8035. bound0 t)
  8036. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  8037. bound1 t))
  8038. (replace-match "0" t nil nil 1)))))
  8039. (defvar org-state)
  8040. (defvar org-blocked-by-checkboxes)
  8041. (defun org-todo (&optional arg)
  8042. "Change the TODO state of an item.
  8043. The state of an item is given by a keyword at the start of the heading,
  8044. like
  8045. *** TODO Write paper
  8046. *** DONE Call mom
  8047. The different keywords are specified in the variable `org-todo-keywords'.
  8048. By default the available states are \"TODO\" and \"DONE\". So, for this
  8049. example: when the item starts with TODO, it is changed to DONE.
  8050. When it starts with DONE, the DONE is removed. And when neither TODO nor
  8051. DONE are present, add TODO at the beginning of the heading.
  8052. You can set up single-character keys to fast-select the new state. See the
  8053. `org-todo-keywords' and `org-use-fast-todo-selection' for details.
  8054. With `\\[universal-argument]' prefix ARG, force logging the state change \
  8055. and take a
  8056. logging note.
  8057. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  8058. next set of TODO \
  8059. keywords (nextset).
  8060. Another way to achieve this is `S-C-<right>'.
  8061. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8062. prefix, circumvent any state blocking.
  8063. With numeric prefix arg, switch to the Nth state.
  8064. With a numeric prefix arg of 0, inhibit note taking for the change.
  8065. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  8066. When called through ELisp, arg is also interpreted in the following way:
  8067. `none' -> empty state
  8068. \"\" -> switch to empty state
  8069. `done' -> switch to DONE
  8070. `nextset' -> switch to the next set of keywords
  8071. `previousset' -> switch to the previous set of keywords
  8072. \"WAITING\" -> switch to the specified keyword, but only if it
  8073. really is a member of `org-todo-keywords'."
  8074. (interactive "P")
  8075. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  8076. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  8077. 'region-start-level 'region))
  8078. org-loop-over-headlines-in-active-region)
  8079. (org-map-entries
  8080. (lambda () (org-todo arg))
  8081. nil cl
  8082. (when (org-invisible-p) (org-end-of-subtree nil t))))
  8083. (when (equal arg '(16)) (setq arg 'nextset))
  8084. (when (equal (prefix-numeric-value arg) -1) (org-cancel-repeater) (setq arg nil))
  8085. (when (< (prefix-numeric-value arg) -1) (user-error "Prefix argument %d not supported" arg))
  8086. (let ((org-blocker-hook org-blocker-hook)
  8087. commentp
  8088. case-fold-search)
  8089. (when (equal arg '(64))
  8090. (setq arg nil org-blocker-hook nil))
  8091. (when (and org-blocker-hook
  8092. (or org-inhibit-blocking
  8093. (org-entry-get nil "NOBLOCKING")))
  8094. (setq org-blocker-hook nil))
  8095. (save-excursion
  8096. (catch 'exit
  8097. (org-back-to-heading t)
  8098. (when (org-in-commented-heading-p t)
  8099. (org-toggle-comment)
  8100. (setq commentp t))
  8101. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  8102. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  8103. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  8104. (let* ((match-data (match-data))
  8105. (startpos (copy-marker (line-beginning-position)))
  8106. (force-log (and (equal arg '(4)) (prog1 t (setq arg nil))))
  8107. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  8108. (org-log-done org-log-done)
  8109. (org-log-repeat org-log-repeat)
  8110. (org-todo-log-states org-todo-log-states)
  8111. (org-inhibit-logging
  8112. (if (equal arg 0)
  8113. (progn (setq arg nil) 'note) org-inhibit-logging))
  8114. (this (match-string 1))
  8115. (hl-pos (match-beginning 0))
  8116. (head (org-get-todo-sequence-head this))
  8117. (ass (assoc head org-todo-kwd-alist))
  8118. (interpret (nth 1 ass))
  8119. (done-word (nth 3 ass))
  8120. (final-done-word (nth 4 ass))
  8121. (org-last-state (or this ""))
  8122. (completion-ignore-case t)
  8123. (member (member this org-todo-keywords-1))
  8124. (tail (cdr member))
  8125. (org-state (cond
  8126. ((eq arg 'right)
  8127. ;; Next state
  8128. (if this
  8129. (if tail (car tail) nil)
  8130. (car org-todo-keywords-1)))
  8131. ((eq arg 'left)
  8132. ;; Previous state
  8133. (unless (equal member org-todo-keywords-1)
  8134. (if this
  8135. (nth (- (length org-todo-keywords-1)
  8136. (length tail) 2)
  8137. org-todo-keywords-1)
  8138. (org-last org-todo-keywords-1))))
  8139. (arg
  8140. ;; User or caller requests a specific state.
  8141. (cond
  8142. ((equal arg "") nil)
  8143. ((eq arg 'none) nil)
  8144. ((eq arg 'done) (or done-word (car org-done-keywords)))
  8145. ((eq arg 'nextset)
  8146. (or (car (cdr (member head org-todo-heads)))
  8147. (car org-todo-heads)))
  8148. ((eq arg 'previousset)
  8149. (let ((org-todo-heads (reverse org-todo-heads)))
  8150. (or (car (cdr (member head org-todo-heads)))
  8151. (car org-todo-heads))))
  8152. ((car (member arg org-todo-keywords-1)))
  8153. ((stringp arg)
  8154. (user-error "State `%s' not valid in this file" arg))
  8155. ((nth (1- (prefix-numeric-value arg))
  8156. org-todo-keywords-1))))
  8157. ((and org-todo-key-trigger org-use-fast-todo-selection)
  8158. ;; Use fast selection.
  8159. (org-fast-todo-selection this))
  8160. ((null member) (or head (car org-todo-keywords-1)))
  8161. ((equal this final-done-word) nil) ;-> make empty
  8162. ((null tail) nil) ;-> first entry
  8163. ((memq interpret '(type priority))
  8164. (if (eq this-command last-command)
  8165. (car tail)
  8166. (if (> (length tail) 0)
  8167. (or done-word (car org-done-keywords))
  8168. nil)))
  8169. (t
  8170. (car tail))))
  8171. (org-state (or
  8172. (run-hook-with-args-until-success
  8173. 'org-todo-get-default-hook org-state org-last-state)
  8174. org-state))
  8175. (next (if (org-string-nw-p org-state) (concat " " org-state " ") " "))
  8176. (change-plist (list :type 'todo-state-change :from this :to org-state
  8177. :position startpos))
  8178. dolog now-done-p)
  8179. (when org-blocker-hook
  8180. (let (org-blocked-by-checkboxes block-reason)
  8181. (setq org-last-todo-state-is-todo
  8182. (not (member this org-done-keywords)))
  8183. (unless (save-excursion
  8184. (save-match-data
  8185. (org-with-wide-buffer
  8186. (run-hook-with-args-until-failure
  8187. 'org-blocker-hook change-plist))))
  8188. (setq block-reason (if org-blocked-by-checkboxes
  8189. "contained checkboxes"
  8190. (format "\"%s\"" org-block-entry-blocking)))
  8191. (if (called-interactively-p 'interactive)
  8192. (user-error "TODO state change from %s to %s blocked (by %s)"
  8193. this org-state block-reason)
  8194. ;; Fail silently.
  8195. (message "TODO state change from %s to %s blocked (by %s)"
  8196. this org-state block-reason)
  8197. (throw 'exit nil)))))
  8198. (store-match-data match-data)
  8199. (org-fold-core-ignore-modifications
  8200. (goto-char (match-beginning 0))
  8201. (replace-match "")
  8202. ;; We need to use `insert-before-markers-and-inherit'
  8203. ;; because: (1) We want to preserve the folding state
  8204. ;; text properties; (2) We do not want to make point
  8205. ;; move before new todo state when inserting a new todo
  8206. ;; into an empty heading. In (2), the above
  8207. ;; `save-excursion' is relying on markers saved before.
  8208. (insert-before-markers-and-inherit next)
  8209. (unless (org-invisible-p (line-beginning-position))
  8210. (org-fold-region (line-beginning-position)
  8211. (line-end-position)
  8212. nil)))
  8213. (cond ((and org-state (equal this org-state))
  8214. (message "TODO state was already %s" (org-trim next)))
  8215. ((not (pos-visible-in-window-p hl-pos))
  8216. (message "TODO state changed to %s" (org-trim next))))
  8217. (unless head
  8218. (setq head (org-get-todo-sequence-head org-state)
  8219. ass (assoc head org-todo-kwd-alist)
  8220. interpret (nth 1 ass)
  8221. done-word (nth 3 ass)
  8222. final-done-word (nth 4 ass)))
  8223. (when (memq arg '(nextset previousset))
  8224. (message "Keyword-Set %d/%d: %s"
  8225. (- (length org-todo-sets) -1
  8226. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  8227. (length org-todo-sets)
  8228. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  8229. (setq org-last-todo-state-is-todo
  8230. (not (member org-state org-done-keywords)))
  8231. (setq now-done-p (and (member org-state org-done-keywords)
  8232. (not (member this org-done-keywords))))
  8233. (and logging (org-local-logging logging))
  8234. (when (or (and (or org-todo-log-states org-log-done)
  8235. (not (eq org-inhibit-logging t))
  8236. (not (memq arg '(nextset previousset))))
  8237. force-log)
  8238. ;; We need to look at recording a time and note.
  8239. (setq dolog (or (if force-log 'note)
  8240. (nth 1 (assoc org-state org-todo-log-states))
  8241. (nth 2 (assoc this org-todo-log-states))))
  8242. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  8243. (setq dolog 'time))
  8244. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  8245. (and org-state
  8246. (member org-state org-not-done-keywords)
  8247. (not (member this org-not-done-keywords))))
  8248. ;; This is now a todo state and was not one before
  8249. ;; If there was a CLOSED time stamp, get rid of it.
  8250. (org-add-planning-info nil nil 'closed))
  8251. (when (and now-done-p org-log-done)
  8252. ;; It is now done, and it was not done before.
  8253. (org-add-planning-info 'closed (org-current-effective-time))
  8254. (when (and (not dolog) (eq 'note org-log-done))
  8255. (org-add-log-setup 'done org-state this 'note)))
  8256. (when (and org-state dolog)
  8257. ;; This is a non-nil state, and we need to log it.
  8258. (org-add-log-setup 'state org-state this dolog)))
  8259. ;; Fixup tag positioning.
  8260. (org-todo-trigger-tag-changes org-state)
  8261. (when org-auto-align-tags (org-align-tags))
  8262. (when org-provide-todo-statistics
  8263. (org-update-parent-todo-statistics))
  8264. (when (bound-and-true-p org-clock-out-when-done)
  8265. (org-clock-out-if-current))
  8266. (run-hooks 'org-after-todo-state-change-hook)
  8267. (when (and arg (not (member org-state org-done-keywords)))
  8268. (setq head (org-get-todo-sequence-head org-state)))
  8269. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  8270. ;; Do we need to trigger a repeat?
  8271. (when now-done-p
  8272. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  8273. ;; This is for the agenda, take a snapshot of the headline.
  8274. (save-match-data
  8275. (setq org-agenda-headline-snapshot-before-repeat
  8276. (org-get-heading))))
  8277. (org-auto-repeat-maybe org-state))
  8278. ;; Fixup cursor location if close to the keyword.
  8279. (when (and (outline-on-heading-p)
  8280. (not (bolp))
  8281. (save-excursion (beginning-of-line 1)
  8282. (looking-at org-todo-line-regexp))
  8283. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  8284. (goto-char (or (match-end 2) (match-end 1)))
  8285. (and (looking-at " ")
  8286. (not (looking-at " *:"))
  8287. (just-one-space)))
  8288. (when org-trigger-hook
  8289. (save-excursion
  8290. (run-hook-with-args 'org-trigger-hook change-plist)))
  8291. (when commentp (org-toggle-comment))))))))
  8292. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  8293. "Block turning an entry into a TODO, using the hierarchy.
  8294. This checks whether the current task should be blocked from state
  8295. changes. Such blocking occurs when:
  8296. 1. The task has children which are not all in a completed state.
  8297. 2. A task has a parent with the property :ORDERED:, and there
  8298. are siblings prior to the current task with incomplete
  8299. status.
  8300. 3. The parent of the task is blocked because it has siblings that should
  8301. be done first, or is child of a block grandparent TODO entry."
  8302. (if (not org-enforce-todo-dependencies)
  8303. t ; if locally turned off don't block
  8304. (catch 'dont-block
  8305. ;; If this is not a todo state change, or if this entry is already DONE,
  8306. ;; do not block
  8307. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  8308. (member (plist-get change-plist :from)
  8309. (cons 'done org-done-keywords))
  8310. (member (plist-get change-plist :to)
  8311. (cons 'todo org-not-done-keywords))
  8312. (not (plist-get change-plist :to)))
  8313. (throw 'dont-block t))
  8314. ;; If this task has children, and any are undone, it's blocked
  8315. (save-excursion
  8316. (org-back-to-heading t)
  8317. (let ((this-level (funcall outline-level)))
  8318. (outline-next-heading)
  8319. (let ((child-level (funcall outline-level)))
  8320. (while (and (not (eobp))
  8321. (> child-level this-level))
  8322. ;; this todo has children, check whether they are all
  8323. ;; completed
  8324. (when (and (not (org-entry-is-done-p))
  8325. (org-entry-is-todo-p))
  8326. (setq org-block-entry-blocking (org-get-heading))
  8327. (throw 'dont-block nil))
  8328. (outline-next-heading)
  8329. (setq child-level (funcall outline-level))))))
  8330. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  8331. ;; any previous siblings are undone, it's blocked
  8332. (save-excursion
  8333. (org-back-to-heading t)
  8334. (let* ((pos (point))
  8335. (parent-pos (and (org-up-heading-safe) (point)))
  8336. (case-fold-search nil))
  8337. (unless parent-pos (throw 'dont-block t)) ; no parent
  8338. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  8339. (forward-line 1)
  8340. (re-search-forward org-not-done-heading-regexp pos t))
  8341. (setq org-block-entry-blocking (match-string 0))
  8342. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  8343. ;; Search further up the hierarchy, to see if an ancestor is blocked
  8344. (while t
  8345. (goto-char parent-pos)
  8346. (unless (looking-at org-not-done-heading-regexp)
  8347. (throw 'dont-block t)) ; do not block, parent is not a TODO
  8348. (setq pos (point))
  8349. (setq parent-pos (and (org-up-heading-safe) (point)))
  8350. (unless parent-pos (throw 'dont-block t)) ; no parent
  8351. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  8352. (forward-line 1)
  8353. (re-search-forward org-not-done-heading-regexp pos t)
  8354. (setq org-block-entry-blocking (org-get-heading)))
  8355. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  8356. (defcustom org-track-ordered-property-with-tag nil
  8357. "Should the ORDERED property also be shown as a tag?
  8358. The ORDERED property decides if an entry should require subtasks to be
  8359. completed in sequence. Since a property is not very visible, setting
  8360. this option means that toggling the ORDERED property with the command
  8361. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  8362. not relevant for the behavior, but it makes things more visible.
  8363. Note that toggling the tag with tags commands will not change the property
  8364. and therefore not influence behavior!
  8365. This can be t, meaning the tag ORDERED should be used. It can also be a
  8366. string to select a different tag for this task."
  8367. :group 'org-todo
  8368. :type '(choice
  8369. (const :tag "No tracking" nil)
  8370. (const :tag "Track with ORDERED tag" t)
  8371. (string :tag "Use other tag")))
  8372. (defun org-toggle-ordered-property ()
  8373. "Toggle the ORDERED property of the current entry.
  8374. For better visibility, you can track the value of this property with a tag.
  8375. See variable `org-track-ordered-property-with-tag'."
  8376. (interactive)
  8377. (let* ((t1 org-track-ordered-property-with-tag)
  8378. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  8379. (save-excursion
  8380. (org-back-to-heading)
  8381. (if (org-entry-get nil "ORDERED")
  8382. (progn
  8383. (org-delete-property "ORDERED")
  8384. (and tag (org-toggle-tag tag 'off))
  8385. (message "Subtasks can be completed in arbitrary order"))
  8386. (org-entry-put nil "ORDERED" "t")
  8387. (and tag (org-toggle-tag tag 'on))
  8388. (message "Subtasks must be completed in sequence")))))
  8389. (defun org-block-todo-from-checkboxes (change-plist)
  8390. "Block turning an entry into a TODO, using checkboxes.
  8391. This checks whether the current task should be blocked from state
  8392. changes because there are unchecked boxes in this entry."
  8393. (if (not org-enforce-todo-checkbox-dependencies)
  8394. t ; if locally turned off don't block
  8395. (catch 'dont-block
  8396. ;; If this is not a todo state change, or if this entry is already DONE,
  8397. ;; do not block
  8398. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  8399. (member (plist-get change-plist :from)
  8400. (cons 'done org-done-keywords))
  8401. (member (plist-get change-plist :to)
  8402. (cons 'todo org-not-done-keywords))
  8403. (not (plist-get change-plist :to)))
  8404. (throw 'dont-block t))
  8405. ;; If this task has checkboxes that are not checked, it's blocked
  8406. (save-excursion
  8407. (org-back-to-heading t)
  8408. (let ((beg (point)) end)
  8409. (outline-next-heading)
  8410. (setq end (point))
  8411. (goto-char beg)
  8412. (when (org-list-search-forward
  8413. (concat (org-item-beginning-re)
  8414. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  8415. "\\[[- ]\\]")
  8416. end t)
  8417. (when (boundp 'org-blocked-by-checkboxes)
  8418. (setq org-blocked-by-checkboxes t))
  8419. (throw 'dont-block nil))))
  8420. t))) ; do not block
  8421. (defun org-entry-blocked-p ()
  8422. "Non-nil if entry at point is blocked."
  8423. (and (not (org-entry-get nil "NOBLOCKING"))
  8424. (member (org-entry-get nil "TODO") org-not-done-keywords)
  8425. (not (run-hook-with-args-until-failure
  8426. 'org-blocker-hook
  8427. (list :type 'todo-state-change
  8428. :position (point)
  8429. :from 'todo
  8430. :to 'done)))))
  8431. (defun org-update-statistics-cookies (all)
  8432. "Update the statistics cookie, either from TODO or from checkboxes.
  8433. This should be called with the cursor in a line with a statistics
  8434. cookie. When called with a \\[universal-argument] prefix, update
  8435. all statistics cookies in the buffer."
  8436. (interactive "P")
  8437. (if all
  8438. (progn
  8439. (org-update-checkbox-count 'all)
  8440. (org-map-region 'org-update-parent-todo-statistics
  8441. (point-min) (point-max)))
  8442. (if (not (org-at-heading-p))
  8443. (org-update-checkbox-count)
  8444. (let ((pos (point-marker))
  8445. end l1 l2)
  8446. (ignore-errors (org-back-to-heading t))
  8447. (if (not (org-at-heading-p))
  8448. (org-update-checkbox-count)
  8449. (setq l1 (org-outline-level))
  8450. (setq end
  8451. (save-excursion
  8452. (outline-next-heading)
  8453. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  8454. (point)))
  8455. (if (and (save-excursion
  8456. (re-search-forward
  8457. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  8458. (not (save-excursion
  8459. (re-search-forward
  8460. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  8461. (org-update-checkbox-count)
  8462. (if (and l2 (> l2 l1))
  8463. (progn
  8464. (goto-char end)
  8465. (org-update-parent-todo-statistics))
  8466. (goto-char pos)
  8467. (beginning-of-line 1)
  8468. (while (re-search-forward
  8469. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  8470. (point-at-eol) t)
  8471. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  8472. (goto-char pos)
  8473. (move-marker pos nil)))))
  8474. (defvar org-entry-property-inherited-from) ;; defined below
  8475. (defun org-update-parent-todo-statistics ()
  8476. "Update any statistics cookie in the parent of the current headline.
  8477. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  8478. the entire subtree and this will travel up the hierarchy and update
  8479. statistics everywhere."
  8480. (let* ((prop (save-excursion
  8481. (org-up-heading-safe)
  8482. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  8483. (recursive (or (not org-hierarchical-todo-statistics)
  8484. (and prop (string-match "\\<recursive\\>" prop))))
  8485. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  8486. 0))
  8487. (first t)
  8488. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  8489. level ltoggle l1 new ndel
  8490. (cnt-all 0) (cnt-done 0) is-percent kwd
  8491. checkbox-beg cookie-present)
  8492. (catch 'exit
  8493. (save-excursion
  8494. (beginning-of-line 1)
  8495. (setq ltoggle (funcall outline-level))
  8496. ;; Three situations are to consider:
  8497. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  8498. ;; to the top-level ancestor on the headline;
  8499. ;; 2. If parent has "recursive" property, repeat up to the
  8500. ;; headline setting that property, taking inheritance into
  8501. ;; account;
  8502. ;; 3. Else, move up to direct parent and proceed only once.
  8503. (while (and (setq level (org-up-heading-safe))
  8504. (or recursive first)
  8505. (>= (point) lim))
  8506. (setq first nil cookie-present nil)
  8507. (unless (and level
  8508. (not (string-match
  8509. "\\<checkbox\\>"
  8510. (downcase (or (org-entry-get nil "COOKIE_DATA")
  8511. "")))))
  8512. (throw 'exit nil))
  8513. (while (re-search-forward box-re (point-at-eol) t)
  8514. (setq cnt-all 0 cnt-done 0 cookie-present t)
  8515. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  8516. (save-match-data
  8517. (unless (outline-next-heading) (throw 'exit nil))
  8518. (while (and (looking-at org-complex-heading-regexp)
  8519. (> (setq l1 (length (match-string 1))) level))
  8520. (setq kwd (and (or recursive (= l1 ltoggle))
  8521. (match-string 2)))
  8522. (if (or (eq org-provide-todo-statistics 'all-headlines)
  8523. (and (eq org-provide-todo-statistics t)
  8524. (or (member kwd org-done-keywords)))
  8525. (and (listp org-provide-todo-statistics)
  8526. (stringp (car org-provide-todo-statistics))
  8527. (or (member kwd org-provide-todo-statistics)
  8528. (member kwd org-done-keywords)))
  8529. (and (listp org-provide-todo-statistics)
  8530. (listp (car org-provide-todo-statistics))
  8531. (or (member kwd (car org-provide-todo-statistics))
  8532. (and (member kwd org-done-keywords)
  8533. (member kwd (cadr org-provide-todo-statistics))))))
  8534. (setq cnt-all (1+ cnt-all))
  8535. (and (eq org-provide-todo-statistics t)
  8536. kwd
  8537. (setq cnt-all (1+ cnt-all))))
  8538. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  8539. (member kwd org-done-keywords))
  8540. (and (listp org-provide-todo-statistics)
  8541. (listp (car org-provide-todo-statistics))
  8542. (member kwd org-done-keywords)
  8543. (member kwd (cadr org-provide-todo-statistics)))
  8544. (and (listp org-provide-todo-statistics)
  8545. (stringp (car org-provide-todo-statistics))
  8546. (member kwd org-done-keywords)))
  8547. (setq cnt-done (1+ cnt-done)))
  8548. (outline-next-heading)))
  8549. (setq new
  8550. (if is-percent
  8551. (format "[%d%%]" (floor (* 100.0 cnt-done)
  8552. (max 1 cnt-all)))
  8553. (format "[%d/%d]" cnt-done cnt-all))
  8554. ndel (- (match-end 0) checkbox-beg))
  8555. (goto-char checkbox-beg)
  8556. (insert new)
  8557. (delete-region (point) (+ (point) ndel))
  8558. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  8559. (when cookie-present
  8560. (run-hook-with-args 'org-after-todo-statistics-hook
  8561. cnt-done (- cnt-all cnt-done))))))
  8562. (run-hooks 'org-todo-statistics-hook)))
  8563. (defvar org-after-todo-statistics-hook nil
  8564. "Hook that is called after a TODO statistics cookie has been updated.
  8565. Each function is called with two arguments: the number of not-done entries
  8566. and the number of done entries.
  8567. For example, the following function, when added to this hook, will switch
  8568. an entry to DONE when all children are done, and back to TODO when new
  8569. entries are set to a TODO status. Note that this hook is only called
  8570. when there is a statistics cookie in the headline!
  8571. (defun org-summary-todo (n-done n-not-done)
  8572. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  8573. (let (org-log-done org-log-states) ; turn off logging
  8574. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))")
  8575. (defvar org-todo-statistics-hook nil
  8576. "Hook that is run whenever Org thinks TODO statistics should be updated.
  8577. This hook runs even if there is no statistics cookie present, in which case
  8578. `org-after-todo-statistics-hook' would not run.")
  8579. (defun org-todo-trigger-tag-changes (state)
  8580. "Apply the changes defined in `org-todo-state-tags-triggers'."
  8581. (let ((l org-todo-state-tags-triggers)
  8582. changes)
  8583. (when (or (not state) (equal state ""))
  8584. (setq changes (append changes (cdr (assoc "" l)))))
  8585. (when (and (stringp state) (> (length state) 0))
  8586. (setq changes (append changes (cdr (assoc state l)))))
  8587. (when (member state org-not-done-keywords)
  8588. (setq changes (append changes (cdr (assq 'todo l)))))
  8589. (when (member state org-done-keywords)
  8590. (setq changes (append changes (cdr (assq 'done l)))))
  8591. (dolist (c changes)
  8592. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  8593. (defun org-local-logging (value)
  8594. "Get logging settings from a property VALUE."
  8595. ;; Directly set the variables, they are already local.
  8596. (setq org-log-done nil
  8597. org-log-repeat nil
  8598. org-todo-log-states nil)
  8599. (dolist (w (split-string value))
  8600. (let (a)
  8601. (cond
  8602. ((setq a (assoc w org-startup-options))
  8603. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  8604. (set (nth 1 a) (nth 2 a))))
  8605. ((setq a (org-extract-log-state-settings w))
  8606. (and (member (car a) org-todo-keywords-1)
  8607. (push a org-todo-log-states)))))))
  8608. (defun org-get-todo-sequence-head (kwd)
  8609. "Return the head of the TODO sequence to which KWD belongs.
  8610. If KWD is not set, check if there is a text property remembering the
  8611. right sequence."
  8612. (let (p)
  8613. (cond
  8614. ((not kwd)
  8615. (or (get-text-property (point-at-bol) 'org-todo-head)
  8616. (progn
  8617. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  8618. nil (point-at-eol)))
  8619. (get-text-property p 'org-todo-head))))
  8620. ((not (member kwd org-todo-keywords-1))
  8621. (car org-todo-keywords-1))
  8622. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  8623. (defun org-fast-todo-selection (&optional current-state)
  8624. "Fast TODO keyword selection with single keys.
  8625. Returns the new TODO keyword, or nil if no state change should occur.
  8626. When CURRENT-STATE is given and selection letters are not unique globally,
  8627. prefer a state in the current sequence over on in another sequence."
  8628. (let* ((fulltable org-todo-key-alist)
  8629. (head (org-get-todo-sequence-head current-state))
  8630. (done-keywords org-done-keywords) ;; needed for the faces.
  8631. (maxlen (apply 'max (mapcar
  8632. (lambda (x)
  8633. (if (stringp (car x)) (string-width (car x)) 0))
  8634. fulltable)))
  8635. (expert (equal org-use-fast-todo-selection 'expert))
  8636. (prompt "")
  8637. (fwidth (+ maxlen 3 1 3))
  8638. (ncol (/ (- (window-width) 4) fwidth))
  8639. tg cnt e c tbl subtable
  8640. groups ingroup in-current-sequence)
  8641. (save-excursion
  8642. (save-window-excursion
  8643. (if expert
  8644. (set-buffer (get-buffer-create " *Org todo*"))
  8645. (delete-other-windows)
  8646. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org todo*"))
  8647. (org-switch-to-buffer-other-window " *Org todo*"))
  8648. (erase-buffer)
  8649. (setq-local org-done-keywords done-keywords)
  8650. (setq tbl fulltable cnt 0)
  8651. (while (setq e (pop tbl))
  8652. (cond
  8653. ((equal e '(:startgroup))
  8654. (push '() groups) (setq ingroup t)
  8655. (unless (= cnt 0)
  8656. (setq cnt 0)
  8657. (insert "\n"))
  8658. (setq prompt (concat prompt "{"))
  8659. (insert "{ "))
  8660. ((equal e '(:endgroup))
  8661. (setq ingroup nil cnt 0 in-current-sequence nil)
  8662. (setq prompt (concat prompt "}"))
  8663. (insert "}\n"))
  8664. ((equal e '(:newline))
  8665. (unless (= cnt 0)
  8666. (setq cnt 0)
  8667. (insert "\n")
  8668. (setq e (car tbl))
  8669. (while (equal (car tbl) '(:newline))
  8670. (insert "\n")
  8671. (setq tbl (cdr tbl)))))
  8672. (t
  8673. (setq tg (car e) c (cdr e))
  8674. (if (equal tg head) (setq in-current-sequence t))
  8675. (when ingroup (push tg (car groups)))
  8676. (when in-current-sequence (push e subtable))
  8677. (setq tg (org-add-props tg nil 'face
  8678. (org-get-todo-face tg)))
  8679. (when (and (= cnt 0) (not ingroup)) (insert " "))
  8680. (setq prompt (concat prompt "[" (char-to-string c) "] " tg " "))
  8681. (insert "[" c "] " tg (make-string
  8682. (- fwidth 4 (length tg)) ?\ ))
  8683. (when (and (= (setq cnt (1+ cnt)) ncol)
  8684. ;; Avoid lines with just a closing delimiter.
  8685. (not (equal (car tbl) '(:endgroup))))
  8686. (insert "\n")
  8687. (when ingroup (insert " "))
  8688. (setq cnt 0)))))
  8689. (insert "\n")
  8690. (goto-char (point-min))
  8691. (unless expert (org-fit-window-to-buffer))
  8692. (message (concat "[a-z..]:Set [SPC]:clear"
  8693. (if expert (concat "\n" prompt) "")))
  8694. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  8695. (setq subtable (nreverse subtable))
  8696. (cond
  8697. ((or (= c ?\C-g)
  8698. (and (= c ?q) (not (rassoc c fulltable))))
  8699. (setq quit-flag t))
  8700. ((= c ?\ ) nil)
  8701. ((setq e (or (rassoc c subtable) (rassoc c fulltable))
  8702. tg (car e))
  8703. tg)
  8704. (t (setq quit-flag t)))))))
  8705. (defun org-entry-is-todo-p ()
  8706. (member (org-get-todo-state) org-not-done-keywords))
  8707. (defun org-entry-is-done-p ()
  8708. (member (org-get-todo-state) org-done-keywords))
  8709. (defun org-get-todo-state ()
  8710. "Return the TODO keyword of the current subtree."
  8711. (save-excursion
  8712. (org-back-to-heading t)
  8713. (and (let ((case-fold-search nil))
  8714. (looking-at org-todo-line-regexp))
  8715. (match-end 2)
  8716. (match-string 2))))
  8717. (defun org-at-date-range-p (&optional inactive-ok)
  8718. "Non-nil if point is inside a date range.
  8719. When optional argument INACTIVE-OK is non-nil, also consider
  8720. inactive time ranges.
  8721. When this function returns a non-nil value, match data is set
  8722. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  8723. on INACTIVE-OK."
  8724. (interactive)
  8725. (save-excursion
  8726. (catch 'exit
  8727. (let ((pos (point)))
  8728. (skip-chars-backward "^[<\r\n")
  8729. (skip-chars-backward "<[")
  8730. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  8731. (>= (match-end 0) pos)
  8732. (throw 'exit t))
  8733. (skip-chars-backward "^<[\r\n")
  8734. (skip-chars-backward "<[")
  8735. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  8736. (>= (match-end 0) pos)
  8737. (throw 'exit t)))
  8738. nil)))
  8739. (defun org-get-repeat (&optional timestamp)
  8740. "Check if there is a time-stamp with repeater in this entry.
  8741. Return the repeater, as a string, or nil. Also return nil when
  8742. this function is called before first heading.
  8743. When optional argument TIMESTAMP is a string, extract the
  8744. repeater from there instead."
  8745. (save-match-data
  8746. (cond
  8747. (timestamp
  8748. (and (string-match org-repeat-re timestamp)
  8749. (match-string-no-properties 1 timestamp)))
  8750. ((org-before-first-heading-p) nil)
  8751. (t
  8752. (save-excursion
  8753. (org-back-to-heading t)
  8754. (let ((end (org-entry-end-position)))
  8755. (catch :repeat
  8756. (while (re-search-forward org-repeat-re end t)
  8757. (when (save-match-data (org-at-timestamp-p 'agenda))
  8758. (throw :repeat (match-string-no-properties 1)))))))))))
  8759. (defvar org-last-changed-timestamp)
  8760. (defvar org-last-inserted-timestamp)
  8761. (defvar org-log-post-message)
  8762. (defvar org-log-note-purpose)
  8763. (defvar org-log-note-how nil)
  8764. (defvar org-log-note-extra)
  8765. (defvar org-log-setup nil)
  8766. (defun org-auto-repeat-maybe (done-word)
  8767. "Check if the current headline contains a repeated time-stamp.
  8768. If yes, set TODO state back to what it was and change the base date
  8769. of repeating deadline/scheduled time stamps to new date.
  8770. This function is run automatically after each state change to a DONE state."
  8771. (let* ((repeat (org-get-repeat))
  8772. (aa (assoc org-last-state org-todo-kwd-alist))
  8773. (interpret (nth 1 aa))
  8774. (head (nth 2 aa))
  8775. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  8776. (msg "Entry repeats: ")
  8777. (org-log-done nil)
  8778. (org-todo-log-states nil)
  8779. (end (copy-marker (org-entry-end-position))))
  8780. (when (and repeat (not (= 0 (string-to-number (substring repeat 1)))))
  8781. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  8782. (let ((to-state
  8783. (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  8784. (and (stringp org-todo-repeat-to-state)
  8785. org-todo-repeat-to-state)
  8786. (and org-todo-repeat-to-state org-last-state))))
  8787. (org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
  8788. to-state)
  8789. ((eq interpret 'type) org-last-state)
  8790. (head)
  8791. (t 'none))))
  8792. (org-back-to-heading t)
  8793. (org-add-planning-info nil nil 'closed)
  8794. ;; When `org-log-repeat' is non-nil or entry contains
  8795. ;; a clock, set LAST_REPEAT property.
  8796. (when (or org-log-repeat
  8797. (catch :clock
  8798. (save-excursion
  8799. (while (re-search-forward org-clock-line-re end t)
  8800. (when (org-at-clock-log-p) (throw :clock t))))))
  8801. (org-entry-put nil "LAST_REPEAT" (format-time-string
  8802. (org-time-stamp-format t t)
  8803. (org-current-effective-time))))
  8804. (when org-log-repeat
  8805. (if org-log-setup
  8806. ;; We are already setup for some record.
  8807. (when (eq org-log-repeat 'note)
  8808. ;; Make sure we take a note, not only a time stamp.
  8809. (setq org-log-note-how 'note))
  8810. ;; Set up for taking a record.
  8811. (org-add-log-setup 'state
  8812. (or done-word (car org-done-keywords))
  8813. org-last-state
  8814. org-log-repeat)))
  8815. ;; Time-stamps without a repeater are usually skipped. However,
  8816. ;; a SCHEDULED time-stamp without one is removed, as they are no
  8817. ;; longer relevant.
  8818. (save-excursion
  8819. (let ((scheduled (org-entry-get (point) "SCHEDULED")))
  8820. (when (and scheduled (not (string-match-p org-repeat-re scheduled)))
  8821. (org-remove-timestamp-with-keyword org-scheduled-string))))
  8822. ;; Update every time-stamp with a repeater in the entry.
  8823. (let ((planning-re (regexp-opt
  8824. (list org-scheduled-string org-deadline-string))))
  8825. (while (re-search-forward org-repeat-re end t)
  8826. (let* ((ts (match-string 0))
  8827. (type (if (not (org-at-planning-p)) "Plain:"
  8828. (save-excursion
  8829. (re-search-backward
  8830. planning-re (line-beginning-position) t)
  8831. (match-string 0)))))
  8832. (when (and (org-at-timestamp-p 'agenda)
  8833. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  8834. (let ((n (string-to-number (match-string 2 ts)))
  8835. (what (match-string 3 ts)))
  8836. (when (equal what "w") (setq n (* n 7) what "d"))
  8837. (when (and (equal what "h")
  8838. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  8839. ts)))
  8840. (user-error
  8841. "Cannot repeat in %d hour(s) because no hour has been set"
  8842. n))
  8843. ;; Preparation, see if we need to modify the start
  8844. ;; date for the change.
  8845. (when (match-end 1)
  8846. (let ((time (save-match-data (org-time-string-to-time ts)))
  8847. (repeater-type (match-string 1 ts)))
  8848. (cond
  8849. ((equal "." repeater-type)
  8850. ;; Shift starting date to today, or now if
  8851. ;; repeater is by hours.
  8852. (if (equal what "h")
  8853. (org-timestamp-change
  8854. (floor (- (org-time-stamp-to-now ts t)) 60) 'minute)
  8855. (org-timestamp-change
  8856. (- (org-today) (time-to-days time)) 'day)))
  8857. ((equal "+" repeater-type)
  8858. (let ((nshiftmax 10)
  8859. (nshift 0))
  8860. (while (or (= nshift 0)
  8861. (not (time-less-p nil time)))
  8862. (when (= nshiftmax (cl-incf nshift))
  8863. (or (y-or-n-p
  8864. (format "%d repeater intervals were not \
  8865. enough to shift date past today. Continue? "
  8866. nshift))
  8867. (user-error "Abort")))
  8868. (org-timestamp-change n (cdr (assoc what whata)))
  8869. (org-in-regexp org-ts-regexp3)
  8870. (setq ts (match-string 1))
  8871. (setq time
  8872. (save-match-data
  8873. (org-time-string-to-time ts)))))
  8874. (org-timestamp-change (- n) (cdr (assoc what whata)))
  8875. ;; Rematch, so that we have everything in place
  8876. ;; for the real shift.
  8877. (org-in-regexp org-ts-regexp3)
  8878. (setq ts (match-string 1))
  8879. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  8880. ts)))))
  8881. (save-excursion
  8882. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  8883. (setq msg
  8884. (concat msg type " " org-last-changed-timestamp " ")))))))
  8885. (run-hooks 'org-todo-repeat-hook)
  8886. (setq org-log-post-message msg)
  8887. (message msg))))
  8888. (defun org-show-todo-tree (arg)
  8889. "Make a compact tree which shows all headlines marked with TODO.
  8890. The tree will show the lines where the regexp matches, and all higher
  8891. headlines above the match.
  8892. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  8893. With a numeric prefix N, construct a sparse tree for the Nth element
  8894. of `org-todo-keywords-1'."
  8895. (interactive "P")
  8896. (let ((case-fold-search nil)
  8897. (kwd-re
  8898. (cond ((null arg) (concat org-not-done-regexp "\\s-"))
  8899. ((equal arg '(4))
  8900. (let ((kwd
  8901. (completing-read "Keyword (or KWD1|KWD2|...): "
  8902. (mapcar #'list org-todo-keywords-1))))
  8903. (concat "\\("
  8904. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  8905. "\\)\\>")))
  8906. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  8907. (regexp-quote (nth (1- (prefix-numeric-value arg))
  8908. org-todo-keywords-1)))
  8909. (t (user-error "Invalid prefix argument: %s" arg)))))
  8910. (message "%d TODO entries found"
  8911. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  8912. (defun org--deadline-or-schedule (arg type time)
  8913. "Insert DEADLINE or SCHEDULE information in current entry.
  8914. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  8915. `org-schedule' for information about ARG and TIME arguments."
  8916. (org-fold-core-ignore-modifications
  8917. (let* ((deadline? (eq type 'deadline))
  8918. (keyword (if deadline? org-deadline-string org-scheduled-string))
  8919. (log (if deadline? org-log-redeadline org-log-reschedule))
  8920. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  8921. (old-date-time (and old-date (org-time-string-to-time old-date)))
  8922. ;; Save repeater cookie from either TIME or current scheduled
  8923. ;; time stamp. We are going to insert it back at the end of
  8924. ;; the process.
  8925. (repeater (or (and (org-string-nw-p time)
  8926. ;; We use `org-ts-regexp-both' because we
  8927. ;; need to tell the difference between a
  8928. ;; real repeater and a time delta, e.g.
  8929. ;; "+2d".
  8930. (string-match-p org-ts-regexp-both time)
  8931. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  8932. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  8933. time)
  8934. (match-string 1 time))
  8935. (and (org-string-nw-p old-date)
  8936. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  8937. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  8938. old-date)
  8939. (match-string 1 old-date)))))
  8940. (pcase arg
  8941. (`(4)
  8942. (if (not old-date)
  8943. (message (if deadline? "Entry had no deadline to remove"
  8944. "Entry was not scheduled"))
  8945. (when (and old-date log)
  8946. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  8947. nil old-date log))
  8948. (org-remove-timestamp-with-keyword keyword)
  8949. (message (if deadline? "Entry no longer has a deadline."
  8950. "Entry is no longer scheduled."))))
  8951. (`(16)
  8952. (save-excursion
  8953. (org-back-to-heading t)
  8954. (let ((regexp (if deadline? org-deadline-time-regexp
  8955. org-scheduled-time-regexp)))
  8956. (if (not (re-search-forward regexp (line-end-position 2) t))
  8957. (user-error (if deadline? "No deadline information to update"
  8958. "No scheduled information to update"))
  8959. (let* ((rpl0 (match-string 1))
  8960. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  8961. (msg (if deadline? "Warn starting from" "Delay until")))
  8962. (replace-match
  8963. (concat keyword
  8964. " <" rpl
  8965. (format " -%dd"
  8966. (abs (- (time-to-days
  8967. (save-match-data
  8968. (org-read-date
  8969. nil t nil msg old-date-time)))
  8970. (time-to-days old-date-time))))
  8971. ">") t t))))))
  8972. (_
  8973. (org-add-planning-info type time 'closed)
  8974. (when (and old-date
  8975. log
  8976. (not (equal old-date org-last-inserted-timestamp)))
  8977. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  8978. org-last-inserted-timestamp
  8979. old-date
  8980. log))
  8981. (when repeater
  8982. (save-excursion
  8983. (org-back-to-heading t)
  8984. (when (re-search-forward
  8985. (concat keyword " " org-last-inserted-timestamp)
  8986. (line-end-position 2)
  8987. t)
  8988. (goto-char (1- (match-end 0)))
  8989. (insert-and-inherit " " repeater)
  8990. (setq org-last-inserted-timestamp
  8991. (concat (substring org-last-inserted-timestamp 0 -1)
  8992. " " repeater
  8993. (substring org-last-inserted-timestamp -1))))))
  8994. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  8995. org-last-inserted-timestamp))))))
  8996. (defun org-deadline (arg &optional time)
  8997. "Insert a \"DEADLINE:\" string with a timestamp to make a deadline.
  8998. When called interactively, this command pops up the Emacs calendar to let
  8999. the user select a date.
  9000. With one universal prefix argument, remove any deadline from the item.
  9001. With two universal prefix arguments, prompt for a warning delay.
  9002. With argument TIME, set the deadline at the corresponding date. TIME
  9003. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9004. (interactive "P")
  9005. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9006. (org-map-entries
  9007. (lambda () (org--deadline-or-schedule arg 'deadline time))
  9008. nil
  9009. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9010. 'region-start-level
  9011. 'region)
  9012. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9013. (org--deadline-or-schedule arg 'deadline time)))
  9014. (defun org-schedule (arg &optional time)
  9015. "Insert a \"SCHEDULED:\" string with a timestamp to schedule an item.
  9016. When called interactively, this command pops up the Emacs calendar to let
  9017. the user select a date.
  9018. With one universal prefix argument, remove any scheduling date from the item.
  9019. With two universal prefix arguments, prompt for a delay cookie.
  9020. With argument TIME, scheduled at the corresponding date. TIME can
  9021. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9022. (interactive "P")
  9023. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9024. (org-map-entries
  9025. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  9026. nil
  9027. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9028. 'region-start-level
  9029. 'region)
  9030. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9031. (org--deadline-or-schedule arg 'scheduled time)))
  9032. (defun org-get-scheduled-time (pom &optional inherit)
  9033. "Get the scheduled time as a time tuple, of a format suitable
  9034. for calling org-schedule with, or if there is no scheduling,
  9035. returns nil."
  9036. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  9037. (when time
  9038. (org-time-string-to-time time))))
  9039. (defun org-get-deadline-time (pom &optional inherit)
  9040. "Get the deadline as a time tuple, of a format suitable for
  9041. calling org-deadline with, or if there is no scheduling, returns
  9042. nil."
  9043. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  9044. (when time
  9045. (org-time-string-to-time time))))
  9046. (defun org-remove-timestamp-with-keyword (keyword)
  9047. "Remove all time stamps with KEYWORD in the current entry."
  9048. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  9049. beg)
  9050. (save-excursion
  9051. (org-back-to-heading t)
  9052. (setq beg (point))
  9053. (outline-next-heading)
  9054. (while (re-search-backward re beg t)
  9055. (replace-match "")
  9056. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  9057. (equal (char-before) ?\ ))
  9058. (backward-delete-char 1)
  9059. (when (string-match "^[ \t]*$" (buffer-substring
  9060. (point-at-bol) (point-at-eol)))
  9061. (delete-region (point-at-bol)
  9062. (min (point-max) (1+ (point-at-eol))))))))))
  9063. (defvar org-time-was-given) ; dynamically scoped parameter
  9064. (defvar org-end-time-was-given) ; dynamically scoped parameter
  9065. (defun org-at-planning-p ()
  9066. "Non-nil when point is on a planning info line."
  9067. ;; This is as accurate and faster than `org-element-at-point' since
  9068. ;; planning info location is fixed in the section.
  9069. (or (let ((cached (org-element-at-point nil 'cached)))
  9070. (and cached
  9071. (eq 'planning (org-element-type cached))))
  9072. (org-with-wide-buffer
  9073. (beginning-of-line)
  9074. (and (looking-at-p org-planning-line-re)
  9075. (eq (point)
  9076. (ignore-errors
  9077. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  9078. (org-back-to-heading t)
  9079. (org-with-limited-levels (org-back-to-heading t)))
  9080. (line-beginning-position 2)))))))
  9081. (defun org-add-planning-info (what &optional time &rest remove)
  9082. "Insert new timestamp with keyword in the planning line.
  9083. WHAT indicates what kind of time stamp to add. It is a symbol
  9084. among `closed', `deadline', `scheduled' and nil. TIME indicates
  9085. the time to use. If none is given, the user is prompted for
  9086. a date. REMOVE indicates what kind of entries to remove. An old
  9087. WHAT entry will also be removed."
  9088. (org-fold-core-ignore-modifications
  9089. (let (org-time-was-given org-end-time-was-given default-time default-input)
  9090. (when (and (memq what '(scheduled deadline))
  9091. (or (not time)
  9092. (and (stringp time)
  9093. (string-match "^[-+]+[0-9]" time))))
  9094. ;; Try to get a default date/time from existing timestamp
  9095. (save-excursion
  9096. (org-back-to-heading t)
  9097. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  9098. (when (re-search-forward (if (eq what 'scheduled)
  9099. org-scheduled-time-regexp
  9100. org-deadline-time-regexp)
  9101. end t)
  9102. (setq ts (match-string 1)
  9103. default-time (org-time-string-to-time ts)
  9104. default-input (and ts (org-get-compact-tod ts)))))))
  9105. (when what
  9106. (setq time
  9107. (if (stringp time)
  9108. ;; This is a string (relative or absolute), set
  9109. ;; proper date.
  9110. (org-encode-time
  9111. (org-read-date-analyze
  9112. time default-time (decode-time default-time)))
  9113. ;; If necessary, get the time from the user
  9114. (or time (org-read-date nil 'to-time nil
  9115. (cl-case what
  9116. (deadline "DEADLINE")
  9117. (scheduled "SCHEDULED")
  9118. (otherwise nil))
  9119. default-time default-input)))))
  9120. (org-with-wide-buffer
  9121. (org-back-to-heading t)
  9122. (let ((planning? (save-excursion
  9123. (forward-line)
  9124. (looking-at-p org-planning-line-re))))
  9125. (cond
  9126. (planning?
  9127. (forward-line)
  9128. ;; Move to current indentation.
  9129. (skip-chars-forward " \t")
  9130. ;; Check if we have to remove something.
  9131. (dolist (type (if what (cons what remove) remove))
  9132. (save-excursion
  9133. (when (re-search-forward
  9134. (cl-case type
  9135. (closed org-closed-time-regexp)
  9136. (deadline org-deadline-time-regexp)
  9137. (scheduled org-scheduled-time-regexp)
  9138. (otherwise (error "Invalid planning type: %s" type)))
  9139. (line-end-position)
  9140. t)
  9141. ;; Delete until next keyword or end of line.
  9142. (delete-region
  9143. (match-beginning 0)
  9144. (if (re-search-forward org-keyword-time-not-clock-regexp
  9145. (line-end-position)
  9146. t)
  9147. (match-beginning 0)
  9148. (line-end-position))))))
  9149. ;; If there is nothing more to add and no more keyword is
  9150. ;; left, remove the line completely.
  9151. (if (and (looking-at-p "[ \t]*$") (not what))
  9152. (delete-region (line-end-position 0)
  9153. (line-end-position))
  9154. ;; If we removed last keyword, do not leave trailing white
  9155. ;; space at the end of line.
  9156. (let ((p (point)))
  9157. (save-excursion
  9158. (end-of-line)
  9159. (unless (= (skip-chars-backward " \t" p) 0)
  9160. (delete-region (point) (line-end-position)))))))
  9161. (what
  9162. (end-of-line)
  9163. (insert-and-inherit "\n")
  9164. (when org-adapt-indentation
  9165. (indent-to-column (1+ (org-outline-level)))))
  9166. (t nil)))
  9167. (when what
  9168. ;; Insert planning keyword.
  9169. (insert-and-inherit (cl-case what
  9170. (closed org-closed-string)
  9171. (deadline org-deadline-string)
  9172. (scheduled org-scheduled-string)
  9173. (otherwise (error "Invalid planning type: %s" what)))
  9174. " ")
  9175. ;; Insert associated timestamp.
  9176. (let ((ts (org-insert-time-stamp
  9177. time
  9178. (or org-time-was-given
  9179. (and (eq what 'closed) org-log-done-with-time))
  9180. (eq what 'closed)
  9181. nil nil (list org-end-time-was-given))))
  9182. (unless (eolp) (insert " "))
  9183. ts))))))
  9184. (defvar org-log-note-marker (make-marker)
  9185. "Marker pointing at the entry where the note is to be inserted.")
  9186. (defvar org-log-note-purpose nil)
  9187. (defvar org-log-note-state nil)
  9188. (defvar org-log-note-previous-state nil)
  9189. (defvar org-log-note-extra nil)
  9190. (defvar org-log-note-window-configuration nil)
  9191. (defvar org-log-note-return-to (make-marker))
  9192. (defvar org-log-note-effective-time nil
  9193. "Remembered current time.
  9194. So that dynamically scoped `org-extend-today-until' affects
  9195. timestamps in state change log.")
  9196. (defvar org-log-post-message nil
  9197. "Message to be displayed after a log note has been stored.
  9198. The auto-repeater uses this.")
  9199. (defun org-add-note ()
  9200. "Add a note to the current entry.
  9201. This is done in the same way as adding a state change note."
  9202. (interactive)
  9203. (org-add-log-setup 'note))
  9204. (defun org-log-beginning (&optional create)
  9205. "Return expected start of log notes in current entry.
  9206. When optional argument CREATE is non-nil, the function creates
  9207. a drawer to store notes, if necessary. Returned position ignores
  9208. narrowing."
  9209. (org-with-wide-buffer
  9210. (let ((drawer (org-log-into-drawer)))
  9211. (cond
  9212. (drawer
  9213. (org-end-of-meta-data)
  9214. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  9215. (end (if (org-at-heading-p) (point)
  9216. (save-excursion (outline-next-heading) (point))))
  9217. (case-fold-search t))
  9218. (catch 'exit
  9219. ;; Try to find existing drawer.
  9220. (while (re-search-forward regexp end t)
  9221. (let ((element (org-element-at-point)))
  9222. (when (eq (org-element-type element) 'drawer)
  9223. (let ((cend (org-element-property :contents-end element)))
  9224. (when (and (not org-log-states-order-reversed) cend)
  9225. (goto-char cend)))
  9226. (throw 'exit nil))))
  9227. ;; No drawer found. Create one, if permitted.
  9228. (when create
  9229. ;; Avoid situation when we insert drawer right before
  9230. ;; first "*". Otherwise, if the previous heading is
  9231. ;; folded, we are inserting after visible newline at
  9232. ;; the end of the fold, thus breaking the fold
  9233. ;; continuity.
  9234. (when (org-at-heading-p) (backward-char))
  9235. (org-fold-core-ignore-modifications
  9236. (unless (bolp) (insert-and-inherit "\n"))
  9237. (let ((beg (point)))
  9238. (insert-and-inherit ":" drawer ":\n:END:\n")
  9239. (org-indent-region beg (point))
  9240. (org-fold-region (line-end-position -1) (1- (point)) t (if (eq org-fold-core-style 'text-properties) 'drawer 'outline)))))
  9241. (end-of-line -1))))
  9242. (t
  9243. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  9244. (skip-chars-forward " \t\n")
  9245. (beginning-of-line)
  9246. (unless org-log-states-order-reversed
  9247. (org-skip-over-state-notes)
  9248. (skip-chars-backward " \t\n")
  9249. (beginning-of-line 2)))))
  9250. (if (bolp) (point) (line-beginning-position 2))))
  9251. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  9252. "Set up the post command hook to take a note.
  9253. If this is about to TODO state change, the new state is expected in STATE.
  9254. HOW is an indicator what kind of note should be created.
  9255. EXTRA is additional text that will be inserted into the notes buffer."
  9256. (move-marker org-log-note-marker (point))
  9257. (setq org-log-note-purpose purpose
  9258. org-log-note-state state
  9259. org-log-note-previous-state prev-state
  9260. org-log-note-how how
  9261. org-log-note-extra extra
  9262. org-log-note-effective-time (org-current-effective-time)
  9263. org-log-setup t)
  9264. (add-hook 'post-command-hook 'org-add-log-note 'append))
  9265. (defun org-skip-over-state-notes ()
  9266. "Skip past the list of State notes in an entry."
  9267. (when (ignore-errors (goto-char (org-in-item-p)))
  9268. (let* ((struct (org-list-struct))
  9269. (prevs (org-list-prevs-alist struct))
  9270. (regexp
  9271. (concat "[ \t]*- +"
  9272. (replace-regexp-in-string
  9273. " +" " +"
  9274. (org-replace-escapes
  9275. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  9276. `(("%d" . ,org-ts-regexp-inactive)
  9277. ("%D" . ,org-ts-regexp)
  9278. ("%s" . "\\(?:\"\\S-+\"\\)?")
  9279. ("%S" . "\\(?:\"\\S-+\"\\)?")
  9280. ("%t" . ,org-ts-regexp-inactive)
  9281. ("%T" . ,org-ts-regexp)
  9282. ("%u" . ".*?")
  9283. ("%U" . ".*?")))))))
  9284. (while (looking-at-p regexp)
  9285. (goto-char (or (org-list-get-next-item (point) struct prevs)
  9286. (org-list-get-item-end (point) struct)))))))
  9287. (defun org-add-log-note (&optional _purpose)
  9288. "Pop up a window for taking a note, and add this note later."
  9289. (remove-hook 'post-command-hook 'org-add-log-note)
  9290. (setq org-log-setup nil)
  9291. (setq org-log-note-window-configuration (current-window-configuration))
  9292. (delete-other-windows)
  9293. (move-marker org-log-note-return-to (point))
  9294. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  9295. (goto-char org-log-note-marker)
  9296. (org-switch-to-buffer-other-window "*Org Note*")
  9297. (erase-buffer)
  9298. (if (memq org-log-note-how '(time state))
  9299. (org-store-log-note)
  9300. (let ((org-inhibit-startup t)) (org-mode))
  9301. (insert (format "# Insert note for %s.
  9302. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  9303. (cl-case org-log-note-purpose
  9304. (clock-out "stopped clock")
  9305. (done "closed todo item")
  9306. (reschedule "rescheduling")
  9307. (delschedule "no longer scheduled")
  9308. (redeadline "changing deadline")
  9309. (deldeadline "removing deadline")
  9310. (refile "refiling")
  9311. (note "this entry")
  9312. (state
  9313. (format "state change from \"%s\" to \"%s\""
  9314. (or org-log-note-previous-state "")
  9315. (or org-log-note-state "")))
  9316. (t (error "This should not happen")))))
  9317. (when org-log-note-extra (insert org-log-note-extra))
  9318. (setq-local org-finish-function 'org-store-log-note)
  9319. (run-hooks 'org-log-buffer-setup-hook)))
  9320. (defvar org-note-abort nil) ; dynamically scoped
  9321. (defun org-store-log-note ()
  9322. "Finish taking a log note, and insert it to where it belongs."
  9323. (let ((txt (prog1 (buffer-string)
  9324. (kill-buffer)))
  9325. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  9326. lines)
  9327. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  9328. (setq txt (replace-match "" t t txt)))
  9329. (when (string-match "\\s-+\\'" txt)
  9330. (setq txt (replace-match "" t t txt)))
  9331. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  9332. (when (org-string-nw-p note)
  9333. (setq note
  9334. (org-replace-escapes
  9335. note
  9336. (list (cons "%u" (user-login-name))
  9337. (cons "%U" user-full-name)
  9338. (cons "%t" (format-time-string
  9339. (org-time-stamp-format 'long 'inactive)
  9340. org-log-note-effective-time))
  9341. (cons "%T" (format-time-string
  9342. (org-time-stamp-format 'long nil)
  9343. org-log-note-effective-time))
  9344. (cons "%d" (format-time-string
  9345. (org-time-stamp-format nil 'inactive)
  9346. org-log-note-effective-time))
  9347. (cons "%D" (format-time-string
  9348. (org-time-stamp-format nil nil)
  9349. org-log-note-effective-time))
  9350. (cons "%s" (cond
  9351. ((not org-log-note-state) "")
  9352. ((string-match-p org-ts-regexp
  9353. org-log-note-state)
  9354. (format "\"[%s]\""
  9355. (substring org-log-note-state 1 -1)))
  9356. (t (format "\"%s\"" org-log-note-state))))
  9357. (cons "%S"
  9358. (cond
  9359. ((not org-log-note-previous-state) "")
  9360. ((string-match-p org-ts-regexp
  9361. org-log-note-previous-state)
  9362. (format "\"[%s]\""
  9363. (substring
  9364. org-log-note-previous-state 1 -1)))
  9365. (t (format "\"%s\""
  9366. org-log-note-previous-state)))))))
  9367. (when lines (setq note (concat note " \\\\")))
  9368. (push note lines))
  9369. (when (and lines (not org-note-abort))
  9370. (with-current-buffer (marker-buffer org-log-note-marker)
  9371. (org-fold-core-ignore-modifications
  9372. (org-with-wide-buffer
  9373. ;; Find location for the new note.
  9374. (goto-char org-log-note-marker)
  9375. (set-marker org-log-note-marker nil)
  9376. ;; Note associated to a clock is to be located right after
  9377. ;; the clock. Do not move point.
  9378. (unless (eq org-log-note-purpose 'clock-out)
  9379. (goto-char (org-log-beginning t)))
  9380. ;; Make sure point is at the beginning of an empty line.
  9381. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert-and-inherit "\n")))
  9382. ((looking-at "[ \t]*\\S-") (save-excursion (insert-and-inherit "\n"))))
  9383. ;; In an existing list, add a new item at the top level.
  9384. ;; Otherwise, indent line like a regular one.
  9385. (let ((itemp (org-in-item-p)))
  9386. (if itemp
  9387. (indent-line-to
  9388. (let ((struct (save-excursion
  9389. (goto-char itemp) (org-list-struct))))
  9390. (org-list-get-ind (org-list-get-top-point struct) struct)))
  9391. (org-indent-line)))
  9392. (insert-and-inherit (org-list-bullet-string "-") (pop lines))
  9393. (let ((ind (org-list-item-body-column (line-beginning-position))))
  9394. (dolist (line lines)
  9395. (insert-and-inherit "\n")
  9396. (indent-line-to ind)
  9397. (insert-and-inherit line)))
  9398. (message "Note stored")
  9399. (org-back-to-heading t))))))
  9400. ;; Don't add undo information when called from `org-agenda-todo'.
  9401. (set-window-configuration org-log-note-window-configuration)
  9402. (with-current-buffer (marker-buffer org-log-note-return-to)
  9403. (goto-char org-log-note-return-to))
  9404. (move-marker org-log-note-return-to nil)
  9405. (when org-log-post-message (message "%s" org-log-post-message)))
  9406. (defun org-remove-empty-drawer-at (pos)
  9407. "Remove an empty drawer at position POS.
  9408. POS may also be a marker."
  9409. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  9410. (org-with-wide-buffer
  9411. (goto-char pos)
  9412. (let ((drawer (org-element-at-point)))
  9413. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  9414. (not (org-element-property :contents-begin drawer)))
  9415. (delete-region (org-element-property :begin drawer)
  9416. (progn (goto-char (org-element-property :end drawer))
  9417. (skip-chars-backward " \r\t\n")
  9418. (forward-line)
  9419. (point))))))))
  9420. (defvar org-ts-type nil)
  9421. (defun org-sparse-tree (&optional arg type)
  9422. "Create a sparse tree, prompt for the details.
  9423. This command can create sparse trees. You first need to select the type
  9424. of match used to create the tree:
  9425. t Show all TODO entries.
  9426. T Show entries with a specific TODO keyword.
  9427. m Show entries selected by a tags/property match.
  9428. p Enter a property name and its value (both with completion on existing
  9429. names/values) and show entries with that property.
  9430. r Show entries matching a regular expression (`/' can be used as well).
  9431. b Show deadlines and scheduled items before a date.
  9432. a Show deadlines and scheduled items after a date.
  9433. d Show deadlines due within `org-deadline-warning-days'.
  9434. D Show deadlines and scheduled items between a date range."
  9435. (interactive "P")
  9436. (setq type (or type org-sparse-tree-default-date-type))
  9437. (setq org-ts-type type)
  9438. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  9439. [d]eadlines [b]efore-date [a]fter-date [D]ates range
  9440. [c]ycle through date types: %s"
  9441. (cl-case type
  9442. (all "all timestamps")
  9443. (scheduled "only scheduled")
  9444. (deadline "only deadline")
  9445. (active "only active timestamps")
  9446. (inactive "only inactive timestamps")
  9447. (closed "with a closed time-stamp")
  9448. (otherwise "scheduled/deadline")))
  9449. (let ((answer (read-char-exclusive)))
  9450. (cl-case answer
  9451. (?c
  9452. (org-sparse-tree
  9453. arg
  9454. (cadr
  9455. (memq type '(nil all scheduled deadline active inactive closed)))))
  9456. (?d (call-interactively 'org-check-deadlines))
  9457. (?b (call-interactively 'org-check-before-date))
  9458. (?a (call-interactively 'org-check-after-date))
  9459. (?D (call-interactively 'org-check-dates-range))
  9460. (?t (call-interactively 'org-show-todo-tree))
  9461. (?T (org-show-todo-tree '(4)))
  9462. (?m (call-interactively 'org-match-sparse-tree))
  9463. ((?p ?P)
  9464. (let* ((kwd (completing-read
  9465. "Property: " (mapcar #'list (org-buffer-property-keys))))
  9466. (value (completing-read
  9467. "Value: " (mapcar #'list (org-property-values kwd)))))
  9468. (unless (string-match "\\`{.*}\\'" value)
  9469. (setq value (concat "\"" value "\"")))
  9470. (org-match-sparse-tree arg (concat kwd "=" value))))
  9471. ((?r ?R ?/) (call-interactively 'org-occur))
  9472. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  9473. (defvar-local org-occur-highlights nil
  9474. "List of overlays used for occur matches.")
  9475. (defvar-local org-occur-parameters nil
  9476. "Parameters of the active org-occur calls.
  9477. This is a list, each call to org-occur pushes as cons cell,
  9478. containing the regular expression and the callback, onto the list.
  9479. The list can contain several entries if `org-occur' has been called
  9480. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  9481. will only contain one set of parameters. When the highlights are
  9482. removed (for example with `C-c C-c', or with the next edit (depending
  9483. on `org-remove-highlights-with-change'), this variable is emptied
  9484. as well.")
  9485. (defun org-occur (regexp &optional keep-previous callback)
  9486. "Make a compact tree showing all matches of REGEXP.
  9487. The tree will show the lines where the regexp matches, and any other context
  9488. defined in `org-fold-show-context-detail', which see.
  9489. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  9490. done by a previous call to `org-occur' will be kept, to allow stacking of
  9491. calls to this command.
  9492. Optional argument CALLBACK can be a function of no argument. In this case,
  9493. it is called with point at the end of the match, match data being set
  9494. accordingly. Current match is shown only if the return value is non-nil.
  9495. The function must neither move point nor alter narrowing."
  9496. (interactive "sRegexp: \nP")
  9497. (when (equal regexp "")
  9498. (user-error "Regexp cannot be empty"))
  9499. (unless keep-previous
  9500. (org-remove-occur-highlights nil nil t))
  9501. (push (cons regexp callback) org-occur-parameters)
  9502. (let ((cnt 0))
  9503. (save-excursion
  9504. (goto-char (point-min))
  9505. (when (or (not keep-previous) ; do not want to keep
  9506. (not org-occur-highlights)) ; no previous matches
  9507. ;; hide everything
  9508. (org-cycle-overview))
  9509. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  9510. (isearch-no-upper-case-p regexp t)
  9511. org-occur-case-fold-search)))
  9512. (while (re-search-forward regexp nil t)
  9513. (when (or (not callback)
  9514. (save-match-data (funcall callback)))
  9515. (setq cnt (1+ cnt))
  9516. (when org-highlight-sparse-tree-matches
  9517. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  9518. (org-fold-show-context 'occur-tree)))))
  9519. (when org-remove-highlights-with-change
  9520. (add-hook 'before-change-functions 'org-remove-occur-highlights
  9521. nil 'local))
  9522. (unless org-sparse-tree-open-archived-trees
  9523. (org-fold-hide-archived-subtrees (point-min) (point-max)))
  9524. (run-hooks 'org-occur-hook)
  9525. (when (called-interactively-p 'interactive)
  9526. (message "%d match(es) for regexp %s" cnt regexp))
  9527. cnt))
  9528. (defun org-occur-next-match (&optional n _reset)
  9529. "Function for `next-error-function' to find sparse tree matches.
  9530. N is the number of matches to move, when negative move backwards.
  9531. This function always goes back to the starting point when no
  9532. match is found."
  9533. (let* ((limit (if (< n 0) (point-min) (point-max)))
  9534. (search-func (if (< n 0)
  9535. 'previous-single-char-property-change
  9536. 'next-single-char-property-change))
  9537. (n (abs n))
  9538. (pos (point))
  9539. p1)
  9540. (catch 'exit
  9541. (while (setq p1 (funcall search-func (point) 'org-type))
  9542. (when (equal p1 limit)
  9543. (goto-char pos)
  9544. (user-error "No more matches"))
  9545. (when (equal (get-char-property p1 'org-type) 'org-occur)
  9546. (setq n (1- n))
  9547. (when (= n 0)
  9548. (goto-char p1)
  9549. (throw 'exit (point))))
  9550. (goto-char p1))
  9551. (goto-char p1)
  9552. (user-error "No more matches"))))
  9553. (defun org-highlight-new-match (beg end)
  9554. "Highlight from BEG to END and mark the highlight is an occur headline."
  9555. (let ((ov (make-overlay beg end)))
  9556. (overlay-put ov 'face 'secondary-selection)
  9557. (overlay-put ov 'org-type 'org-occur)
  9558. (push ov org-occur-highlights)))
  9559. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  9560. "Remove the occur highlights from the buffer.
  9561. BEG and END are ignored. If NOREMOVE is nil, remove this function
  9562. from the `before-change-functions' in the current buffer."
  9563. (interactive)
  9564. (unless org-inhibit-highlight-removal
  9565. (mapc #'delete-overlay org-occur-highlights)
  9566. (setq org-occur-highlights nil)
  9567. (setq org-occur-parameters nil)
  9568. (unless noremove
  9569. (remove-hook 'before-change-functions
  9570. 'org-remove-occur-highlights 'local))))
  9571. ;;;; Priorities
  9572. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]+\\)\\] ?\\)"
  9573. "Regular expression matching the priority indicator.
  9574. A priority indicator can be e.g. [#A] or [#1].
  9575. This regular expression matches these groups:
  9576. 0 : the whole match, e.g. \"TODO [#A] Hack\"
  9577. 1 : the priority cookie, e.g. \"[#A]\"
  9578. 2 : the value of the priority cookie, e.g. \"A\".")
  9579. (defun org-priority-up ()
  9580. "Increase the priority of the current item."
  9581. (interactive)
  9582. (org-priority 'up))
  9583. (defun org-priority-down ()
  9584. "Decrease the priority of the current item."
  9585. (interactive)
  9586. (org-priority 'down))
  9587. (defun org-priority (&optional action show)
  9588. "Change the priority of an item.
  9589. When called interactively with a `\\[universal-argument]' prefix,
  9590. show the priority in the minibuffer instead of changing it.
  9591. When called programmatically, ACTION can be `set', `up', `down',
  9592. or a character."
  9593. (interactive "P")
  9594. (when show
  9595. ;; Deprecation warning inserted for Org 9.2; once enough time has
  9596. ;; passed the SHOW argument should be removed.
  9597. (warn "`org-priority' called with deprecated SHOW argument"))
  9598. (if (equal action '(4))
  9599. (org-priority-show)
  9600. (unless org-priority-enable-commands
  9601. (user-error "Priority commands are disabled"))
  9602. (setq action (or action 'set))
  9603. (let ((nump (< org-priority-lowest 65))
  9604. current new news have remove)
  9605. (save-excursion
  9606. (org-back-to-heading t)
  9607. (when (looking-at org-priority-regexp)
  9608. (let ((ms (match-string 2)))
  9609. (setq current (org-priority-to-value ms)
  9610. have t)))
  9611. (cond
  9612. ((eq action 'remove)
  9613. (setq remove t new ?\ ))
  9614. ((or (eq action 'set)
  9615. (integerp action))
  9616. (if (not (eq action 'set))
  9617. (setq new action)
  9618. (setq
  9619. new
  9620. (if nump
  9621. (let* ((msg (format "Priority %s-%s, SPC to remove: "
  9622. (number-to-string org-priority-highest)
  9623. (number-to-string org-priority-lowest)))
  9624. (s (if (< 9 org-priority-lowest)
  9625. (read-string msg)
  9626. (message msg)
  9627. (char-to-string (read-char-exclusive)))))
  9628. (if (equal s " ") ?\s (string-to-number s)))
  9629. (progn (message "Priority %c-%c, SPC to remove: "
  9630. org-priority-highest org-priority-lowest)
  9631. (save-match-data
  9632. (setq new (read-char-exclusive)))))))
  9633. (when (and (= (upcase org-priority-highest) org-priority-highest)
  9634. (= (upcase org-priority-lowest) org-priority-lowest))
  9635. (setq new (upcase new)))
  9636. (cond ((equal new ?\s) (setq remove t))
  9637. ((or (< (upcase new) org-priority-highest) (> (upcase new) org-priority-lowest))
  9638. (user-error
  9639. (if nump
  9640. "Priority must be between `%s' and `%s'"
  9641. "Priority must be between `%c' and `%c'")
  9642. org-priority-highest org-priority-lowest))))
  9643. ((eq action 'up)
  9644. (setq new (if have
  9645. (1- current) ; normal cycling
  9646. ;; last priority was empty
  9647. (if (eq last-command this-command)
  9648. org-priority-lowest ; wrap around empty to lowest
  9649. ;; default
  9650. (if org-priority-start-cycle-with-default
  9651. org-priority-default
  9652. (1- org-priority-default))))))
  9653. ((eq action 'down)
  9654. (setq new (if have
  9655. (1+ current) ; normal cycling
  9656. ;; last priority was empty
  9657. (if (eq last-command this-command)
  9658. org-priority-highest ; wrap around empty to highest
  9659. ;; default
  9660. (if org-priority-start-cycle-with-default
  9661. org-priority-default
  9662. (1+ org-priority-default))))))
  9663. (t (user-error "Invalid action")))
  9664. (when (or (< (upcase new) org-priority-highest)
  9665. (> (upcase new) org-priority-lowest))
  9666. (if (and (memq action '(up down))
  9667. (not have) (not (eq last-command this-command)))
  9668. ;; `new' is from default priority
  9669. (error
  9670. "The default can not be set, see `org-priority-default' why")
  9671. ;; normal cycling: `new' is beyond highest/lowest priority
  9672. ;; and is wrapped around to the empty priority
  9673. (setq remove t)))
  9674. ;; Numerical priorities are limited to 64, beyond that number,
  9675. ;; assume the priority cookie is a character.
  9676. (setq news (if (> new 64) (format "%c" new) (format "%s" new)))
  9677. (if have
  9678. (if remove
  9679. (replace-match "" t t nil 1)
  9680. (replace-match news t t nil 2))
  9681. (if remove
  9682. (user-error "No priority cookie found in line")
  9683. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  9684. (if (match-end 2)
  9685. (progn
  9686. (goto-char (match-end 2))
  9687. (insert " [#" news "]"))
  9688. (goto-char (match-beginning 3))
  9689. (insert "[#" news "] "))))
  9690. (org-align-tags))
  9691. (if remove
  9692. (message "Priority removed")
  9693. (message "Priority of current item set to %s" news)))))
  9694. (defalias 'org-show-priority 'org-priority-show)
  9695. (defun org-priority-show ()
  9696. "Show the priority of the current item.
  9697. This priority is composed of the main priority given with the [#A] cookies,
  9698. and by additional input from the age of a schedules or deadline entry."
  9699. (interactive)
  9700. (let ((pri (if (eq major-mode 'org-agenda-mode)
  9701. (org-get-at-bol 'priority)
  9702. (save-excursion
  9703. (save-match-data
  9704. (beginning-of-line)
  9705. (and (looking-at org-heading-regexp)
  9706. (org-get-priority (match-string 0))))))))
  9707. (message "Priority is %d" (if pri pri -1000))))
  9708. (defun org-get-priority (s)
  9709. "Find priority cookie and return priority.
  9710. S is a string against which you can match `org-priority-regexp'.
  9711. If `org-priority-get-priority-function' is set to a custom
  9712. function, use it. Otherwise process S and output the priority
  9713. value, an integer."
  9714. (save-match-data
  9715. (if (functionp org-priority-get-priority-function)
  9716. (funcall org-priority-get-priority-function s)
  9717. (if (not (string-match org-priority-regexp s))
  9718. (* 1000 (- org-priority-lowest org-priority-default))
  9719. (* 1000 (- org-priority-lowest
  9720. (org-priority-to-value (match-string 2 s))))))))
  9721. ;;;; Tags
  9722. (defvar org-agenda-archives-mode)
  9723. (defvar org-map-continue-from nil
  9724. "Position from where mapping should continue.
  9725. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  9726. (defvar org-scanner-tags nil
  9727. "The current tag list while the tags scanner is running.")
  9728. (defvar org-trust-scanner-tags nil
  9729. "Should `org-get-tags' use the tags for the scanner.
  9730. This is for internal dynamical scoping only.
  9731. When this is non-nil, the function `org-get-tags' will return the value
  9732. of `org-scanner-tags' instead of building the list by itself. This
  9733. can lead to large speed-ups when the tags scanner is used in a file with
  9734. many entries, and when the list of tags is retrieved, for example to
  9735. obtain a list of properties. Building the tags list for each entry in such
  9736. a file becomes an N^2 operation - but with this variable set, it scales
  9737. as N.")
  9738. (defvar org--matcher-tags-todo-only nil)
  9739. (defun org-scan-tags (action matcher todo-only &optional start-level)
  9740. "Scan headline tags with inheritance and produce output ACTION.
  9741. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  9742. or `agenda' to produce an entry list for an agenda view. It can also be
  9743. a Lisp form or a function that should be called at each matched headline, in
  9744. this case the return value is a list of all return values from these calls.
  9745. MATCHER is a function accepting three arguments, returning
  9746. a non-nil value whenever a given set of tags qualifies a headline
  9747. for inclusion. See `org-make-tags-matcher' for more information.
  9748. As a special case, it can also be set to t (respectively nil) in
  9749. order to match all (respectively none) headline.
  9750. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  9751. included in the output.
  9752. START-LEVEL can be a string with asterisks, reducing the scope to
  9753. headlines matching this string."
  9754. (require 'org-agenda)
  9755. (let* ((re (concat "^"
  9756. (if start-level
  9757. ;; Get the correct level to match
  9758. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  9759. org-outline-regexp)
  9760. " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
  9761. " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
  9762. (props (list 'face 'default
  9763. 'done-face 'org-agenda-done
  9764. 'undone-face 'default
  9765. 'mouse-face 'highlight
  9766. 'org-not-done-regexp org-not-done-regexp
  9767. 'org-todo-regexp org-todo-regexp
  9768. 'org-complex-heading-regexp org-complex-heading-regexp
  9769. 'help-echo
  9770. (format "mouse-2 or RET jump to Org file %S"
  9771. (abbreviate-file-name
  9772. (or (buffer-file-name (buffer-base-buffer))
  9773. (buffer-name (buffer-base-buffer)))))))
  9774. (org-map-continue-from nil)
  9775. lspos tags tags-list
  9776. (tags-alist (list (cons 0 org-file-tags)))
  9777. (llast 0) rtn rtn1 level category i txt
  9778. todo marker entry priority
  9779. ts-date ts-date-type ts-date-pair)
  9780. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  9781. (setq action (list 'lambda nil action)))
  9782. (save-excursion
  9783. (goto-char (point-min))
  9784. (when (eq action 'sparse-tree)
  9785. (org-cycle-overview)
  9786. (org-remove-occur-highlights))
  9787. (if (org-element--cache-active-p)
  9788. (let ((fast-re (concat "^"
  9789. (if start-level
  9790. ;; Get the correct level to match
  9791. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  9792. org-outline-regexp))))
  9793. (org-element-cache-map
  9794. (lambda (el)
  9795. (goto-char (org-element-property :begin el))
  9796. (setq todo (org-element-property :todo-keyword el)
  9797. level (org-element-property :level el)
  9798. category (org-entry-get-with-inheritance "CATEGORY" nil el)
  9799. tags-list (org-get-tags el)
  9800. org-scanner-tags tags-list)
  9801. (when (eq action 'agenda)
  9802. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  9803. ts-date (car ts-date-pair)
  9804. ts-date-type (cdr ts-date-pair)))
  9805. (catch :skip
  9806. (when (and
  9807. ;; eval matcher only when the todo condition is OK
  9808. (and (or (not todo-only) (member todo org-todo-keywords-1))
  9809. (if (functionp matcher)
  9810. (let ((case-fold-search t) (org-trust-scanner-tags t))
  9811. (funcall matcher todo tags-list level))
  9812. matcher))
  9813. ;; Call the skipper, but return t if it does not
  9814. ;; skip, so that the `and' form continues evaluating.
  9815. (progn
  9816. (unless (eq action 'sparse-tree) (org-agenda-skip el))
  9817. t)
  9818. ;; Check if timestamps are deselecting this entry
  9819. (or (not todo-only)
  9820. (and (member todo org-todo-keywords-1)
  9821. (or (not org-agenda-tags-todo-honor-ignore-options)
  9822. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  9823. ;; select this headline
  9824. (cond
  9825. ((eq action 'sparse-tree)
  9826. (and org-highlight-sparse-tree-matches
  9827. (org-get-heading) (match-end 0)
  9828. (org-highlight-new-match
  9829. (match-beginning 1) (match-end 1)))
  9830. (org-fold-show-context 'tags-tree))
  9831. ((eq action 'agenda)
  9832. (let* ((effort (org-entry-get (point) org-effort-property))
  9833. (effort-minutes (when effort (save-match-data (org-duration-to-minutes effort)))))
  9834. (setq txt (org-agenda-format-item
  9835. ""
  9836. ;; Add `effort' and `effort-minutes'
  9837. ;; properties for prefix format.
  9838. (org-add-props
  9839. (concat
  9840. (if (eq org-tags-match-list-sublevels 'indented)
  9841. (make-string (1- level) ?.) "")
  9842. (org-get-heading))
  9843. nil
  9844. 'effort effort
  9845. 'effort-minutes effort-minutes)
  9846. (make-string level ?\s)
  9847. category
  9848. tags-list)
  9849. priority (org-get-priority txt))
  9850. ;; Now add `effort' and `effort-minutes' to
  9851. ;; full agenda line.
  9852. (setq txt (org-add-props txt nil
  9853. 'effort effort
  9854. 'effort-minutes effort-minutes)))
  9855. (goto-char (org-element-property :begin el))
  9856. (setq marker (org-agenda-new-marker))
  9857. (org-add-props txt props
  9858. 'org-marker marker 'org-hd-marker marker 'org-category category
  9859. 'todo-state todo
  9860. 'ts-date ts-date
  9861. 'priority priority
  9862. 'type (concat "tagsmatch" ts-date-type))
  9863. (push txt rtn))
  9864. ((functionp action)
  9865. (setq org-map-continue-from nil)
  9866. (save-excursion
  9867. (setq rtn1 (funcall action))
  9868. (push rtn1 rtn)))
  9869. (t (user-error "Invalid action")))
  9870. ;; if we are to skip sublevels, jump to end of subtree
  9871. (unless org-tags-match-list-sublevels
  9872. (goto-char (1- (org-element-property :end el))))))
  9873. ;; Get the correct position from where to continue
  9874. (when org-map-continue-from
  9875. (setq org-element-cache-map-continue-from org-map-continue-from)
  9876. (goto-char org-map-continue-from))
  9877. ;; Return nil.
  9878. nil)
  9879. :next-re fast-re
  9880. :fail-re fast-re
  9881. :narrow t))
  9882. (while (let (case-fold-search)
  9883. (re-search-forward re nil t))
  9884. (setq org-map-continue-from nil)
  9885. (catch :skip
  9886. ;; Ignore closing parts of inline tasks.
  9887. (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
  9888. (throw :skip t))
  9889. (setq todo (and (match-end 1) (match-string-no-properties 1)))
  9890. (setq tags (and (match-end 4) (org-trim (match-string-no-properties 4))))
  9891. (goto-char (setq lspos (match-beginning 0)))
  9892. (setq level (org-reduced-level (org-outline-level))
  9893. category (org-get-category))
  9894. (when (eq action 'agenda)
  9895. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  9896. ts-date (car ts-date-pair)
  9897. ts-date-type (cdr ts-date-pair)))
  9898. (setq i llast llast level)
  9899. ;; remove tag lists from same and sublevels
  9900. (while (>= i level)
  9901. (when (setq entry (assoc i tags-alist))
  9902. (setq tags-alist (delete entry tags-alist)))
  9903. (setq i (1- i)))
  9904. ;; add the next tags
  9905. (when tags
  9906. (setq tags (org-split-string tags ":")
  9907. tags-alist
  9908. (cons (cons level tags) tags-alist)))
  9909. ;; compile tags for current headline
  9910. (setq tags-list
  9911. (if org-use-tag-inheritance
  9912. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  9913. tags)
  9914. org-scanner-tags tags-list)
  9915. (when org-use-tag-inheritance
  9916. (setcdr (car tags-alist)
  9917. (mapcar (lambda (x)
  9918. (setq x (copy-sequence x))
  9919. (org-add-prop-inherited x))
  9920. (cdar tags-alist))))
  9921. (when (and tags org-use-tag-inheritance
  9922. (or (not (eq t org-use-tag-inheritance))
  9923. org-tags-exclude-from-inheritance))
  9924. ;; Selective inheritance, remove uninherited ones.
  9925. (setcdr (car tags-alist)
  9926. (org-remove-uninherited-tags (cdar tags-alist))))
  9927. (when (and
  9928. ;; eval matcher only when the todo condition is OK
  9929. (and (or (not todo-only) (member todo org-todo-keywords-1))
  9930. (if (functionp matcher)
  9931. (let ((case-fold-search t) (org-trust-scanner-tags t))
  9932. (funcall matcher todo tags-list level))
  9933. matcher))
  9934. ;; Call the skipper, but return t if it does not
  9935. ;; skip, so that the `and' form continues evaluating.
  9936. (progn
  9937. (unless (eq action 'sparse-tree) (org-agenda-skip))
  9938. t)
  9939. ;; Check if timestamps are deselecting this entry
  9940. (or (not todo-only)
  9941. (and (member todo org-todo-keywords-1)
  9942. (or (not org-agenda-tags-todo-honor-ignore-options)
  9943. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  9944. ;; select this headline
  9945. (cond
  9946. ((eq action 'sparse-tree)
  9947. (and org-highlight-sparse-tree-matches
  9948. (org-get-heading) (match-end 0)
  9949. (org-highlight-new-match
  9950. (match-beginning 1) (match-end 1)))
  9951. (org-fold-show-context 'tags-tree))
  9952. ((eq action 'agenda)
  9953. (setq txt (org-agenda-format-item
  9954. ""
  9955. (concat
  9956. (if (eq org-tags-match-list-sublevels 'indented)
  9957. (make-string (1- level) ?.) "")
  9958. (org-get-heading))
  9959. (make-string level ?\s)
  9960. category
  9961. tags-list)
  9962. priority (org-get-priority txt))
  9963. (goto-char lspos)
  9964. (setq marker (org-agenda-new-marker))
  9965. (org-add-props txt props
  9966. 'org-marker marker 'org-hd-marker marker 'org-category category
  9967. 'todo-state todo
  9968. 'ts-date ts-date
  9969. 'priority priority
  9970. 'type (concat "tagsmatch" ts-date-type))
  9971. (push txt rtn))
  9972. ((functionp action)
  9973. (setq org-map-continue-from nil)
  9974. (save-excursion
  9975. (setq rtn1 (funcall action))
  9976. (push rtn1 rtn)))
  9977. (t (user-error "Invalid action")))
  9978. ;; if we are to skip sublevels, jump to end of subtree
  9979. (unless org-tags-match-list-sublevels
  9980. (org-end-of-subtree t)
  9981. (backward-char 1))))
  9982. ;; Get the correct position from where to continue
  9983. (if org-map-continue-from
  9984. (goto-char org-map-continue-from)
  9985. (and (= (point) lspos) (end-of-line 1))))))
  9986. (when (and (eq action 'sparse-tree)
  9987. (not org-sparse-tree-open-archived-trees))
  9988. (org-fold-hide-archived-subtrees (point-min) (point-max)))
  9989. (nreverse rtn)))
  9990. (defun org-remove-uninherited-tags (tags)
  9991. "Remove all tags that are not inherited from the list TAGS."
  9992. (cond
  9993. ((eq org-use-tag-inheritance t)
  9994. (if org-tags-exclude-from-inheritance
  9995. (org-delete-all org-tags-exclude-from-inheritance tags)
  9996. tags))
  9997. ((not org-use-tag-inheritance) nil)
  9998. ((stringp org-use-tag-inheritance)
  9999. (delq nil (mapcar
  10000. (lambda (x)
  10001. (if (and (string-match org-use-tag-inheritance x)
  10002. (not (member x org-tags-exclude-from-inheritance)))
  10003. x nil))
  10004. tags)))
  10005. ((listp org-use-tag-inheritance)
  10006. (delq nil (mapcar
  10007. (lambda (x)
  10008. (if (member x org-use-tag-inheritance) x nil))
  10009. tags)))))
  10010. (defun org-match-sparse-tree (&optional todo-only match)
  10011. "Create a sparse tree according to tags string MATCH.
  10012. MATCH is a string with match syntax. It can contain a selection
  10013. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  10014. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  10015. those. See the manual for details.
  10016. If optional argument TODO-ONLY is non-nil, only select lines that
  10017. are also TODO tasks."
  10018. (interactive "P")
  10019. (org-agenda-prepare-buffers (list (current-buffer)))
  10020. (let ((org--matcher-tags-todo-only todo-only))
  10021. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match t))
  10022. org--matcher-tags-todo-only)))
  10023. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  10024. (defvar org-cached-props nil)
  10025. (defun org-cached-entry-get (pom property)
  10026. (if (or (eq t org-use-property-inheritance)
  10027. (and (stringp org-use-property-inheritance)
  10028. (let ((case-fold-search t))
  10029. (string-match-p org-use-property-inheritance property)))
  10030. (and (listp org-use-property-inheritance)
  10031. (member-ignore-case property org-use-property-inheritance)))
  10032. ;; Caching is not possible, check it directly.
  10033. (org-entry-get pom property 'inherit)
  10034. ;; Get all properties, so we can do complicated checks easily.
  10035. (cdr (assoc-string property
  10036. (or org-cached-props
  10037. (setq org-cached-props (org-entry-properties pom)))
  10038. t))))
  10039. (defun org-global-tags-completion-table (&optional files)
  10040. "Return the list of all tags in all agenda buffer/files.
  10041. Optional FILES argument is a list of files which can be used
  10042. instead of the agenda files."
  10043. (save-excursion
  10044. (org-uniquify
  10045. (delq nil
  10046. (apply #'append
  10047. (mapcar
  10048. (lambda (file)
  10049. (set-buffer (find-file-noselect file))
  10050. (org--tag-add-to-alist
  10051. (org-get-buffer-tags)
  10052. (mapcar (lambda (x)
  10053. (and (stringp (car-safe x))
  10054. (list (car-safe x))))
  10055. org-current-tag-alist)))
  10056. (if (car-safe files) files
  10057. (org-agenda-files))))))))
  10058. (defun org-make-tags-matcher (match &optional only-local-tags)
  10059. "Create the TAGS/TODO matcher form for the selection string MATCH.
  10060. Returns a cons of the selection string MATCH and a function
  10061. implementing the matcher.
  10062. The matcher is to be called at an Org entry, with point on the
  10063. headline, and returns non-nil if the entry matches the selection
  10064. string MATCH. It must be called with three arguments: the TODO
  10065. keyword at the entry (or nil if none), the list of all tags at
  10066. the entry including inherited ones and the reduced level of the
  10067. headline. Additionally, the category of the entry, if any, must
  10068. be specified as the text property `org-category' on the headline.
  10069. This function sets the variable `org--matcher-tags-todo-only' to
  10070. a non-nil value if the matcher restricts matching to TODO
  10071. entries, otherwise it is not touched.
  10072. When ONLY-LOCAL-TAGS is non-nil, ignore the global tag completion
  10073. table, only get buffer tags.
  10074. See also `org-scan-tags'."
  10075. (unless match
  10076. ;; Get a new match request, with completion against the global
  10077. ;; tags table and the local tags in current buffer.
  10078. (let ((org-last-tags-completion-table
  10079. (org--tag-add-to-alist
  10080. (org-get-buffer-tags)
  10081. (unless only-local-tags
  10082. (org-global-tags-completion-table)))))
  10083. (setq match
  10084. (completing-read
  10085. "Match: "
  10086. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  10087. (let ((match0 match)
  10088. (re (concat
  10089. "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
  10090. "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
  10091. "\\([<>=]\\{1,2\\}\\)"
  10092. "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
  10093. "\\|" org-tag-re "\\)"))
  10094. (start 0)
  10095. tagsmatch todomatch tagsmatcher todomatcher)
  10096. ;; Expand group tags.
  10097. (setq match (org-tags-expand match))
  10098. ;; Check if there is a TODO part of this match, which would be the
  10099. ;; part after a "/". To make sure that this slash is not part of
  10100. ;; a property value to be matched against, we also check that
  10101. ;; there is no / after that slash. First, find the last slash.
  10102. (let ((s 0))
  10103. (while (string-match "/+" match s)
  10104. (setq start (match-beginning 0))
  10105. (setq s (match-end 0))))
  10106. (if (and (string-match "/+" match start)
  10107. (not (string-match-p "\"" match start)))
  10108. ;; Match contains also a TODO-matching request.
  10109. (progn
  10110. (setq tagsmatch (substring match 0 (match-beginning 0)))
  10111. (setq todomatch (substring match (match-end 0)))
  10112. (when (string-prefix-p "!" todomatch)
  10113. (setq org--matcher-tags-todo-only t)
  10114. (setq todomatch (substring todomatch 1)))
  10115. (when (string-match "\\`\\s-*\\'" todomatch)
  10116. (setq todomatch nil)))
  10117. ;; Only matching tags.
  10118. (setq tagsmatch match)
  10119. (setq todomatch nil))
  10120. ;; Make the tags matcher.
  10121. (when (org-string-nw-p tagsmatch)
  10122. (let ((orlist nil)
  10123. (orterms (org-split-string tagsmatch "|"))
  10124. term)
  10125. (while (setq term (pop orterms))
  10126. (while (and (equal (substring term -1) "\\") orterms)
  10127. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  10128. (while (string-match re term)
  10129. (let* ((rest (substring term (match-end 0)))
  10130. (minus (and (match-end 1)
  10131. (equal (match-string 1 term) "-")))
  10132. (tag (save-match-data
  10133. (replace-regexp-in-string
  10134. "\\\\-" "-" (match-string 2 term))))
  10135. (regexp (eq (string-to-char tag) ?{))
  10136. (levelp (match-end 4))
  10137. (propp (match-end 5))
  10138. (mm
  10139. (cond
  10140. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  10141. (levelp
  10142. `(,(org-op-to-function (match-string 3 term))
  10143. level
  10144. ,(string-to-number (match-string 4 term))))
  10145. (propp
  10146. (let* ((gv (pcase (upcase (match-string 5 term))
  10147. ("CATEGORY"
  10148. '(org-get-category (point)))
  10149. ("TODO" 'todo)
  10150. (p `(org-cached-entry-get nil ,p))))
  10151. (pv (match-string 7 term))
  10152. (regexp (eq (string-to-char pv) ?{))
  10153. (strp (eq (string-to-char pv) ?\"))
  10154. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  10155. (po (org-op-to-function (match-string 6 term)
  10156. (if timep 'time strp))))
  10157. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  10158. (when timep (setq pv (org-matcher-time pv)))
  10159. (cond ((and regexp (eq po '/=))
  10160. `(not (string-match ,pv (or ,gv ""))))
  10161. (regexp `(string-match ,pv (or ,gv "")))
  10162. (strp `(,po (or ,gv "") ,pv))
  10163. (t
  10164. `(,po
  10165. (string-to-number (or ,gv ""))
  10166. ,(string-to-number pv))))))
  10167. (t `(member ,tag tags-list)))))
  10168. (push (if minus `(not ,mm) mm) tagsmatcher)
  10169. (setq term rest)))
  10170. (push `(and ,@tagsmatcher) orlist)
  10171. (setq tagsmatcher nil))
  10172. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  10173. ;; Make the TODO matcher.
  10174. (when (org-string-nw-p todomatch)
  10175. (let ((orlist nil))
  10176. (dolist (term (org-split-string todomatch "|"))
  10177. (while (string-match re term)
  10178. (let* ((minus (and (match-end 1)
  10179. (equal (match-string 1 term) "-")))
  10180. (kwd (match-string 2 term))
  10181. (regexp (eq (string-to-char kwd) ?{))
  10182. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  10183. `(equal todo ,kwd))))
  10184. (push (if minus `(not ,mm) mm) todomatcher))
  10185. (setq term (substring term (match-end 0))))
  10186. (push (if (> (length todomatcher) 1)
  10187. (cons 'and todomatcher)
  10188. (car todomatcher))
  10189. orlist)
  10190. (setq todomatcher nil))
  10191. (setq todomatcher (cons 'or orlist))))
  10192. ;; Return the string and function of the matcher. If no
  10193. ;; tags-specific or todo-specific matcher exists, match
  10194. ;; everything.
  10195. (let ((matcher (if (and tagsmatcher todomatcher)
  10196. `(and ,tagsmatcher ,todomatcher)
  10197. (or tagsmatcher todomatcher t))))
  10198. (when org--matcher-tags-todo-only
  10199. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  10200. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  10201. (defun org--tags-expand-group (group tag-groups expanded)
  10202. "Recursively expand all tags in GROUP, according to TAG-GROUPS.
  10203. TAG-GROUPS is the list of groups used for expansion. EXPANDED is
  10204. an accumulator used in recursive calls."
  10205. (dolist (tag group)
  10206. (unless (member tag expanded)
  10207. (let ((group (assoc tag tag-groups)))
  10208. (push tag expanded)
  10209. (when group
  10210. (setq expanded
  10211. (org--tags-expand-group (cdr group) tag-groups expanded))))))
  10212. expanded)
  10213. (defun org-tags-expand (match &optional single-as-list)
  10214. "Expand group tags in MATCH.
  10215. This replaces every group tag in MATCH with a regexp tag search.
  10216. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  10217. will be replaced like this:
  10218. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10219. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10220. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10221. Replacing by a regexp preserves the structure of the match.
  10222. E.g., this expansion
  10223. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  10224. will match anything tagged with \"Lab\" and \"Home\", or tagged
  10225. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"Home\".
  10226. A group tag in MATCH can contain regular expressions of its own.
  10227. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  10228. will be replaced like this:
  10229. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  10230. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  10231. assumed to be a single group tag, and the function will return
  10232. the list of tags in this group."
  10233. (unless (org-string-nw-p match) (error "Invalid match tag: %S" match))
  10234. (let ((tag-groups
  10235. (or org-tag-groups-alist-for-agenda org-tag-groups-alist)))
  10236. (cond
  10237. (single-as-list (org--tags-expand-group (list match) tag-groups nil))
  10238. (org-group-tags
  10239. (let* ((case-fold-search t)
  10240. (tag-syntax org-mode-syntax-table)
  10241. (group-keys (mapcar #'car tag-groups))
  10242. (key-regexp (concat "\\([+-]?\\)" (regexp-opt group-keys 'words)))
  10243. (return-match match))
  10244. ;; Mark regexp-expressions in the match-expression so that we
  10245. ;; do not replace them later on.
  10246. (let ((s 0))
  10247. (while (string-match "{.+?}" return-match s)
  10248. (setq s (match-end 0))
  10249. (add-text-properties
  10250. (match-beginning 0) (match-end 0) '(regexp t) return-match)))
  10251. ;; @ and _ are allowed as word-components in tags.
  10252. (modify-syntax-entry ?@ "w" tag-syntax)
  10253. (modify-syntax-entry ?_ "w" tag-syntax)
  10254. ;; For each tag token found in MATCH, compute a regexp and it
  10255. (with-syntax-table tag-syntax
  10256. (replace-regexp-in-string
  10257. key-regexp
  10258. (lambda (m)
  10259. (if (get-text-property (match-beginning 2) 'regexp m)
  10260. m ;regexp tag: ignore
  10261. (let* ((operator (match-string 1 m))
  10262. (tag-token (let ((tag (match-string 2 m)))
  10263. (list tag)))
  10264. regexp-tags regular-tags)
  10265. ;; Partition tags between regexp and regular tags.
  10266. ;; Remove curly bracket syntax from regexp tags.
  10267. (dolist (tag (org--tags-expand-group tag-token tag-groups nil))
  10268. (save-match-data
  10269. (if (string-match "{\\(.+?\\)}" tag)
  10270. (push (match-string 1 tag) regexp-tags)
  10271. (push tag regular-tags))))
  10272. ;; Replace tag token by the appropriate regexp.
  10273. ;; Regular tags need to be regexp-quoted, whereas
  10274. ;; regexp-tags are inserted as-is.
  10275. (let ((regular (regexp-opt regular-tags))
  10276. (regexp (mapconcat #'identity regexp-tags "\\|")))
  10277. (concat operator
  10278. (cond
  10279. ((null regular-tags) (format "{%s}" regexp))
  10280. ((null regexp-tags) (format "{\\<%s\\>}" regular))
  10281. (t (format "{\\<%s\\>\\|%s}" regular regexp))))))))
  10282. return-match
  10283. t t))))
  10284. (t match))))
  10285. (defun org-op-to-function (op &optional stringp)
  10286. "Turn an operator into the appropriate function."
  10287. (setq op
  10288. (cond
  10289. ((equal op "<" ) '(< org-string< org-time<))
  10290. ((equal op ">" ) '(> org-string> org-time>))
  10291. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  10292. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  10293. ((member op '("=" "==")) '(= string= org-time=))
  10294. ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
  10295. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  10296. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  10297. (defvar org-tags-overlay (make-overlay 1 1))
  10298. (delete-overlay org-tags-overlay)
  10299. (defun org-add-prop-inherited (s)
  10300. (add-text-properties 0 (length s) '(inherited t) s)
  10301. s)
  10302. (defun org-toggle-tag (tag &optional onoff)
  10303. "Toggle the tag TAG for the current line.
  10304. If ONOFF is `on' or `off', don't toggle but set to this state."
  10305. (save-excursion
  10306. (org-back-to-heading t)
  10307. (let ((current
  10308. ;; Reverse the tags list so any new tag is appended to the
  10309. ;; current list of tags.
  10310. (nreverse (org-get-tags nil t)))
  10311. res)
  10312. (pcase onoff
  10313. (`off (setq current (delete tag current)))
  10314. ((or `on (guard (not (member tag current))))
  10315. (setq res t)
  10316. (cl-pushnew tag current :test #'equal))
  10317. (_ (setq current (delete tag current))))
  10318. (org-set-tags (nreverse current))
  10319. res)))
  10320. (defun org--align-tags-here (to-col)
  10321. "Align tags on the current headline to TO-COL.
  10322. Assume point is on a headline. Preserve point when aligning
  10323. tags."
  10324. (when (org-match-line org-tag-line-re)
  10325. (let* ((tags-start (match-beginning 1))
  10326. (blank-start (save-excursion
  10327. (goto-char tags-start)
  10328. (skip-chars-backward " \t")
  10329. (point)))
  10330. (new (max (if (>= to-col 0) to-col
  10331. (- (abs to-col) (string-width (match-string 1))))
  10332. ;; Introduce at least one space after the heading
  10333. ;; or the stars.
  10334. (save-excursion
  10335. (goto-char blank-start)
  10336. (1+ (current-column)))))
  10337. (current
  10338. (save-excursion (goto-char tags-start) (current-column)))
  10339. (origin (point-marker))
  10340. (column (current-column))
  10341. (in-blank? (and (> origin blank-start) (<= origin tags-start))))
  10342. (when (/= new current)
  10343. (delete-region blank-start tags-start)
  10344. (goto-char blank-start)
  10345. (let ((indent-tabs-mode nil)) (indent-to new))
  10346. ;; Try to move back to original position. If point was in the
  10347. ;; blanks before the tags, ORIGIN marker is of no use because
  10348. ;; it now points to BLANK-START. Use COLUMN instead.
  10349. (if in-blank? (org-move-to-column column) (goto-char origin))))))
  10350. (defun org-set-tags-command (&optional arg)
  10351. "Set the tags for the current visible entry.
  10352. When called with `\\[universal-argument]' prefix argument ARG, \
  10353. realign all tags
  10354. in the current buffer.
  10355. When called with `\\[universal-argument] \\[universal-argument]' prefix argument, \
  10356. unconditionally do not
  10357. offer the fast tag selection interface.
  10358. If a region is active, set tags in the region according to the
  10359. setting of `org-loop-over-headlines-in-active-region'.
  10360. This function is for interactive use only;
  10361. in Lisp code use `org-set-tags' instead."
  10362. (interactive "P")
  10363. (let ((org-use-fast-tag-selection
  10364. (unless (equal '(16) arg) org-use-fast-tag-selection)))
  10365. (cond
  10366. ((equal '(4) arg) (org-align-tags t))
  10367. ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
  10368. (let (org-loop-over-headlines-in-active-region) ; hint: infinite recursion.
  10369. (org-map-entries
  10370. #'org-set-tags-command
  10371. nil
  10372. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  10373. 'region-start-level
  10374. 'region)
  10375. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
  10376. (t
  10377. (save-excursion
  10378. (org-back-to-heading)
  10379. (let* ((all-tags (org-get-tags))
  10380. (table (setq org-last-tags-completion-table
  10381. (org--tag-add-to-alist
  10382. (and org-complete-tags-always-offer-all-agenda-tags
  10383. (org-global-tags-completion-table
  10384. (org-agenda-files)))
  10385. (or org-current-tag-alist (org-get-buffer-tags)))))
  10386. (current-tags
  10387. (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
  10388. all-tags))
  10389. (inherited-tags
  10390. (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
  10391. all-tags))
  10392. (tags
  10393. (replace-regexp-in-string
  10394. ;; Ignore all forbidden characters in tags.
  10395. "[^[:alnum:]_@#%]+" ":"
  10396. (if (or (eq t org-use-fast-tag-selection)
  10397. (and org-use-fast-tag-selection
  10398. (delq nil (mapcar #'cdr table))))
  10399. (org-fast-tag-selection
  10400. current-tags
  10401. inherited-tags
  10402. table
  10403. (and org-fast-tag-selection-include-todo org-todo-key-alist))
  10404. (let ((org-add-colon-after-tag-completion (< 1 (length table)))
  10405. (crm-separator "[ \t]*:[ \t]*"))
  10406. (mapconcat #'identity
  10407. (completing-read-multiple
  10408. "Tags: "
  10409. org-last-tags-completion-table
  10410. nil nil (org-make-tag-string current-tags)
  10411. 'org-tags-history)
  10412. ":"))))))
  10413. (org-set-tags tags)))))
  10414. ;; `save-excursion' may not replace the point at the right
  10415. ;; position.
  10416. (when (and (save-excursion (skip-chars-backward "*") (bolp))
  10417. (looking-at-p " "))
  10418. (forward-char))))
  10419. (defun org-align-tags (&optional all)
  10420. "Align tags in current entry.
  10421. When optional argument ALL is non-nil, align all tags in the
  10422. visible part of the buffer."
  10423. (let ((get-indent-column
  10424. (lambda ()
  10425. (let ((offset (if (bound-and-true-p org-indent-mode)
  10426. (* (1- org-indent-indentation-per-level)
  10427. (1- (org-current-level)))
  10428. 0)))
  10429. (+ org-tags-column
  10430. (if (> org-tags-column 0) (- offset) offset))))))
  10431. (if (and (not all) (org-at-heading-p))
  10432. (org--align-tags-here (funcall get-indent-column))
  10433. (save-excursion
  10434. (if all
  10435. (progn
  10436. (goto-char (point-min))
  10437. (while (re-search-forward org-tag-line-re nil t)
  10438. (org--align-tags-here (funcall get-indent-column))))
  10439. (org-back-to-heading t)
  10440. (org--align-tags-here (funcall get-indent-column)))))))
  10441. (defun org-set-tags (tags)
  10442. "Set the tags of the current entry to TAGS, replacing current tags.
  10443. TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
  10444. If TAGS is nil or the empty string, all tags are removed.
  10445. This function assumes point is on a headline."
  10446. (org-with-wide-buffer
  10447. (org-fold-core-ignore-modifications
  10448. (let ((tags (pcase tags
  10449. ((pred listp) tags)
  10450. ((pred stringp) (split-string (org-trim tags) ":" t))
  10451. (_ (error "Invalid tag specification: %S" tags))))
  10452. (old-tags (org-get-tags nil t))
  10453. (tags-change? nil))
  10454. (when (functionp org-tags-sort-function)
  10455. (setq tags (sort tags org-tags-sort-function)))
  10456. (setq tags-change? (not (equal tags old-tags)))
  10457. (when tags-change?
  10458. ;; Delete previous tags and any trailing white space.
  10459. (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
  10460. (line-end-position)))
  10461. (skip-chars-backward " \t")
  10462. (delete-region (point) (line-end-position))
  10463. ;; Deleting white spaces may break an otherwise empty headline.
  10464. ;; Re-introduce one space in this case.
  10465. (unless (org-at-heading-p) (insert " "))
  10466. (when tags
  10467. (save-excursion (insert-and-inherit " " (org-make-tag-string tags)))
  10468. ;; When text is being inserted on an invisible region
  10469. ;; boundary, it can be inadvertently sucked into
  10470. ;; invisibility.
  10471. (unless (org-invisible-p (line-beginning-position))
  10472. (org-fold-region (point) (line-end-position) nil 'outline))))
  10473. ;; Align tags, if any.
  10474. (when tags (org-align-tags))
  10475. (when tags-change? (run-hooks 'org-after-tags-change-hook))))))
  10476. (defun org-change-tag-in-region (beg end tag off)
  10477. "Add or remove TAG for each entry in the region.
  10478. This works in the agenda, and also in an Org buffer."
  10479. (interactive
  10480. (list (region-beginning) (region-end)
  10481. (let ((org-last-tags-completion-table
  10482. (if (derived-mode-p 'org-mode)
  10483. (org--tag-add-to-alist
  10484. (org-get-buffer-tags)
  10485. (org-global-tags-completion-table))
  10486. (org-global-tags-completion-table))))
  10487. (completing-read
  10488. "Tag: " org-last-tags-completion-table nil nil nil
  10489. 'org-tags-history))
  10490. (progn
  10491. (message "[s]et or [r]emove? ")
  10492. (equal (read-char-exclusive) ?r))))
  10493. (deactivate-mark)
  10494. (let ((agendap (equal major-mode 'org-agenda-mode))
  10495. l1 l2 m buf pos newhead (cnt 0))
  10496. (goto-char end)
  10497. (setq l2 (1- (org-current-line)))
  10498. (goto-char beg)
  10499. (setq l1 (org-current-line))
  10500. (cl-loop for l from l1 to l2 do
  10501. (org-goto-line l)
  10502. (setq m (get-text-property (point) 'org-hd-marker))
  10503. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  10504. (and agendap m))
  10505. (setq buf (if agendap (marker-buffer m) (current-buffer))
  10506. pos (if agendap m (point)))
  10507. (with-current-buffer buf
  10508. (save-excursion
  10509. (save-restriction
  10510. (goto-char pos)
  10511. (setq cnt (1+ cnt))
  10512. (org-toggle-tag tag (if off 'off 'on))
  10513. (setq newhead (org-get-heading)))))
  10514. (and agendap (org-agenda-change-all-lines newhead m))))
  10515. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  10516. (defun org-tags-completion-function (string _predicate &optional flag)
  10517. "Complete tag STRING.
  10518. FLAG specifies the type of completion operation to perform. This
  10519. function is passed as a collection function to `completing-read',
  10520. which see."
  10521. (let ((completion-ignore-case nil) ;tags are case-sensitive
  10522. (confirm (lambda (x) (stringp (car x))))
  10523. (prefix ""))
  10524. (when (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  10525. (setq prefix (match-string 1 string))
  10526. (setq string (match-string 2 string)))
  10527. (pcase flag
  10528. (`t (all-completions string org-last-tags-completion-table confirm))
  10529. (`lambda (assoc string org-last-tags-completion-table)) ;exact match?
  10530. (`nil
  10531. (pcase (try-completion string org-last-tags-completion-table confirm)
  10532. ((and completion (pred stringp))
  10533. (concat prefix
  10534. completion
  10535. (if (and org-add-colon-after-tag-completion
  10536. (assoc completion org-last-tags-completion-table))
  10537. ":"
  10538. "")))
  10539. (completion completion)))
  10540. (_ nil))))
  10541. (defun org-fast-tag-insert (kwd tags face &optional end)
  10542. "Insert KWD, and the TAGS, the latter with face FACE.
  10543. Also insert END."
  10544. (insert (format "%-12s" (concat kwd ":"))
  10545. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  10546. (or end "")))
  10547. (defun org-fast-tag-show-exit (flag)
  10548. (save-excursion
  10549. (org-goto-line 3)
  10550. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  10551. (replace-match ""))
  10552. (when flag
  10553. (end-of-line 1)
  10554. (org-move-to-column (- (window-width) 19) t)
  10555. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  10556. (defun org-set-current-tags-overlay (current prefix)
  10557. "Add an overlay to CURRENT tag with PREFIX."
  10558. (let ((s (org-make-tag-string current)))
  10559. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  10560. (org-overlay-display org-tags-overlay (concat prefix s))))
  10561. (defvar org-last-tag-selection-key nil)
  10562. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  10563. "Fast tag selection with single keys.
  10564. CURRENT is the current list of tags in the headline, INHERITED is the
  10565. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  10566. possibly with grouping information. TODO-TABLE is a similar table with
  10567. TODO keywords, should these have keys assigned to them.
  10568. If the keys are nil, a-z are automatically assigned.
  10569. Returns the new tags string, or nil to not change the current settings."
  10570. (let* ((fulltable (append table todo-table))
  10571. (maxlen (if (null fulltable) 0
  10572. (apply #'max
  10573. (mapcar (lambda (x)
  10574. (if (stringp (car x)) (string-width (car x))
  10575. 0))
  10576. fulltable))))
  10577. (buf (current-buffer))
  10578. (expert (eq org-fast-tag-selection-single-key 'expert))
  10579. (tab-tags nil)
  10580. (fwidth (+ maxlen 3 1 3))
  10581. (ncol (/ (- (window-width) 4) fwidth))
  10582. (i-face 'org-done)
  10583. (c-face 'org-todo)
  10584. tg cnt e c char c1 c2 ntable tbl rtn
  10585. ov-start ov-end ov-prefix
  10586. (exit-after-next org-fast-tag-selection-single-key)
  10587. (done-keywords org-done-keywords)
  10588. groups ingroup intaggroup)
  10589. (save-excursion
  10590. (beginning-of-line)
  10591. (if (looking-at org-tag-line-re)
  10592. (setq ov-start (match-beginning 1)
  10593. ov-end (match-end 1)
  10594. ov-prefix "")
  10595. (setq ov-start (1- (point-at-eol))
  10596. ov-end (1+ ov-start))
  10597. (skip-chars-forward "^\n\r")
  10598. (setq ov-prefix
  10599. (concat
  10600. (buffer-substring (1- (point)) (point))
  10601. (if (> (current-column) org-tags-column)
  10602. " "
  10603. (make-string (- org-tags-column (current-column)) ?\ ))))))
  10604. (move-overlay org-tags-overlay ov-start ov-end)
  10605. (save-excursion
  10606. (save-window-excursion
  10607. (if expert
  10608. (set-buffer (get-buffer-create " *Org tags*"))
  10609. (delete-other-windows)
  10610. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  10611. (org-switch-to-buffer-other-window " *Org tags*"))
  10612. (erase-buffer)
  10613. (setq-local org-done-keywords done-keywords)
  10614. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  10615. (org-fast-tag-insert "Current" current c-face "\n\n")
  10616. (org-fast-tag-show-exit exit-after-next)
  10617. (org-set-current-tags-overlay current ov-prefix)
  10618. (setq tbl fulltable char ?a cnt 0)
  10619. (while (setq e (pop tbl))
  10620. (cond
  10621. ((eq (car e) :startgroup)
  10622. (push '() groups) (setq ingroup t)
  10623. (unless (zerop cnt)
  10624. (setq cnt 0)
  10625. (insert "\n"))
  10626. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  10627. ((eq (car e) :endgroup)
  10628. (setq ingroup nil cnt 0)
  10629. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  10630. ((eq (car e) :startgrouptag)
  10631. (setq intaggroup t)
  10632. (unless (zerop cnt)
  10633. (setq cnt 0)
  10634. (insert "\n"))
  10635. (insert "[ "))
  10636. ((eq (car e) :endgrouptag)
  10637. (setq intaggroup nil cnt 0)
  10638. (insert "]\n"))
  10639. ((equal e '(:newline))
  10640. (unless (zerop cnt)
  10641. (setq cnt 0)
  10642. (insert "\n")
  10643. (setq e (car tbl))
  10644. (while (equal (car tbl) '(:newline))
  10645. (insert "\n")
  10646. (setq tbl (cdr tbl)))))
  10647. ((equal e '(:grouptags)) (insert " : "))
  10648. (t
  10649. (setq tg (copy-sequence (car e)) c2 nil)
  10650. (if (cdr e)
  10651. (setq c (cdr e))
  10652. ;; automatically assign a character.
  10653. (setq c1 (string-to-char
  10654. (downcase (substring
  10655. tg (if (= (string-to-char tg) ?@) 1 0)))))
  10656. (if (or (rassoc c1 ntable) (rassoc c1 table))
  10657. (while (or (rassoc char ntable) (rassoc char table))
  10658. (setq char (1+ char)))
  10659. (setq c2 c1))
  10660. (setq c (or c2 char)))
  10661. (when ingroup (push tg (car groups)))
  10662. (setq tg (org-add-props tg nil 'face
  10663. (cond
  10664. ((not (assoc tg table))
  10665. (org-get-todo-face tg))
  10666. ((member tg current) c-face)
  10667. ((member tg inherited) i-face))))
  10668. (when (equal (caar tbl) :grouptags)
  10669. (org-add-props tg nil 'face 'org-tag-group))
  10670. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  10671. (insert "[" c "] " tg (make-string
  10672. (- fwidth 4 (length tg)) ?\ ))
  10673. (push (cons tg c) ntable)
  10674. (when (= (cl-incf cnt) ncol)
  10675. (unless (memq (caar tbl) '(:endgroup :endgrouptag))
  10676. (insert "\n")
  10677. (when (or ingroup intaggroup) (insert " ")))
  10678. (setq cnt 0)))))
  10679. (setq ntable (nreverse ntable))
  10680. (insert "\n")
  10681. (goto-char (point-min))
  10682. (unless expert (org-fit-window-to-buffer))
  10683. (setq rtn
  10684. (catch 'exit
  10685. (while t
  10686. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  10687. (if (not groups) "no " "")
  10688. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  10689. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  10690. (setq org-last-tag-selection-key c)
  10691. (cond
  10692. ((= c ?\r) (throw 'exit t))
  10693. ((= c ?!)
  10694. (setq groups (not groups))
  10695. (goto-char (point-min))
  10696. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  10697. ((= c ?\C-c)
  10698. (if (not expert)
  10699. (org-fast-tag-show-exit
  10700. (setq exit-after-next (not exit-after-next)))
  10701. (setq expert nil)
  10702. (delete-other-windows)
  10703. (set-window-buffer (split-window-vertically) " *Org tags*")
  10704. (org-switch-to-buffer-other-window " *Org tags*")
  10705. (org-fit-window-to-buffer)))
  10706. ((or (= c ?\C-g)
  10707. (and (= c ?q) (not (rassoc c ntable))))
  10708. (delete-overlay org-tags-overlay)
  10709. (setq quit-flag t))
  10710. ((= c ?\ )
  10711. (setq current nil)
  10712. (when exit-after-next (setq exit-after-next 'now)))
  10713. ((= c ?\t)
  10714. (condition-case nil
  10715. (unless tab-tags
  10716. (setq tab-tags
  10717. (delq nil
  10718. (mapcar (lambda (x)
  10719. (let ((item (car-safe x)))
  10720. (and (stringp item)
  10721. (list item))))
  10722. (org--tag-add-to-alist
  10723. (with-current-buffer buf
  10724. (org-get-buffer-tags))
  10725. table))))))
  10726. (setq tg (completing-read "Tag: " tab-tags))
  10727. (when (string-match "\\S-" tg)
  10728. (cl-pushnew (list tg) tab-tags :test #'equal)
  10729. (if (member tg current)
  10730. (setq current (delete tg current))
  10731. (push tg current)))
  10732. (when exit-after-next (setq exit-after-next 'now)))
  10733. ((setq e (rassoc c todo-table) tg (car e))
  10734. (with-current-buffer buf
  10735. (save-excursion (org-todo tg)))
  10736. (when exit-after-next (setq exit-after-next 'now)))
  10737. ((setq e (rassoc c ntable) tg (car e))
  10738. (if (member tg current)
  10739. (setq current (delete tg current))
  10740. (cl-loop for g in groups do
  10741. (when (member tg g)
  10742. (dolist (x g) (setq current (delete x current)))))
  10743. (push tg current))
  10744. (when exit-after-next (setq exit-after-next 'now))))
  10745. ;; Create a sorted list
  10746. (setq current
  10747. (sort current
  10748. (lambda (a b)
  10749. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  10750. (when (eq exit-after-next 'now) (throw 'exit t))
  10751. (goto-char (point-min))
  10752. (beginning-of-line 2)
  10753. (delete-region (point) (point-at-eol))
  10754. (org-fast-tag-insert "Current" current c-face)
  10755. (org-set-current-tags-overlay current ov-prefix)
  10756. (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
  10757. (while (re-search-forward tag-re nil t)
  10758. (let ((tag (match-string 1)))
  10759. (add-text-properties
  10760. (match-beginning 1) (match-end 1)
  10761. (list 'face
  10762. (cond
  10763. ((member tag current) c-face)
  10764. ((member tag inherited) i-face)
  10765. (t 'default)))))))
  10766. (goto-char (point-min)))))
  10767. (delete-overlay org-tags-overlay)
  10768. (if rtn
  10769. (mapconcat 'identity current ":")
  10770. nil)))))
  10771. (defun org-make-tag-string (tags)
  10772. "Return string associated to TAGS.
  10773. TAGS is a list of strings."
  10774. (if (null tags) ""
  10775. (format ":%s:" (mapconcat #'identity tags ":"))))
  10776. (defun org--get-local-tags ()
  10777. "Return list of tags for the current headline.
  10778. Assume point is at the beginning of the headline."
  10779. (let* ((cached (and (org-element--cache-active-p) (org-element-at-point nil 'cached)))
  10780. (cached-tags (org-element-property :tags cached)))
  10781. (if cached
  10782. ;; If we do not explicitly copy the result, reference would
  10783. ;; be returned and cache element might be modified directly.
  10784. (mapcar #'copy-sequence cached-tags)
  10785. ;; Parse tags manually.
  10786. (and (looking-at org-tag-line-re)
  10787. (split-string (match-string-no-properties 2) ":" t)))))
  10788. (defun org-get-tags (&optional pos-or-element local)
  10789. "Get the list of tags specified in the current headline.
  10790. When argument POS-OR-ELEMENT is non-nil, retrieve tags for headline at
  10791. POS.
  10792. According to `org-use-tag-inheritance', tags may be inherited
  10793. from parent headlines, and from the whole document, through
  10794. `org-file-tags'. In this case, the returned list of tags
  10795. contains tags in this order: file tags, tags inherited from
  10796. parent headlines, local tags. If a tag appears multiple times,
  10797. only the most local tag is returned.
  10798. However, when optional argument LOCAL is non-nil, only return
  10799. tags specified at the headline.
  10800. Inherited tags have the `inherited' text property."
  10801. (save-match-data
  10802. (if (and org-trust-scanner-tags
  10803. (or (not pos-or-element) (eq pos-or-element (point)))
  10804. (not local))
  10805. org-scanner-tags
  10806. (org-with-point-at (unless (org-element-type pos-or-element)
  10807. (or pos-or-element (point)))
  10808. (unless (or (org-element-type pos-or-element)
  10809. (org-before-first-heading-p))
  10810. (org-back-to-heading t))
  10811. (let ((ltags (if (org-element-type pos-or-element)
  10812. (org-element-property :tags (org-element-lineage pos-or-element '(headline inlinetask) t))
  10813. (org--get-local-tags)))
  10814. itags)
  10815. (if (or local (not org-use-tag-inheritance)) ltags
  10816. (let ((cached (and (org-element--cache-active-p)
  10817. (if (org-element-type pos-or-element)
  10818. (org-element-lineage pos-or-element '(headline org-data inlinetask) t)
  10819. (org-element-at-point nil 'cached)))))
  10820. (if cached
  10821. (while (setq cached (org-element-property :parent cached))
  10822. (setq itags (nconc (mapcar #'org-add-prop-inherited
  10823. ;; If we do explicitly copy the result, reference would
  10824. ;; be returned and cache element might be modified directly.
  10825. (mapcar #'copy-sequence (org-element-property :tags cached)))
  10826. itags)))
  10827. (while (org-up-heading-safe)
  10828. (setq itags (nconc (mapcar #'org-add-prop-inherited
  10829. (org--get-local-tags))
  10830. itags)))))
  10831. (setq itags (append org-file-tags itags))
  10832. (nreverse
  10833. (delete-dups
  10834. (nreverse (nconc (org-remove-uninherited-tags itags) ltags))))))))))
  10835. (defun org-get-buffer-tags ()
  10836. "Get a table of all tags used in the buffer, for completion."
  10837. (if (org-element--cache-active-p)
  10838. ;; `org-element-cache-map' is about 2x faster compared to regexp
  10839. ;; search.
  10840. (let ((hashed (make-hash-table :test #'equal)))
  10841. (org-element-cache-map
  10842. (lambda (el)
  10843. (dolist (tag (org-element-property :tags el))
  10844. (puthash (list tag) t hashed))))
  10845. (dolist (tag org-file-tags) (puthash (list tag) t hashed))
  10846. (hash-table-keys hashed))
  10847. (org-with-point-at 1
  10848. (let (tags)
  10849. (while (re-search-forward org-tag-line-re nil t)
  10850. (setq tags (nconc (split-string (match-string-no-properties 2) ":")
  10851. tags)))
  10852. (mapcar #'list (delete-dups (append org-file-tags tags)))))))
  10853. ;;;; The mapping API
  10854. (defvar org-agenda-skip-comment-trees)
  10855. (defvar org-agenda-skip-function)
  10856. (defun org-map-entries (func &optional match scope &rest skip)
  10857. "Call FUNC at each headline selected by MATCH in SCOPE.
  10858. FUNC is a function or a Lisp form. The function will be called without
  10859. arguments, with the cursor positioned at the beginning of the headline.
  10860. The return values of all calls to the function will be collected and
  10861. returned as a list.
  10862. The call to FUNC will be wrapped into a `save-excursion' form, so FUNC
  10863. does not need to preserve point. After evaluation, the cursor will be
  10864. moved to the end of the line (presumably of the headline of the
  10865. processed entry) and search continues from there. Under some
  10866. circumstances, this may not produce the wanted results. For example,
  10867. if you have removed (e.g. archived) the current (sub)tree it could
  10868. mean that the next entry will be skipped entirely. In such cases, you
  10869. can specify the position from where search should continue by making
  10870. FUNC set the variable `org-map-continue-from' to the desired buffer
  10871. position.
  10872. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  10873. Only headlines that are matched by this query will be considered during
  10874. the iteration. When MATCH is nil or t, all headlines will be
  10875. visited by the iteration.
  10876. SCOPE determines the scope of this command. It can be any of:
  10877. nil The current buffer, respecting the restriction if any
  10878. tree The subtree started with the entry at point
  10879. region The entries within the active region, if any
  10880. region-start-level
  10881. The entries within the active region, but only those at
  10882. the same level than the first one.
  10883. file The current buffer, without restriction
  10884. file-with-archives
  10885. The current buffer, and any archives associated with it
  10886. agenda All agenda files
  10887. agenda-with-archives
  10888. All agenda files with any archive files associated with them
  10889. \(file1 file2 ...)
  10890. If this is a list, all files in the list will be scanned
  10891. The remaining args are treated as settings for the skipping facilities of
  10892. the scanner. The following items can be given here:
  10893. archive skip trees with the archive tag
  10894. comment skip trees with the COMMENT keyword
  10895. function or Emacs Lisp form:
  10896. will be used as value for `org-agenda-skip-function', so
  10897. whenever the function returns a position, FUNC will not be
  10898. called for that entry and search will continue from the
  10899. position returned
  10900. If your function needs to retrieve the tags including inherited tags
  10901. at the *current* entry, you can use the value of the variable
  10902. `org-scanner-tags' which will be much faster than getting the value
  10903. with `org-get-tags'. If your function gets properties with
  10904. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  10905. to t around the call to `org-entry-properties' to get the same speedup.
  10906. Note that if your function moves around to retrieve tags and properties at
  10907. a *different* entry, you cannot use these techniques."
  10908. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  10909. (not (org-region-active-p)))
  10910. (let* ((org-agenda-archives-mode nil) ; just to make sure
  10911. (org-agenda-skip-archived-trees (memq 'archive skip))
  10912. (org-agenda-skip-comment-trees (memq 'comment skip))
  10913. (org-agenda-skip-function
  10914. (car (org-delete-all '(comment archive) skip)))
  10915. (org-tags-match-list-sublevels t)
  10916. (start-level (eq scope 'region-start-level))
  10917. matcher res
  10918. org-todo-keywords-for-agenda
  10919. org-done-keywords-for-agenda
  10920. org-todo-keyword-alist-for-agenda
  10921. org-tag-alist-for-agenda
  10922. org--matcher-tags-todo-only)
  10923. (cond
  10924. ((eq match t) (setq matcher t))
  10925. ((eq match nil) (setq matcher t))
  10926. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  10927. (save-excursion
  10928. (save-restriction
  10929. (cond ((eq scope 'tree)
  10930. (org-back-to-heading t)
  10931. (org-narrow-to-subtree)
  10932. (setq scope nil))
  10933. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  10934. (org-region-active-p))
  10935. ;; If needed, set start-level to a string like "2"
  10936. (when start-level
  10937. (save-excursion
  10938. (goto-char (region-beginning))
  10939. (unless (org-at-heading-p) (outline-next-heading))
  10940. (setq start-level (org-current-level))))
  10941. (narrow-to-region (region-beginning)
  10942. (save-excursion
  10943. (goto-char (region-end))
  10944. (unless (and (bolp) (org-at-heading-p))
  10945. (outline-next-heading))
  10946. (point)))
  10947. (setq scope nil)))
  10948. (if (not scope)
  10949. (progn
  10950. (org-agenda-prepare-buffers
  10951. (and buffer-file-name (list buffer-file-name)))
  10952. (setq res
  10953. (org-scan-tags
  10954. func matcher org--matcher-tags-todo-only start-level)))
  10955. ;; Get the right scope
  10956. (cond
  10957. ((and scope (listp scope) (symbolp (car scope)))
  10958. (setq scope (eval scope t)))
  10959. ((eq scope 'agenda)
  10960. (setq scope (org-agenda-files t)))
  10961. ((eq scope 'agenda-with-archives)
  10962. (setq scope (org-agenda-files t))
  10963. (setq scope (org-add-archive-files scope)))
  10964. ((eq scope 'file)
  10965. (setq scope (and buffer-file-name (list buffer-file-name))))
  10966. ((eq scope 'file-with-archives)
  10967. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  10968. (org-agenda-prepare-buffers scope)
  10969. (dolist (file scope)
  10970. (with-current-buffer (org-find-base-buffer-visiting file)
  10971. (org-with-wide-buffer
  10972. (goto-char (point-min))
  10973. (setq res
  10974. (append
  10975. res
  10976. (org-scan-tags
  10977. func matcher org--matcher-tags-todo-only)))))))))
  10978. res)))
  10979. ;;; Properties API
  10980. (defconst org-special-properties
  10981. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  10982. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  10983. "The special properties valid in Org mode.
  10984. These are properties that are not defined in the property drawer,
  10985. but in some other way.")
  10986. (defconst org-default-properties
  10987. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  10988. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  10989. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  10990. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  10991. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  10992. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  10993. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  10994. "Some properties that are used by Org mode for various purposes.
  10995. Being in this list makes sure that they are offered for completion.")
  10996. (defun org--valid-property-p (property)
  10997. "Non-nil when string PROPERTY is a valid property name."
  10998. (not
  10999. (or (equal property "")
  11000. (string-match-p "\\s-" property))))
  11001. (defun org--update-property-plist (key val props)
  11002. "Associate KEY to VAL in alist PROPS.
  11003. Modifications are made by side-effect. Return new alist."
  11004. (let* ((appending (string= (substring key -1) "+"))
  11005. (key (if appending (substring key 0 -1) key))
  11006. (old (assoc-string key props t)))
  11007. (if (not old) (cons (cons key val) props)
  11008. (setcdr old (if appending (concat (cdr old) " " val) val))
  11009. props)))
  11010. (defun org-get-property-block (&optional beg force)
  11011. "Return the (beg . end) range of the body of the property drawer.
  11012. BEG is the beginning of the current subtree or the beginning of
  11013. the document if before the first headline. If it is not given,
  11014. it will be found. If the drawer does not exist, create it if
  11015. FORCE is non-nil, or return nil."
  11016. (org-with-wide-buffer
  11017. (let ((beg (cond (beg (goto-char beg))
  11018. ((or (not (featurep 'org-inlinetask))
  11019. (org-inlinetask-in-task-p))
  11020. (org-back-to-heading-or-point-min t) (point))
  11021. (t (org-with-limited-levels
  11022. (org-back-to-heading-or-point-min t))
  11023. (point)))))
  11024. ;; Move point to its position according to its positional rules.
  11025. (cond ((org-before-first-heading-p)
  11026. (while (and (org-at-comment-p) (bolp)) (forward-line)))
  11027. (t (forward-line)
  11028. (when (looking-at-p org-planning-line-re) (forward-line))))
  11029. (cond ((looking-at org-property-drawer-re)
  11030. (forward-line)
  11031. (cons (point) (progn (goto-char (match-end 0))
  11032. (line-beginning-position))))
  11033. (force
  11034. (goto-char beg)
  11035. (org-insert-property-drawer)
  11036. (let ((pos (save-excursion (re-search-forward org-property-drawer-re)
  11037. (line-beginning-position))))
  11038. (cons pos pos)))))))
  11039. (defun org-at-property-drawer-p ()
  11040. "Non-nil when point is at the first line of a property drawer."
  11041. (org-with-wide-buffer
  11042. (beginning-of-line)
  11043. (and (looking-at org-property-drawer-re)
  11044. (or (bobp)
  11045. (progn
  11046. (forward-line -1)
  11047. (cond ((org-at-heading-p))
  11048. ((looking-at org-planning-line-re)
  11049. (forward-line -1)
  11050. (org-at-heading-p))
  11051. ((looking-at org-comment-regexp)
  11052. (forward-line -1)
  11053. (while (and (not (bobp)) (looking-at org-comment-regexp))
  11054. (forward-line -1))
  11055. (looking-at org-comment-regexp))
  11056. (t nil)))))))
  11057. (defun org-at-property-p ()
  11058. "Non-nil when point is inside a property drawer.
  11059. See `org-property-re' for match data, if applicable."
  11060. (save-excursion
  11061. (beginning-of-line)
  11062. (and (looking-at org-property-re)
  11063. (let ((property-drawer (save-match-data (org-get-property-block))))
  11064. (and property-drawer
  11065. (>= (point) (car property-drawer))
  11066. (< (point) (cdr property-drawer)))))))
  11067. (defun org-property-action ()
  11068. "Do an action on properties."
  11069. (interactive)
  11070. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  11071. (let ((c (read-char-exclusive)))
  11072. (cl-case c
  11073. (?s (call-interactively #'org-set-property))
  11074. (?d (call-interactively #'org-delete-property))
  11075. (?D (call-interactively #'org-delete-property-globally))
  11076. (?c (call-interactively #'org-compute-property-at-point))
  11077. (otherwise (user-error "No such property action %c" c)))))
  11078. (defun org-inc-effort ()
  11079. "Increment the value of the effort property in the current entry."
  11080. (interactive)
  11081. (org-set-effort t))
  11082. (defvar org-clock-effort) ; Defined in org-clock.el.
  11083. (defvar org-clock-current-task) ; Defined in org-clock.el.
  11084. (defun org-set-effort (&optional increment value)
  11085. "Set the effort property of the current entry.
  11086. If INCREMENT is non-nil, set the property to the next allowed
  11087. value. Otherwise, if optional argument VALUE is provided, use
  11088. it. Eventually, prompt for the new value if none of the previous
  11089. variables is set."
  11090. (interactive "P")
  11091. (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
  11092. (current (org-entry-get nil org-effort-property))
  11093. (value
  11094. (cond
  11095. (increment
  11096. (unless allowed (user-error "Allowed effort values are not set"))
  11097. (or (cl-caadr (member (list current) allowed))
  11098. (user-error "Unknown value %S among allowed values" current)))
  11099. (value
  11100. (if (stringp value) value
  11101. (error "Invalid effort value: %S" value)))
  11102. (t
  11103. (let ((must-match
  11104. (and allowed
  11105. (not (get-text-property 0 'org-unrestricted
  11106. (caar allowed))))))
  11107. (completing-read "Effort: " allowed nil must-match))))))
  11108. ;; Test whether the value can be interpreted as a duration before
  11109. ;; inserting it in the buffer:
  11110. (org-duration-to-minutes value)
  11111. ;; Maybe update the effort value:
  11112. (unless (equal current value)
  11113. (org-entry-put nil org-effort-property value))
  11114. (unless (org-element--cache-active-p)
  11115. (org-refresh-property '((effort . identity)
  11116. (effort-minutes . org-duration-to-minutes))
  11117. value))
  11118. (when (equal (org-get-heading t t t t)
  11119. (bound-and-true-p org-clock-current-task))
  11120. (setq org-clock-effort value)
  11121. (org-clock-update-mode-line))
  11122. (message "%s is now %s" org-effort-property value)))
  11123. (defun org-entry-properties (&optional pom which)
  11124. "Get all properties of the current entry.
  11125. When POM is a buffer position, get all properties from the entry
  11126. there instead.
  11127. This includes the TODO keyword, the tags, time strings for
  11128. deadline, scheduled, and clocking, and any additional properties
  11129. defined in the entry.
  11130. If WHICH is nil or `all', get all properties. If WHICH is
  11131. `special' or `standard', only get that subclass. If WHICH is
  11132. a string, only get that property.
  11133. Return value is an alist. Keys are properties, as upcased
  11134. strings."
  11135. (org-with-point-at pom
  11136. (when (and (derived-mode-p 'org-mode)
  11137. (org-back-to-heading-or-point-min t))
  11138. (catch 'exit
  11139. (let* ((beg (point))
  11140. (specific (and (stringp which) (upcase which)))
  11141. (which (cond ((not specific) which)
  11142. ((member specific org-special-properties) 'special)
  11143. (t 'standard)))
  11144. props)
  11145. ;; Get the special properties, like TODO and TAGS.
  11146. (when (memq which '(nil all special))
  11147. (when (or (not specific) (string= specific "CLOCKSUM"))
  11148. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  11149. (when clocksum
  11150. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  11151. props)))
  11152. (when specific (throw 'exit props)))
  11153. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  11154. (let ((clocksumt (get-text-property (point)
  11155. :org-clock-minutes-today)))
  11156. (when clocksumt
  11157. (push (cons "CLOCKSUM_T"
  11158. (org-duration-from-minutes clocksumt))
  11159. props)))
  11160. (when specific (throw 'exit props)))
  11161. (when (or (not specific) (string= specific "ITEM"))
  11162. (let ((case-fold-search nil))
  11163. (when (looking-at org-complex-heading-regexp)
  11164. (push (cons "ITEM"
  11165. (let ((title (match-string-no-properties 4)))
  11166. (if (org-string-nw-p title)
  11167. (org-remove-tabs title)
  11168. "")))
  11169. props)))
  11170. (when specific (throw 'exit props)))
  11171. (when (or (not specific) (string= specific "TODO"))
  11172. (let ((case-fold-search nil))
  11173. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  11174. (push (cons "TODO" (match-string-no-properties 2)) props)))
  11175. (when specific (throw 'exit props)))
  11176. (when (or (not specific) (string= specific "PRIORITY"))
  11177. (push (cons "PRIORITY"
  11178. (if (looking-at org-priority-regexp)
  11179. (match-string-no-properties 2)
  11180. (char-to-string org-priority-default)))
  11181. props)
  11182. (when specific (throw 'exit props)))
  11183. (when (or (not specific) (string= specific "FILE"))
  11184. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  11185. props)
  11186. (when specific (throw 'exit props)))
  11187. (when (or (not specific) (string= specific "TAGS"))
  11188. (let ((tags (org-get-tags nil t)))
  11189. (when tags
  11190. (push (cons "TAGS" (org-make-tag-string tags))
  11191. props)))
  11192. (when specific (throw 'exit props)))
  11193. (when (or (not specific) (string= specific "ALLTAGS"))
  11194. (let ((tags (org-get-tags)))
  11195. (when tags
  11196. (push (cons "ALLTAGS" (org-make-tag-string tags))
  11197. props)))
  11198. (when specific (throw 'exit props)))
  11199. (when (or (not specific) (string= specific "BLOCKED"))
  11200. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  11201. (when specific (throw 'exit props)))
  11202. (when (or (not specific)
  11203. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  11204. (forward-line)
  11205. (when (looking-at-p org-planning-line-re)
  11206. (end-of-line)
  11207. (let ((bol (line-beginning-position))
  11208. ;; Backward compatibility: time keywords used to
  11209. ;; be configurable (before 8.3). Make sure we
  11210. ;; get the correct keyword.
  11211. (key-assoc `(("CLOSED" . ,org-closed-string)
  11212. ("DEADLINE" . ,org-deadline-string)
  11213. ("SCHEDULED" . ,org-scheduled-string))))
  11214. (dolist (pair (if specific (list (assoc specific key-assoc))
  11215. key-assoc))
  11216. (save-excursion
  11217. (when (search-backward (cdr pair) bol t)
  11218. (goto-char (match-end 0))
  11219. (skip-chars-forward " \t")
  11220. (and (looking-at org-ts-regexp-both)
  11221. (push (cons (car pair)
  11222. (match-string-no-properties 0))
  11223. props)))))))
  11224. (when specific (throw 'exit props)))
  11225. (when (or (not specific)
  11226. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  11227. (let ((find-ts
  11228. (lambda (end ts)
  11229. ;; Fix next time-stamp before END. TS is the
  11230. ;; list of time-stamps found so far.
  11231. (let ((ts ts)
  11232. (regexp (cond
  11233. ((string= specific "TIMESTAMP")
  11234. org-ts-regexp)
  11235. ((string= specific "TIMESTAMP_IA")
  11236. org-ts-regexp-inactive)
  11237. ((assoc "TIMESTAMP_IA" ts)
  11238. org-ts-regexp)
  11239. ((assoc "TIMESTAMP" ts)
  11240. org-ts-regexp-inactive)
  11241. (t org-ts-regexp-both))))
  11242. (catch 'next
  11243. (while (re-search-forward regexp end t)
  11244. (backward-char)
  11245. (let ((object (org-element-context)))
  11246. ;; Accept to match timestamps in node
  11247. ;; properties, too.
  11248. (when (memq (org-element-type object)
  11249. '(node-property timestamp))
  11250. (let ((type
  11251. (org-element-property :type object)))
  11252. (cond
  11253. ((and (memq type '(active active-range))
  11254. (not (equal specific "TIMESTAMP_IA")))
  11255. (unless (assoc "TIMESTAMP" ts)
  11256. (push (cons "TIMESTAMP"
  11257. (org-element-property
  11258. :raw-value object))
  11259. ts)
  11260. (when specific (throw 'exit ts))))
  11261. ((and (memq type '(inactive inactive-range))
  11262. (not (string= specific "TIMESTAMP")))
  11263. (unless (assoc "TIMESTAMP_IA" ts)
  11264. (push (cons "TIMESTAMP_IA"
  11265. (org-element-property
  11266. :raw-value object))
  11267. ts)
  11268. (when specific (throw 'exit ts))))))
  11269. ;; Both timestamp types are found,
  11270. ;; move to next part.
  11271. (when (= (length ts) 2) (throw 'next ts)))))
  11272. ts)))))
  11273. (goto-char beg)
  11274. ;; First look for timestamps within headline.
  11275. (let ((ts (funcall find-ts (line-end-position) nil)))
  11276. (if (= (length ts) 2) (setq props (nconc ts props))
  11277. ;; Then find timestamps in the section, skipping
  11278. ;; planning line.
  11279. (let ((end (save-excursion (outline-next-heading))))
  11280. (forward-line)
  11281. (when (looking-at-p org-planning-line-re) (forward-line))
  11282. (setq props (nconc (funcall find-ts end ts) props))))))))
  11283. ;; Get the standard properties, like :PROP:.
  11284. (when (memq which '(nil all standard))
  11285. ;; If we are looking after a specific property, delegate
  11286. ;; to `org-entry-get', which is faster. However, make an
  11287. ;; exception for "CATEGORY", since it can be also set
  11288. ;; through keywords (i.e. #+CATEGORY).
  11289. (if (and specific (not (equal specific "CATEGORY")))
  11290. (let ((value (org-entry-get beg specific nil t)))
  11291. (throw 'exit (and value (list (cons specific value)))))
  11292. (let ((range (org-get-property-block beg)))
  11293. (when range
  11294. (let ((end (cdr range)) seen-base)
  11295. (goto-char (car range))
  11296. ;; Unlike to `org--update-property-plist', we
  11297. ;; handle the case where base values is found
  11298. ;; after its extension. We also forbid standard
  11299. ;; properties to be named as special properties.
  11300. (while (re-search-forward org-property-re end t)
  11301. (let* ((key (upcase (match-string-no-properties 2)))
  11302. (extendp (string-match-p "\\+\\'" key))
  11303. (key-base (if extendp (substring key 0 -1) key))
  11304. (value (match-string-no-properties 3)))
  11305. (cond
  11306. ((member-ignore-case key-base org-special-properties))
  11307. (extendp
  11308. (setq props
  11309. (org--update-property-plist key value props)))
  11310. ((member key seen-base))
  11311. (t (push key seen-base)
  11312. (let ((p (assoc-string key props t)))
  11313. (if p (setcdr p (concat value " " (cdr p)))
  11314. (push (cons key value) props))))))))))))
  11315. (unless (assoc "CATEGORY" props)
  11316. (push (cons "CATEGORY" (org-get-category beg)) props)
  11317. (when (string= specific "CATEGORY") (throw 'exit props)))
  11318. ;; Return value.
  11319. props)))))
  11320. (defun org--property-local-values (property literal-nil &optional element)
  11321. "Return value for PROPERTY in current entry or ELEMENT.
  11322. Value is a list whose car is the base value for PROPERTY and cdr
  11323. a list of accumulated values. Return nil if neither is found in
  11324. the entry. Also return nil when PROPERTY is set to \"nil\",
  11325. unless LITERAL-NIL is non-nil."
  11326. (let ((element (or element
  11327. (and (org-element--cache-active-p)
  11328. (org-element-at-point nil 'cached)))))
  11329. (if element
  11330. (let* ((element (org-element-lineage element '(headline org-data inlinetask) 'with-self))
  11331. (base-value (org-element-property (intern (concat ":" (upcase property))) element))
  11332. (base-value (if literal-nil base-value (org-not-nil base-value)))
  11333. (extra-value (org-element-property (intern (concat ":" (upcase property) "+")) element))
  11334. (extra-value (if (listp extra-value) extra-value (list extra-value)))
  11335. (value (cons base-value extra-value)))
  11336. (and (not (equal value '(nil))) value))
  11337. (let ((range (org-get-property-block)))
  11338. (when range
  11339. (goto-char (car range))
  11340. (let* ((case-fold-search t)
  11341. (end (cdr range))
  11342. (value
  11343. ;; Base value.
  11344. (save-excursion
  11345. (let ((v (and (re-search-forward
  11346. (org-re-property property nil t) end t)
  11347. (match-string-no-properties 3))))
  11348. (list (if literal-nil v (org-not-nil v)))))))
  11349. ;; Find additional values.
  11350. (let* ((property+ (org-re-property (concat property "+") nil t)))
  11351. (while (re-search-forward property+ end t)
  11352. (push (match-string-no-properties 3) value)))
  11353. ;; Return final values.
  11354. (and (not (equal value '(nil))) (nreverse value))))))))
  11355. (defun org--property-global-or-keyword-value (property literal-nil)
  11356. "Return value for PROPERTY as defined by global properties or by keyword.
  11357. Return value is a string. Return nil if property is not set
  11358. globally or by keyword. Also return nil when PROPERTY is set to
  11359. \"nil\", unless LITERAL-NIL is non-nil."
  11360. (let ((global
  11361. (cdr (or (assoc-string property org-keyword-properties t)
  11362. (assoc-string property org-global-properties t)
  11363. (assoc-string property org-global-properties-fixed t)))))
  11364. (if literal-nil global (org-not-nil global))))
  11365. (defun org-entry-get (pom property &optional inherit literal-nil)
  11366. "Get value of PROPERTY for entry or content at point-or-marker POM.
  11367. If INHERIT is non-nil and the entry does not have the property,
  11368. then also check higher levels of the hierarchy. If INHERIT is
  11369. the symbol `selective', use inheritance only if the setting in
  11370. `org-use-property-inheritance' selects PROPERTY for inheritance.
  11371. If the property is present but empty, the return value is the
  11372. empty string. If the property is not present at all, nil is
  11373. returned. In any other case, return the value as a string.
  11374. Search is case-insensitive.
  11375. If LITERAL-NIL is set, return the string value \"nil\" as
  11376. a string, do not interpret it as the list atom nil. This is used
  11377. for inheritance when a \"nil\" value can supersede a non-nil
  11378. value higher up the hierarchy."
  11379. (org-with-point-at pom
  11380. (cond
  11381. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  11382. ;; We need a special property. Use `org-entry-properties' to
  11383. ;; retrieve it, but specify the wanted property.
  11384. (cdr (assoc-string property (org-entry-properties nil property))))
  11385. ((and inherit
  11386. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  11387. (org-entry-get-with-inheritance property literal-nil))
  11388. (t
  11389. (let* ((local (org--property-local-values property literal-nil))
  11390. (value (and local (mapconcat #'identity
  11391. (delq nil local)
  11392. (org--property-get-separator property)))))
  11393. (if literal-nil value (org-not-nil value)))))))
  11394. (defun org-property-or-variable-value (var &optional inherit)
  11395. "Check if there is a property fixing the value of VAR.
  11396. If yes, return this value. If not, return the current value of the variable."
  11397. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  11398. (if (and prop (stringp prop) (string-match "\\S-" prop))
  11399. (read prop)
  11400. (symbol-value var))))
  11401. (defun org-entry-delete (pom property)
  11402. "Delete PROPERTY from entry at point-or-marker POM.
  11403. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  11404. non-nil when a property was removed."
  11405. (org-with-point-at pom
  11406. (pcase (org-get-property-block)
  11407. (`(,begin . ,origin)
  11408. (let* ((end (copy-marker origin))
  11409. (re (org-re-property
  11410. (concat (regexp-quote property) "\\+?") t t)))
  11411. (goto-char begin)
  11412. (while (re-search-forward re end t)
  11413. (delete-region (match-beginning 0) (line-beginning-position 2)))
  11414. ;; If drawer is empty, remove it altogether.
  11415. (when (= begin end)
  11416. (delete-region (line-beginning-position 0)
  11417. (line-beginning-position 2)))
  11418. ;; Return non-nil if some property was removed.
  11419. (prog1 (/= end origin) (set-marker end nil))))
  11420. (_ nil))))
  11421. ;; Multi-values properties are properties that contain multiple values
  11422. ;; These values are assumed to be single words, separated by whitespace.
  11423. (defun org-entry-add-to-multivalued-property (pom property value)
  11424. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  11425. (let* ((old (org-entry-get pom property))
  11426. (values (and old (split-string old))))
  11427. (setq value (org-entry-protect-space value))
  11428. (unless (member value values)
  11429. (setq values (append values (list value)))
  11430. (org-entry-put pom property (mapconcat #'identity values " ")))))
  11431. (defun org-entry-remove-from-multivalued-property (pom property value)
  11432. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  11433. (let* ((old (org-entry-get pom property))
  11434. (values (and old (split-string old))))
  11435. (setq value (org-entry-protect-space value))
  11436. (when (member value values)
  11437. (setq values (delete value values))
  11438. (org-entry-put pom property (mapconcat #'identity values " ")))))
  11439. (defun org-entry-member-in-multivalued-property (pom property value)
  11440. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  11441. (let* ((old (org-entry-get pom property))
  11442. (values (and old (split-string old))))
  11443. (setq value (org-entry-protect-space value))
  11444. (member value values)))
  11445. (defun org-entry-get-multivalued-property (pom property)
  11446. "Return a list of values in a multivalued property."
  11447. (let* ((value (org-entry-get pom property))
  11448. (values (and value (split-string value))))
  11449. (mapcar #'org-entry-restore-space values)))
  11450. (defun org-entry-put-multivalued-property (pom property &rest values)
  11451. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  11452. VALUES should be a list of strings. Spaces will be protected."
  11453. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  11454. (let* ((value (org-entry-get pom property))
  11455. (values (and value (split-string value))))
  11456. (mapcar #'org-entry-restore-space values)))
  11457. (defun org-entry-protect-space (s)
  11458. "Protect spaces and newline in string S."
  11459. (while (string-match " " s)
  11460. (setq s (replace-match "%20" t t s)))
  11461. (while (string-match "\n" s)
  11462. (setq s (replace-match "%0A" t t s)))
  11463. s)
  11464. (defun org-entry-restore-space (s)
  11465. "Restore spaces and newline in string S."
  11466. (while (string-match "%20" s)
  11467. (setq s (replace-match " " t t s)))
  11468. (while (string-match "%0A" s)
  11469. (setq s (replace-match "\n" t t s)))
  11470. s)
  11471. (defvar org-entry-property-inherited-from (make-marker)
  11472. "Marker pointing to the entry from where a property was inherited.
  11473. Each call to `org-entry-get-with-inheritance' will set this marker to the
  11474. location of the entry where the inheritance search matched. If there was
  11475. no match, the marker will point nowhere.
  11476. Note that also `org-entry-get' calls this function, if the INHERIT flag
  11477. is set.")
  11478. (defun org-entry-get-with-inheritance (property &optional literal-nil element)
  11479. "Get PROPERTY of entry or content at point, search higher levels if needed.
  11480. The search will stop at the first ancestor which has the property defined.
  11481. If the value found is \"nil\", return nil to show that the property
  11482. should be considered as undefined (this is the meaning of nil here).
  11483. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  11484. (move-marker org-entry-property-inherited-from nil)
  11485. (org-with-wide-buffer
  11486. (let (value at-bob-no-heading)
  11487. (catch 'exit
  11488. (let ((element (or element
  11489. (and (org-element--cache-active-p)
  11490. (org-element-at-point nil 'cached))))
  11491. (separator (org--property-get-separator property)))
  11492. (if element
  11493. (let ((element (org-element-lineage element '(headline org-data inlinetask) 'with-self)))
  11494. (while t
  11495. (let* ((v (org--property-local-values property literal-nil element))
  11496. (v (if (listp v) v (list v))))
  11497. (when v
  11498. (setq value
  11499. (concat (mapconcat #'identity (delq nil v) separator)
  11500. (and value separator)
  11501. value)))
  11502. (cond
  11503. ((car v)
  11504. (move-marker org-entry-property-inherited-from (org-element-property :begin element))
  11505. (throw 'exit nil))
  11506. ((org-element-property :parent element)
  11507. (setq element (org-element-property :parent element)))
  11508. (t
  11509. (let ((global (org--property-global-or-keyword-value property literal-nil)))
  11510. (cond ((not global))
  11511. (value (setq value (concat global separator value)))
  11512. (t (setq value global))))
  11513. (throw 'exit nil))))))
  11514. (while t
  11515. (let ((v (org--property-local-values property literal-nil)))
  11516. (when v
  11517. (setq value
  11518. (concat (mapconcat #'identity (delq nil v) separator)
  11519. (and value separator)
  11520. value)))
  11521. (cond
  11522. ((car v)
  11523. (org-back-to-heading-or-point-min t)
  11524. (move-marker org-entry-property-inherited-from (point))
  11525. (throw 'exit nil))
  11526. ((or (org-up-heading-safe)
  11527. (and (not (bobp))
  11528. (goto-char (point-min))
  11529. nil)
  11530. ;; `org-up-heading-safe' returned nil. We are at low
  11531. ;; level heading or bob. If there is headline
  11532. ;; there, do not try to fetch its properties.
  11533. (and (bobp)
  11534. (not at-bob-no-heading)
  11535. (not (org-at-heading-p))
  11536. (setq at-bob-no-heading t))))
  11537. (t
  11538. (let ((global (org--property-global-or-keyword-value property literal-nil)))
  11539. (cond ((not global))
  11540. (value (setq value (concat global separator value)))
  11541. (t (setq value global))))
  11542. (throw 'exit nil))))))))
  11543. (if literal-nil value (org-not-nil value)))))
  11544. (defvar org-property-changed-functions nil
  11545. "Hook called when the value of a property has changed.
  11546. Each hook function should accept two arguments, the name of the property
  11547. and the new value.")
  11548. (defun org-entry-put (pom property value)
  11549. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  11550. If the value is nil, it is converted to the empty string. If it
  11551. is not a string, an error is raised. Also raise an error on
  11552. invalid property names.
  11553. PROPERTY can be any regular property (see
  11554. `org-special-properties'). It can also be \"TODO\",
  11555. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  11556. For the last two properties, VALUE may have any of the special
  11557. values \"earlier\" and \"later\". The function then increases or
  11558. decreases scheduled or deadline date by one day."
  11559. (cond ((null value) (setq value ""))
  11560. ((not (stringp value)) (error "Properties values should be strings"))
  11561. ((not (org--valid-property-p property))
  11562. (user-error "Invalid property name: \"%s\"" property)))
  11563. (org-no-read-only
  11564. (org-with-point-at pom
  11565. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  11566. (org-back-to-heading-or-point-min t)
  11567. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  11568. (let ((beg (point)))
  11569. (cond
  11570. ((equal property "TODO")
  11571. (cond ((not (org-string-nw-p value)) (setq value 'none))
  11572. ((not (member value org-todo-keywords-1))
  11573. (user-error "\"%s\" is not a valid TODO state" value)))
  11574. (org-todo value)
  11575. (org-align-tags))
  11576. ((equal property "PRIORITY")
  11577. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  11578. (org-align-tags))
  11579. ((equal property "SCHEDULED")
  11580. (forward-line)
  11581. (if (and (looking-at-p org-planning-line-re)
  11582. (re-search-forward
  11583. org-scheduled-time-regexp (line-end-position) t))
  11584. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  11585. ((string= value "later") (org-timestamp-change 1 'day))
  11586. ((string= value "") (org-schedule '(4)))
  11587. (t (org-schedule nil value)))
  11588. (if (member value '("earlier" "later" ""))
  11589. (call-interactively #'org-schedule)
  11590. (org-schedule nil value))))
  11591. ((equal property "DEADLINE")
  11592. (forward-line)
  11593. (if (and (looking-at-p org-planning-line-re)
  11594. (re-search-forward
  11595. org-deadline-time-regexp (line-end-position) t))
  11596. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  11597. ((string= value "later") (org-timestamp-change 1 'day))
  11598. ((string= value "") (org-deadline '(4)))
  11599. (t (org-deadline nil value)))
  11600. (if (member value '("earlier" "later" ""))
  11601. (call-interactively #'org-deadline)
  11602. (org-deadline nil value))))
  11603. ((member property org-special-properties)
  11604. (error "The %s property cannot be set with `org-entry-put'" property))
  11605. (t
  11606. (org-fold-core-ignore-modifications
  11607. (let* ((range (org-get-property-block beg 'force))
  11608. (end (cdr range))
  11609. (case-fold-search t))
  11610. (goto-char (car range))
  11611. (if (re-search-forward (org-re-property property nil t) end t)
  11612. (progn (delete-region (match-beginning 0) (match-end 0))
  11613. (goto-char (match-beginning 0)))
  11614. (goto-char end)
  11615. (insert-and-inherit "\n")
  11616. (backward-char))
  11617. (insert-and-inherit ":" property ":")
  11618. (when value (insert-and-inherit " " value))
  11619. (org-indent-line))))))
  11620. (run-hook-with-args 'org-property-changed-functions property value))))
  11621. (defun org-buffer-property-keys (&optional specials defaults columns)
  11622. "Get all property keys in the current buffer.
  11623. When SPECIALS is non-nil, also list the special properties that
  11624. reflect things like tags and TODO state.
  11625. When DEFAULTS is non-nil, also include properties that has
  11626. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  11627. DESCRIPTION, LOCATION, and LOGGING and others.
  11628. When COLUMNS in non-nil, also include property names given in
  11629. COLUMN formats in the current buffer."
  11630. (let ((case-fold-search t)
  11631. (props (append
  11632. (and specials org-special-properties)
  11633. (and defaults (cons org-effort-property org-default-properties))
  11634. ;; Get property names from #+PROPERTY keywords as well
  11635. (mapcar (lambda (s)
  11636. (nth 0 (split-string s)))
  11637. (cdar (org-collect-keywords '("PROPERTY")))))))
  11638. (org-with-wide-buffer
  11639. (goto-char (point-min))
  11640. (while (re-search-forward org-property-start-re nil t)
  11641. (catch :skip
  11642. (let ((range (org-get-property-block)))
  11643. (unless range (throw :skip nil))
  11644. (goto-char (car range))
  11645. (let ((begin (car range))
  11646. (end (cdr range)))
  11647. ;; Make sure that found property block is not located
  11648. ;; before current point, as it would generate an infloop.
  11649. ;; It can happen, for example, in the following
  11650. ;; situation:
  11651. ;;
  11652. ;; * Headline
  11653. ;; :PROPERTIES:
  11654. ;; ...
  11655. ;; :END:
  11656. ;; *************** Inlinetask
  11657. ;; #+BEGIN_EXAMPLE
  11658. ;; :PROPERTIES:
  11659. ;; #+END_EXAMPLE
  11660. ;;
  11661. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  11662. (while (< (point) end)
  11663. (let ((p (progn (looking-at org-property-re)
  11664. (match-string-no-properties 2))))
  11665. ;; Only add true property name, not extension symbol.
  11666. (push (if (not (string-match-p "\\+\\'" p)) p
  11667. (substring p 0 -1))
  11668. props))
  11669. (forward-line))))
  11670. (outline-next-heading)))
  11671. (when columns
  11672. (goto-char (point-min))
  11673. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  11674. (let ((element (org-element-at-point)))
  11675. (when (memq (org-element-type element) '(keyword node-property))
  11676. (let ((value (org-element-property :value element))
  11677. (start 0))
  11678. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  11679. \\(?:{[^}]+}\\)?"
  11680. value start)
  11681. (setq start (match-end 0))
  11682. (let ((p (match-string-no-properties 1 value)))
  11683. (unless (member-ignore-case p org-special-properties)
  11684. (push p props))))))))))
  11685. (sort (delete-dups
  11686. (append props
  11687. ;; for each xxx_ALL property, make sure the bare
  11688. ;; xxx property is also included
  11689. (delq nil (mapcar (lambda (p)
  11690. (and (string-match-p "._ALL\\'" p)
  11691. (substring p 0 -4)))
  11692. props))))
  11693. (lambda (a b) (string< (upcase a) (upcase b))))))
  11694. (defun org-property-values (key)
  11695. "List all non-nil values of property KEY in current buffer."
  11696. (org-with-wide-buffer
  11697. (goto-char (point-min))
  11698. (let ((case-fold-search t)
  11699. (re (org-re-property key))
  11700. values)
  11701. (while (re-search-forward re nil t)
  11702. (push (org-entry-get (point) key) values))
  11703. (delete-dups values))))
  11704. (defun org-insert-property-drawer ()
  11705. "Insert a property drawer into the current entry.
  11706. Do nothing if the drawer already exists. The newly created
  11707. drawer is immediately hidden."
  11708. (org-with-wide-buffer
  11709. ;; Set point to the position where the drawer should be inserted.
  11710. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  11711. (org-back-to-heading-or-point-min t)
  11712. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  11713. (if (org-before-first-heading-p)
  11714. (while (and (org-at-comment-p) (bolp)) (forward-line))
  11715. (forward-line)
  11716. (when (looking-at-p org-planning-line-re) (forward-line)))
  11717. (unless (looking-at-p org-property-drawer-re)
  11718. ;; Make sure we start editing a line from current entry, not from
  11719. ;; next one. It prevents extending text properties or overlays
  11720. ;; belonging to the latter.
  11721. (when (and (bolp) (> (point) (point-min))) (backward-char))
  11722. (let ((begin (if (bobp) (point) (1+ (point))))
  11723. (inhibit-read-only t))
  11724. (unless (bobp) (insert "\n"))
  11725. (insert ":PROPERTIES:\n:END:")
  11726. (org-fold-region (line-end-position 0) (point) t (if (eq org-fold-core-style 'text-properties) 'drawer 'outline))
  11727. (when (or (eobp) (= begin (point-min))) (insert "\n"))
  11728. (org-indent-region begin (point))))))
  11729. (defun org-insert-drawer (&optional arg drawer)
  11730. "Insert a drawer at point.
  11731. When optional argument ARG is non-nil, insert a property drawer.
  11732. Optional argument DRAWER, when non-nil, is a string representing
  11733. drawer's name. Otherwise, the user is prompted for a name.
  11734. If a region is active, insert the drawer around that region
  11735. instead.
  11736. Point is left between drawer's boundaries."
  11737. (interactive "P")
  11738. (let* ((drawer (if arg "PROPERTIES"
  11739. (or drawer (read-from-minibuffer "Drawer: ")))))
  11740. (cond
  11741. ;; With C-u, fall back on `org-insert-property-drawer'
  11742. (arg (org-insert-property-drawer))
  11743. ;; Check validity of suggested drawer's name.
  11744. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  11745. (user-error "Invalid drawer name"))
  11746. ;; With an active region, insert a drawer at point.
  11747. ((not (org-region-active-p))
  11748. (progn
  11749. (unless (bolp) (insert "\n"))
  11750. (insert (format ":%s:\n\n:END:\n" drawer))
  11751. (forward-line -2)))
  11752. ;; Otherwise, insert the drawer at point
  11753. (t
  11754. (let ((rbeg (region-beginning))
  11755. (rend (copy-marker (region-end))))
  11756. (unwind-protect
  11757. (progn
  11758. (goto-char rbeg)
  11759. (beginning-of-line)
  11760. (when (save-excursion
  11761. (re-search-forward org-outline-regexp-bol rend t))
  11762. (user-error "Drawers cannot contain headlines"))
  11763. ;; Position point at the beginning of the first
  11764. ;; non-blank line in region. Insert drawer's opening
  11765. ;; there, then indent it.
  11766. (org-skip-whitespace)
  11767. (beginning-of-line)
  11768. (insert ":" drawer ":\n")
  11769. (forward-line -1)
  11770. (indent-for-tab-command)
  11771. ;; Move point to the beginning of the first blank line
  11772. ;; after the last non-blank line in region. Insert
  11773. ;; drawer's closing, then indent it.
  11774. (goto-char rend)
  11775. (skip-chars-backward " \r\t\n")
  11776. (insert "\n:END:")
  11777. (deactivate-mark t)
  11778. (indent-for-tab-command)
  11779. (unless (eolp) (insert "\n")))
  11780. ;; Clear marker, whatever the outcome of insertion is.
  11781. (set-marker rend nil)))))))
  11782. (defvar org-property-set-functions-alist nil
  11783. "Property set function alist.
  11784. Each entry should have the following format:
  11785. (PROPERTY . READ-FUNCTION)
  11786. The read function will be called with the same argument as
  11787. `org-completing-read'.")
  11788. (defun org-set-property-function (property)
  11789. "Get the function that should be used to set PROPERTY.
  11790. This is computed according to `org-property-set-functions-alist'."
  11791. (or (cdr (assoc property org-property-set-functions-alist))
  11792. 'org-completing-read))
  11793. (defun org-read-property-value (property &optional pom default)
  11794. "Read value for PROPERTY, as a string.
  11795. When optional argument POM is non-nil, completion uses additional
  11796. information, i.e., allowed or existing values at point or marker
  11797. POM.
  11798. Optional argument DEFAULT provides a default value for PROPERTY."
  11799. (let* ((completion-ignore-case t)
  11800. (allowed
  11801. (or (org-property-get-allowed-values nil property 'table)
  11802. (and pom (org-property-get-allowed-values pom property 'table))))
  11803. (current (org-entry-get nil property))
  11804. (prompt (format "%s value%s: "
  11805. property
  11806. (if (org-string-nw-p current)
  11807. (format " [%s]" current)
  11808. "")))
  11809. (set-function (org-set-property-function property)))
  11810. (org-trim
  11811. (if allowed
  11812. (funcall set-function
  11813. prompt allowed nil
  11814. (not (get-text-property 0 'org-unrestricted (caar allowed)))
  11815. default nil default)
  11816. (let ((all (mapcar #'list
  11817. (append (org-property-values property)
  11818. (and pom
  11819. (org-with-point-at pom
  11820. (org-property-values property)))))))
  11821. (funcall set-function prompt all nil nil "" nil current))))))
  11822. (defvar org-last-set-property nil)
  11823. (defvar org-last-set-property-value nil)
  11824. (defun org-read-property-name ()
  11825. "Read a property name."
  11826. (let ((completion-ignore-case t)
  11827. (default-prop (or (and (org-at-property-p)
  11828. (match-string-no-properties 2))
  11829. org-last-set-property)))
  11830. (org-completing-read
  11831. (concat "Property"
  11832. (if default-prop (concat " [" default-prop "]") "")
  11833. ": ")
  11834. (mapcar #'list (org-buffer-property-keys nil t t))
  11835. nil nil nil nil default-prop)))
  11836. (defun org-set-property-and-value (use-last)
  11837. "Allow to set [PROPERTY]: [value] direction from prompt.
  11838. When use-default, don't even ask, just use the last
  11839. \"[PROPERTY]: [value]\" string from the history."
  11840. (interactive "P")
  11841. (let* ((completion-ignore-case t)
  11842. (pv (or (and use-last org-last-set-property-value)
  11843. (org-completing-read
  11844. "Enter a \"[Property]: [value]\" pair: "
  11845. nil nil nil nil nil
  11846. org-last-set-property-value)))
  11847. prop val)
  11848. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  11849. (setq prop (match-string 1 pv)
  11850. val (match-string 2 pv))
  11851. (org-set-property prop val))))
  11852. (defun org-set-property (property value)
  11853. "In the current entry, set PROPERTY to VALUE.
  11854. When called interactively, this will prompt for a property name, offering
  11855. completion on existing and default properties. And then it will prompt
  11856. for a value, offering completion either on allowed values (via an inherited
  11857. xxx_ALL property) or on existing values in other instances of this property
  11858. in the current file.
  11859. Throw an error when trying to set a property with an invalid name."
  11860. (interactive (list nil nil))
  11861. (let ((property (or property (org-read-property-name))))
  11862. ;; `org-entry-put' also makes the following check, but this one
  11863. ;; avoids polluting `org-last-set-property' and
  11864. ;; `org-last-set-property-value' needlessly.
  11865. (unless (org--valid-property-p property)
  11866. (user-error "Invalid property name: \"%s\"" property))
  11867. (let ((value (or value (org-read-property-value property)))
  11868. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  11869. (setq org-last-set-property property)
  11870. (setq org-last-set-property-value (concat property ": " value))
  11871. ;; Possibly postprocess the inserted value:
  11872. (when fn (setq value (funcall fn value)))
  11873. (unless (equal (org-entry-get nil property) value)
  11874. (org-entry-put nil property value)))))
  11875. (defun org-find-property (property &optional value)
  11876. "Find first entry in buffer that sets PROPERTY.
  11877. When optional argument VALUE is non-nil, only consider an entry
  11878. if it contains PROPERTY set to this value. If PROPERTY should be
  11879. explicitly set to nil, use string \"nil\" for VALUE.
  11880. Return position where the entry begins, or nil if there is no
  11881. such entry. If narrowing is in effect, only search the visible
  11882. part of the buffer."
  11883. (save-excursion
  11884. (goto-char (point-min))
  11885. (let ((case-fold-search t)
  11886. (re (org-re-property property nil (not value) value)))
  11887. (catch 'exit
  11888. (while (re-search-forward re nil t)
  11889. (when (if value (org-at-property-p)
  11890. (org-entry-get (point) property nil t))
  11891. (throw 'exit (progn (org-back-to-heading-or-point-min t)
  11892. (point)))))))))
  11893. (defun org-delete-property (property)
  11894. "In the current entry, delete PROPERTY."
  11895. (interactive
  11896. (let* ((completion-ignore-case t)
  11897. (cat (org-entry-get (point) "CATEGORY"))
  11898. (props0 (org-entry-properties nil 'standard))
  11899. (props (if cat props0
  11900. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  11901. (prop (if (< 1 (length props))
  11902. (completing-read "Property: " props nil t)
  11903. (caar props))))
  11904. (list prop)))
  11905. (if (not property)
  11906. (message "No property to delete in this entry")
  11907. (org-entry-delete nil property)
  11908. (message "Property \"%s\" deleted" property)))
  11909. (defun org-delete-property-globally (property)
  11910. "Remove PROPERTY globally, from all entries.
  11911. This function ignores narrowing, if any."
  11912. (interactive
  11913. (let* ((completion-ignore-case t)
  11914. (prop (completing-read
  11915. "Globally remove property: "
  11916. (mapcar #'list (org-buffer-property-keys)))))
  11917. (list prop)))
  11918. (org-with-wide-buffer
  11919. (goto-char (point-min))
  11920. (let ((count 0)
  11921. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  11922. (while (re-search-forward re nil t)
  11923. (when (org-entry-delete (point) property) (cl-incf count)))
  11924. (message "Property \"%s\" removed from %d entries" property count))))
  11925. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  11926. (defun org-compute-property-at-point ()
  11927. "Compute the property at point.
  11928. This looks for an enclosing column format, extracts the operator and
  11929. then applies it to the property in the column format's scope."
  11930. (interactive)
  11931. (unless (org-at-property-p)
  11932. (user-error "Not at a property"))
  11933. (let ((prop (match-string-no-properties 2)))
  11934. (org-columns-get-format-and-top-level)
  11935. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  11936. (user-error "No operator defined for property %s" prop))
  11937. (org-columns-compute prop)))
  11938. (defvar org-property-allowed-value-functions nil
  11939. "Hook for functions supplying allowed values for a specific property.
  11940. The functions must take a single argument, the name of the property, and
  11941. return a flat list of allowed values. If \":ETC\" is one of
  11942. the values, this means that these values are intended as defaults for
  11943. completion, but that other values should be allowed too.
  11944. The functions must return nil if they are not responsible for this
  11945. property.")
  11946. (defun org-property-get-allowed-values (pom property &optional table)
  11947. "Get allowed values for the property PROPERTY.
  11948. When TABLE is non-nil, return an alist that can directly be used for
  11949. completion."
  11950. (let (vals)
  11951. (cond
  11952. ((equal property "TODO")
  11953. (setq vals (org-with-point-at pom
  11954. (append org-todo-keywords-1 '("")))))
  11955. ((equal property "PRIORITY")
  11956. (let ((n org-priority-lowest))
  11957. (while (>= n org-priority-highest)
  11958. (push (char-to-string n) vals)
  11959. (setq n (1- n)))))
  11960. ((equal property "CATEGORY"))
  11961. ((member property org-special-properties))
  11962. ((setq vals (run-hook-with-args-until-success
  11963. 'org-property-allowed-value-functions property)))
  11964. (t
  11965. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  11966. (when (and vals (string-match "\\S-" vals))
  11967. (setq vals (car (read-from-string (concat "(" vals ")"))))
  11968. (setq vals (mapcar (lambda (x)
  11969. (cond ((stringp x) x)
  11970. ((numberp x) (number-to-string x))
  11971. ((symbolp x) (symbol-name x))
  11972. (t "???")))
  11973. vals)))))
  11974. (when (member ":ETC" vals)
  11975. (setq vals (remove ":ETC" vals))
  11976. (org-add-props (car vals) '(org-unrestricted t)))
  11977. (if table (mapcar 'list vals) vals)))
  11978. (defun org-property-previous-allowed-value (&optional _previous)
  11979. "Switch to the next allowed value for this property."
  11980. (interactive)
  11981. (org-property-next-allowed-value t))
  11982. (defun org-property-next-allowed-value (&optional previous)
  11983. "Switch to the next allowed value for this property."
  11984. (interactive)
  11985. (unless (org-at-property-p)
  11986. (user-error "Not at a property"))
  11987. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  11988. (key (match-string 2))
  11989. (value (match-string 3))
  11990. (allowed (or (org-property-get-allowed-values (point) key)
  11991. (and (member value '("[ ]" "[-]" "[X]"))
  11992. '("[ ]" "[X]"))))
  11993. (heading (save-match-data (nth 4 (org-heading-components))))
  11994. nval)
  11995. (unless allowed
  11996. (user-error "Allowed values for this property have not been defined"))
  11997. (when previous (setq allowed (reverse allowed)))
  11998. (when (member value allowed)
  11999. (setq nval (car (cdr (member value allowed)))))
  12000. (setq nval (or nval (car allowed)))
  12001. (when (equal nval value)
  12002. (user-error "Only one allowed value for this property"))
  12003. (org-at-property-p)
  12004. (replace-match (concat " :" key ": " nval) t t)
  12005. (org-indent-line)
  12006. (beginning-of-line 1)
  12007. (skip-chars-forward " \t")
  12008. (when (equal prop org-effort-property)
  12009. (unless (org-element--cache-active-p)
  12010. (org-refresh-property
  12011. '((effort . identity)
  12012. (effort-minutes . org-duration-to-minutes))
  12013. nval))
  12014. (when (string= org-clock-current-task heading)
  12015. (setq org-clock-effort nval)
  12016. (org-clock-update-mode-line)))
  12017. (run-hook-with-args 'org-property-changed-functions key nval)))
  12018. (defun org-find-olp (path &optional this-buffer)
  12019. "Return a marker pointing to the entry at outline path OLP.
  12020. If anything goes wrong, throw an error, and if you need to do
  12021. something based on this error, you can catch it with
  12022. `condition-case'.
  12023. If THIS-BUFFER is set, the outline path does not contain a file,
  12024. only headings."
  12025. (let* ((file (if this-buffer buffer-file-name (pop path)))
  12026. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  12027. (level 1)
  12028. (lmin 1)
  12029. (lmax 1)
  12030. end found flevel)
  12031. (unless buffer (error "File not found :%s" file))
  12032. (with-current-buffer buffer
  12033. (unless (derived-mode-p 'org-mode)
  12034. (error "Buffer %s needs to be in Org mode" buffer))
  12035. (org-with-wide-buffer
  12036. (goto-char (point-min))
  12037. (dolist (heading path)
  12038. (let ((re (format org-complex-heading-regexp-format
  12039. (regexp-quote heading)))
  12040. (cnt 0))
  12041. (while (re-search-forward re end t)
  12042. (setq level (- (match-end 1) (match-beginning 1)))
  12043. (when (and (>= level lmin) (<= level lmax))
  12044. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  12045. (when (= cnt 0)
  12046. (error "Heading not found on level %d: %s" lmax heading))
  12047. (when (> cnt 1)
  12048. (error "Heading not unique on level %d: %s" lmax heading))
  12049. (goto-char found)
  12050. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  12051. (setq end (save-excursion (org-end-of-subtree t t)))))
  12052. (when (org-at-heading-p)
  12053. (point-marker))))))
  12054. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  12055. "Find node HEADING in BUFFER.
  12056. Return a marker to the heading if it was found, or nil if not.
  12057. If POS-ONLY is set, return just the position instead of a marker.
  12058. The heading text must match exact, but it may have a TODO keyword,
  12059. a priority cookie and tags in the standard locations."
  12060. (with-current-buffer (or buffer (current-buffer))
  12061. (org-with-wide-buffer
  12062. (goto-char (point-min))
  12063. (let (case-fold-search)
  12064. (when (re-search-forward
  12065. (format org-complex-heading-regexp-format
  12066. (regexp-quote heading)) nil t)
  12067. (if pos-only
  12068. (match-beginning 0)
  12069. (move-marker (make-marker) (match-beginning 0))))))))
  12070. (defun org-find-exact-heading-in-directory (heading &optional dir)
  12071. "Find Org node headline HEADING in all \".org\" files in directory DIR.
  12072. When the target headline is found, return a marker to this location."
  12073. (let ((files (directory-files (or dir default-directory)
  12074. t "\\`[^.#].*\\.org\\'"))
  12075. visiting m buffer)
  12076. (catch 'found
  12077. (dolist (file files)
  12078. (message "trying %s" file)
  12079. (setq visiting (org-find-base-buffer-visiting file))
  12080. (setq buffer (or visiting (find-file-noselect file)))
  12081. (setq m (org-find-exact-headline-in-buffer
  12082. heading buffer))
  12083. (when (and (not m) (not visiting)) (kill-buffer buffer))
  12084. (and m (throw 'found m))))))
  12085. (defun org-find-entry-with-id (ident)
  12086. "Locate the entry that contains the ID property with exact value IDENT.
  12087. IDENT can be a string, a symbol or a number, this function will search for
  12088. the string representation of it.
  12089. Return the position where this entry starts, or nil if there is no such entry."
  12090. (interactive "sID: ")
  12091. (let ((id (cond
  12092. ((stringp ident) ident)
  12093. ((symbolp ident) (symbol-name ident))
  12094. ((numberp ident) (number-to-string ident))
  12095. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  12096. (org-with-wide-buffer (org-find-property "ID" id))))
  12097. ;;;; Timestamps
  12098. (defvar org-last-changed-timestamp nil)
  12099. (defvar org-last-inserted-timestamp nil
  12100. "The last time stamp inserted with `org-insert-time-stamp'.")
  12101. (defun org-time-stamp (arg &optional inactive)
  12102. "Prompt for a date/time and insert a time stamp.
  12103. If the user specifies a time like HH:MM or if this command is
  12104. called with at least one prefix argument, the time stamp contains
  12105. the date and the time. Otherwise, only the date is included.
  12106. All parts of a date not specified by the user are filled in from
  12107. the timestamp at point, if any, or the current date/time
  12108. otherwise.
  12109. If there is already a timestamp at the cursor, it is replaced.
  12110. With two universal prefix arguments, insert an active timestamp
  12111. with the current time without prompting the user.
  12112. When called from Lisp, the timestamp is inactive if INACTIVE is
  12113. non-nil."
  12114. (interactive "P")
  12115. (let* ((ts (cond
  12116. ((org-at-date-range-p t)
  12117. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  12118. ((org-at-timestamp-p 'lax) (match-string 0))))
  12119. ;; Default time is either the timestamp at point or today.
  12120. ;; When entering a range, only the range start is considered.
  12121. (default-time (and ts (org-time-string-to-time ts)))
  12122. (default-input (and ts (org-get-compact-tod ts)))
  12123. (repeater (and ts
  12124. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  12125. (match-string 0 ts)))
  12126. org-time-was-given
  12127. org-end-time-was-given
  12128. (time
  12129. (if (equal arg '(16)) (current-time)
  12130. ;; Preserve `this-command' and `last-command'.
  12131. (let ((this-command this-command)
  12132. (last-command last-command))
  12133. (org-read-date
  12134. arg 'totime nil nil default-time default-input
  12135. inactive)))))
  12136. (cond
  12137. ((and ts
  12138. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  12139. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  12140. (insert "--")
  12141. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  12142. (ts
  12143. ;; Make sure we're on a timestamp. When in the middle of a date
  12144. ;; range, move arbitrarily to range end.
  12145. (unless (org-at-timestamp-p 'lax)
  12146. (skip-chars-forward "-")
  12147. (org-at-timestamp-p 'lax))
  12148. (replace-match "")
  12149. (setq org-last-changed-timestamp
  12150. (org-insert-time-stamp
  12151. time (or org-time-was-given arg)
  12152. inactive nil nil (list org-end-time-was-given)))
  12153. (when repeater
  12154. (backward-char)
  12155. (insert " " repeater)
  12156. (setq org-last-changed-timestamp
  12157. (concat (substring org-last-inserted-timestamp 0 -1)
  12158. " " repeater ">")))
  12159. (message "Timestamp updated"))
  12160. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  12161. (t (org-insert-time-stamp
  12162. time (or org-time-was-given arg) inactive nil nil
  12163. (list org-end-time-was-given))))))
  12164. ;; FIXME: can we use this for something else, like computing time differences?
  12165. (defun org-get-compact-tod (s)
  12166. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  12167. (let* ((t1 (match-string 1 s))
  12168. (h1 (string-to-number (match-string 2 s)))
  12169. (m1 (string-to-number (match-string 3 s)))
  12170. (t2 (and (match-end 4) (match-string 5 s)))
  12171. (h2 (and t2 (string-to-number (match-string 6 s))))
  12172. (m2 (and t2 (string-to-number (match-string 7 s))))
  12173. dh dm)
  12174. (if (not t2)
  12175. t1
  12176. (setq dh (- h2 h1) dm (- m2 m1))
  12177. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  12178. (concat t1 "+" (number-to-string dh)
  12179. (and (/= 0 dm) (format ":%02d" dm)))))))
  12180. (defun org-time-stamp-inactive (&optional arg)
  12181. "Insert an inactive time stamp.
  12182. An inactive time stamp is enclosed in square brackets instead of
  12183. angle brackets. It is inactive in the sense that it does not
  12184. trigger agenda entries. So these are more for recording a
  12185. certain time/date.
  12186. If the user specifies a time like HH:MM or if this command is called with
  12187. at least one prefix argument, the time stamp contains the date and the time.
  12188. Otherwise, only the date is included.
  12189. When called with two universal prefix arguments, insert an inactive time stamp
  12190. with the current time without prompting the user."
  12191. (interactive "P")
  12192. (org-time-stamp arg 'inactive))
  12193. (defvar org-date-ovl (make-overlay 1 1))
  12194. (overlay-put org-date-ovl 'face 'org-date-selected)
  12195. (delete-overlay org-date-ovl)
  12196. (defvar org-ans1) ; dynamically scoped parameter
  12197. (defvar org-ans2) ; dynamically scoped parameter
  12198. (defvar org-plain-time-of-day-regexp) ; defined below
  12199. (defvar org-overriding-default-time nil) ; dynamically scoped
  12200. (defvar org-read-date-overlay nil)
  12201. (defvar org-read-date-history nil)
  12202. (defvar org-read-date-final-answer nil)
  12203. (defvar org-read-date-analyze-futurep nil)
  12204. (defvar org-read-date-analyze-forced-year nil)
  12205. (defvar org-read-date-inactive)
  12206. (defvar org-def)
  12207. (defvar org-defdecode)
  12208. (defvar org-with-time)
  12209. (defvar calendar-setup) ; Dynamically scoped.
  12210. (defun org-read-date (&optional with-time to-time from-string prompt
  12211. default-time default-input inactive)
  12212. "Read a date, possibly a time, and make things smooth for the user.
  12213. The prompt will suggest to enter an ISO date, but you can also enter anything
  12214. which will at least partially be understood by `parse-time-string'.
  12215. Unrecognized parts of the date will default to the current day, month, year,
  12216. hour and minute. If this command is called to replace a timestamp at point,
  12217. or to enter the second timestamp of a range, the default time is taken
  12218. from the existing stamp. Furthermore, the command prefers the future,
  12219. so if you are giving a date where the year is not given, and the day-month
  12220. combination is already past in the current year, it will assume you
  12221. mean next year. For details, see the manual. A few examples:
  12222. 3-2-5 --> 2003-02-05
  12223. feb 15 --> currentyear-02-15
  12224. 2/15 --> currentyear-02-15
  12225. sep 12 9 --> 2009-09-12
  12226. 12:45 --> today 12:45
  12227. 22 sept 0:34 --> currentyear-09-22 0:34
  12228. 12 --> currentyear-currentmonth-12
  12229. Fri --> nearest Friday after today
  12230. -Tue --> last Tuesday
  12231. etc.
  12232. Furthermore you can specify a relative date by giving, as the *first* thing
  12233. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  12234. change in days weeks, months, years.
  12235. With a single plus or minus, the date is relative to today. With a double
  12236. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  12237. +4d --> four days from today
  12238. +4 --> same as above
  12239. +2w --> two weeks from today
  12240. ++5 --> five days from default date
  12241. The function understands only English month and weekday abbreviations.
  12242. While prompting, a calendar is popped up - you can also select the
  12243. date with the mouse (button 1). The calendar shows a period of three
  12244. months. To scroll it to other months, use the keys `>' and `<'.
  12245. There are many other calendar navigation commands available, see
  12246. Info node `(org) The date/time prompt' for a full list.
  12247. If you don't like the calendar, turn it off with
  12248. (setq org-read-date-popup-calendar nil)
  12249. With optional argument TO-TIME, the date will immediately be converted
  12250. to an internal time.
  12251. With an optional argument WITH-TIME, the prompt will suggest to
  12252. also insert a time. Note that when WITH-TIME is not set, you can
  12253. still enter a time, and this function will inform the calling routine
  12254. about this change. The calling routine may then choose to change the
  12255. format used to insert the time stamp into the buffer to include the time.
  12256. With optional argument FROM-STRING, read from this string instead from
  12257. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  12258. the time/date that is used for everything that is not specified by the
  12259. user."
  12260. (require 'parse-time)
  12261. (let* ((org-with-time with-time)
  12262. (org-time-stamp-rounding-minutes
  12263. (if (equal org-with-time '(16))
  12264. '(0 0)
  12265. org-time-stamp-rounding-minutes))
  12266. (ct (org-current-time))
  12267. (org-def (or org-overriding-default-time default-time ct))
  12268. (org-defdecode (decode-time org-def))
  12269. (cur-frame (selected-frame))
  12270. (mouse-autoselect-window nil) ; Don't let the mouse jump
  12271. (calendar-setup
  12272. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  12273. (calendar-move-hook nil)
  12274. (calendar-view-diary-initially-flag nil)
  12275. (calendar-view-holidays-initially-flag nil)
  12276. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  12277. ;; Rationalize `org-def' and `org-defdecode', if required.
  12278. (when (< (nth 2 org-defdecode) org-extend-today-until)
  12279. (setf (nth 2 org-defdecode) -1)
  12280. (setf (nth 1 org-defdecode) 59)
  12281. (setq org-def (org-encode-time org-defdecode))
  12282. (setq org-defdecode (decode-time org-def)))
  12283. (let* ((timestr (format-time-string
  12284. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  12285. org-def))
  12286. (prompt (concat (if prompt (concat prompt " ") "")
  12287. (format "Date+time [%s]: " timestr))))
  12288. (cond
  12289. (from-string (setq ans from-string))
  12290. (org-read-date-popup-calendar
  12291. (save-excursion
  12292. (save-window-excursion
  12293. (calendar)
  12294. (when (eq calendar-setup 'calendar-only)
  12295. (setq cal-frame
  12296. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  12297. (select-frame cal-frame))
  12298. (org-eval-in-calendar '(setq cursor-type nil) t)
  12299. (unwind-protect
  12300. (progn
  12301. (calendar-forward-day (- (time-to-days org-def)
  12302. (calendar-absolute-from-gregorian
  12303. (calendar-current-date))))
  12304. (org-eval-in-calendar nil t)
  12305. (let* ((old-map (current-local-map))
  12306. (map (copy-keymap calendar-mode-map))
  12307. (minibuffer-local-map
  12308. (copy-keymap org-read-date-minibuffer-local-map)))
  12309. (org-defkey map (kbd "RET") 'org-calendar-select)
  12310. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  12311. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  12312. (unwind-protect
  12313. (progn
  12314. (use-local-map map)
  12315. (setq org-read-date-inactive inactive)
  12316. (add-hook 'post-command-hook 'org-read-date-display)
  12317. (setq org-ans0
  12318. (read-string prompt
  12319. default-input
  12320. 'org-read-date-history
  12321. nil))
  12322. ;; org-ans0: from prompt
  12323. ;; org-ans1: from mouse click
  12324. ;; org-ans2: from calendar motion
  12325. (setq ans
  12326. (concat org-ans0 " " (or org-ans1 org-ans2))))
  12327. (remove-hook 'post-command-hook 'org-read-date-display)
  12328. (use-local-map old-map)
  12329. (when org-read-date-overlay
  12330. (delete-overlay org-read-date-overlay)
  12331. (setq org-read-date-overlay nil)))))
  12332. (bury-buffer "*Calendar*")
  12333. (when cal-frame
  12334. (delete-frame cal-frame)
  12335. (select-frame-set-input-focus cur-frame))))))
  12336. (t ; Naked prompt only
  12337. (unwind-protect
  12338. (setq ans (read-string prompt default-input
  12339. 'org-read-date-history timestr))
  12340. (when org-read-date-overlay
  12341. (delete-overlay org-read-date-overlay)
  12342. (setq org-read-date-overlay nil))))))
  12343. (setq final (org-read-date-analyze ans org-def org-defdecode))
  12344. (when org-read-date-analyze-forced-year
  12345. (message "Year was forced into %s"
  12346. (if org-read-date-force-compatible-dates
  12347. "compatible range (1970-2037)"
  12348. "range representable on this machine"))
  12349. (ding))
  12350. (setq final (org-encode-time final))
  12351. (setq org-read-date-final-answer ans)
  12352. (if to-time
  12353. final
  12354. ;; This round-trip gets rid of 34th of August and stuff like that....
  12355. (setq final (decode-time final))
  12356. (if (and (boundp 'org-time-was-given) org-time-was-given)
  12357. (format "%04d-%02d-%02d %02d:%02d"
  12358. (nth 5 final) (nth 4 final) (nth 3 final)
  12359. (nth 2 final) (nth 1 final))
  12360. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  12361. (defun org-read-date-display ()
  12362. "Display the current date prompt interpretation in the minibuffer."
  12363. (when org-read-date-display-live
  12364. (when org-read-date-overlay
  12365. (delete-overlay org-read-date-overlay))
  12366. (when (minibufferp (current-buffer))
  12367. (save-excursion
  12368. (end-of-line 1)
  12369. (while (not (equal (buffer-substring
  12370. (max (point-min) (- (point) 4)) (point))
  12371. " "))
  12372. (insert " ")))
  12373. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  12374. " " (or org-ans1 org-ans2)))
  12375. (org-end-time-was-given nil)
  12376. (f (org-read-date-analyze ans org-def org-defdecode))
  12377. (fmts (if org-display-custom-times
  12378. org-time-stamp-custom-formats
  12379. org-time-stamp-formats))
  12380. (fmt (if (or org-with-time
  12381. (and (boundp 'org-time-was-given) org-time-was-given))
  12382. (cdr fmts)
  12383. (car fmts)))
  12384. (txt (format-time-string fmt (org-encode-time f)))
  12385. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  12386. (txt (concat "=> " txt)))
  12387. (when (and org-end-time-was-given
  12388. (string-match org-plain-time-of-day-regexp txt))
  12389. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  12390. org-end-time-was-given
  12391. (substring txt (match-end 0)))))
  12392. (when org-read-date-analyze-futurep
  12393. (setq txt (concat txt " (=>F)")))
  12394. (setq org-read-date-overlay
  12395. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  12396. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  12397. (defun org-read-date-analyze (ans def defdecode)
  12398. "Analyze the combined answer of the date prompt."
  12399. ;; FIXME: cleanup and comment
  12400. (let ((org-def def)
  12401. (org-defdecode defdecode)
  12402. (nowdecode (decode-time))
  12403. delta deltan deltaw deltadef year month day
  12404. hour minute second wday pm h2 m2 tl wday1
  12405. iso-year iso-weekday iso-week iso-date futurep kill-year)
  12406. (setq org-read-date-analyze-futurep nil
  12407. org-read-date-analyze-forced-year nil)
  12408. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  12409. (setq ans "+0"))
  12410. (when (setq delta (org-read-date-get-relative ans nil org-def))
  12411. (setq ans (replace-match "" t t ans)
  12412. deltan (car delta)
  12413. deltaw (nth 1 delta)
  12414. deltadef (nth 2 delta)))
  12415. ;; Check if there is an iso week date in there. If yes, store the
  12416. ;; info and postpone interpreting it until the rest of the parsing
  12417. ;; is done.
  12418. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  12419. (setq iso-year (when (match-end 1)
  12420. (org-small-year-to-year
  12421. (string-to-number (match-string 1 ans))))
  12422. iso-weekday (when (match-end 3)
  12423. (string-to-number (match-string 3 ans)))
  12424. iso-week (string-to-number (match-string 2 ans)))
  12425. (setq ans (replace-match "" t t ans)))
  12426. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  12427. (when (string-match
  12428. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  12429. (setq year (if (match-end 2)
  12430. (string-to-number (match-string 2 ans))
  12431. (progn (setq kill-year t)
  12432. (string-to-number (format-time-string "%Y"))))
  12433. month (string-to-number (match-string 3 ans))
  12434. day (string-to-number (match-string 4 ans)))
  12435. (setq year (org-small-year-to-year year))
  12436. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  12437. t nil ans)))
  12438. ;; Help matching dotted european dates
  12439. (when (string-match
  12440. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  12441. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  12442. (setq kill-year t)
  12443. (string-to-number (format-time-string "%Y")))
  12444. day (string-to-number (match-string 1 ans))
  12445. month (string-to-number (match-string 2 ans))
  12446. ans (replace-match (format "%04d-%02d-%02d" year month day)
  12447. t nil ans)))
  12448. ;; Help matching american dates, like 5/30 or 5/30/7
  12449. (when (string-match
  12450. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  12451. (setq year (if (match-end 4)
  12452. (string-to-number (match-string 4 ans))
  12453. (progn (setq kill-year t)
  12454. (string-to-number (format-time-string "%Y"))))
  12455. month (string-to-number (match-string 1 ans))
  12456. day (string-to-number (match-string 2 ans)))
  12457. (setq year (org-small-year-to-year year))
  12458. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  12459. t nil ans)))
  12460. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  12461. ;; If there is a time with am/pm, and *no* time without it, we convert
  12462. ;; so that matching will be successful.
  12463. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  12464. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  12465. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  12466. (setq hour (string-to-number (match-string 1 ans))
  12467. minute (if (match-end 3)
  12468. (string-to-number (match-string 3 ans))
  12469. 0)
  12470. pm (equal ?p
  12471. (string-to-char (downcase (match-string 4 ans)))))
  12472. (if (and (= hour 12) (not pm))
  12473. (setq hour 0)
  12474. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  12475. (setq ans (replace-match (format "%02d:%02d" hour minute)
  12476. t t ans))))
  12477. ;; Help matching HHhMM times, similarly as for am/pm times.
  12478. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  12479. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  12480. (string-match "\\(?:\\(?1:[012]?[0-9]\\)?h\\(?2:[0-5][0-9]\\)\\)\\|\\(?:\\(?1:[012]?[0-9]\\)h\\(?2:[0-5][0-9]\\)?\\)\\>" ans))
  12481. (setq hour (if (match-end 1)
  12482. (string-to-number (match-string 1 ans))
  12483. 0)
  12484. minute (if (match-end 2)
  12485. (string-to-number (match-string 2 ans))
  12486. 0))
  12487. (setq ans (replace-match (format "%02d:%02d" hour minute)
  12488. t t ans))))
  12489. ;; Check if a time range is given as a duration
  12490. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  12491. (setq hour (string-to-number (match-string 1 ans))
  12492. h2 (+ hour (string-to-number (match-string 3 ans)))
  12493. minute (string-to-number (match-string 2 ans))
  12494. m2 (+ minute (if (match-end 5) (string-to-number
  12495. (match-string 5 ans))0)))
  12496. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  12497. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  12498. t t ans)))
  12499. ;; Check if there is a time range
  12500. (when (boundp 'org-end-time-was-given)
  12501. (setq org-time-was-given nil)
  12502. (when (and (string-match org-plain-time-of-day-regexp ans)
  12503. (match-end 8))
  12504. (setq org-end-time-was-given (match-string 8 ans))
  12505. (setq ans (concat (substring ans 0 (match-beginning 7))
  12506. (substring ans (match-end 7))))))
  12507. (setq tl (parse-time-string ans)
  12508. day (or (nth 3 tl) (nth 3 org-defdecode))
  12509. month
  12510. (cond ((nth 4 tl))
  12511. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  12512. ;; Day was specified. Make sure DAY+MONTH
  12513. ;; combination happens in the future.
  12514. ((nth 3 tl)
  12515. (setq futurep t)
  12516. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  12517. (nth 4 nowdecode)))
  12518. (t (nth 4 org-defdecode)))
  12519. year
  12520. (cond ((and (not kill-year) (nth 5 tl)))
  12521. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  12522. ;; Month was guessed in the future and is at least
  12523. ;; equal to NOWDECODE's. Fix year accordingly.
  12524. (futurep
  12525. (if (or (> month (nth 4 nowdecode))
  12526. (>= day (nth 3 nowdecode)))
  12527. (nth 5 nowdecode)
  12528. (1+ (nth 5 nowdecode))))
  12529. ;; Month was specified. Make sure MONTH+YEAR
  12530. ;; combination happens in the future.
  12531. ((nth 4 tl)
  12532. (setq futurep t)
  12533. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  12534. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  12535. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  12536. (t (nth 5 nowdecode))))
  12537. (t (nth 5 org-defdecode)))
  12538. hour (or (nth 2 tl) (nth 2 org-defdecode))
  12539. minute (or (nth 1 tl) (nth 1 org-defdecode))
  12540. second (or (nth 0 tl) 0)
  12541. wday (nth 6 tl))
  12542. (when (and (eq org-read-date-prefer-future 'time)
  12543. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  12544. (equal day (nth 3 nowdecode))
  12545. (equal month (nth 4 nowdecode))
  12546. (equal year (nth 5 nowdecode))
  12547. (nth 2 tl)
  12548. (or (< (nth 2 tl) (nth 2 nowdecode))
  12549. (and (= (nth 2 tl) (nth 2 nowdecode))
  12550. (nth 1 tl)
  12551. (< (nth 1 tl) (nth 1 nowdecode)))))
  12552. (setq day (1+ day)
  12553. futurep t))
  12554. ;; Special date definitions below
  12555. (cond
  12556. (iso-week
  12557. ;; There was an iso week
  12558. (require 'cal-iso)
  12559. (setq futurep nil)
  12560. (setq year (or iso-year year)
  12561. day (or iso-weekday wday 1)
  12562. wday nil ; to make sure that the trigger below does not match
  12563. iso-date (calendar-gregorian-from-absolute
  12564. (calendar-iso-to-absolute
  12565. (list iso-week day year))))
  12566. ; FIXME: Should we also push ISO weeks into the future?
  12567. ; (when (and org-read-date-prefer-future
  12568. ; (not iso-year)
  12569. ; (< (calendar-absolute-from-gregorian iso-date)
  12570. ; (time-to-days nil)))
  12571. ; (setq year (1+ year)
  12572. ; iso-date (calendar-gregorian-from-absolute
  12573. ; (calendar-iso-to-absolute
  12574. ; (list iso-week day year)))))
  12575. (setq month (car iso-date)
  12576. year (nth 2 iso-date)
  12577. day (nth 1 iso-date)))
  12578. (deltan
  12579. (setq futurep nil)
  12580. (unless deltadef
  12581. (let ((now (decode-time)))
  12582. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  12583. (cond ((member deltaw '("h" ""))
  12584. (when (boundp 'org-time-was-given)
  12585. (setq org-time-was-given t))
  12586. (setq hour (+ hour deltan)))
  12587. ((member deltaw '("d" "")) (setq day (+ day deltan)))
  12588. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  12589. ((equal deltaw "m") (setq month (+ month deltan)))
  12590. ((equal deltaw "y") (setq year (+ year deltan)))))
  12591. ((and wday (not (nth 3 tl)))
  12592. ;; Weekday was given, but no day, so pick that day in the week
  12593. ;; on or after the derived date.
  12594. (setq wday1 (nth 6 (decode-time (org-encode-time 0 0 0 day month year))))
  12595. (unless (equal wday wday1)
  12596. (setq day (+ day (% (- wday wday1 -7) 7))))))
  12597. (when (and (boundp 'org-time-was-given)
  12598. (nth 2 tl))
  12599. (setq org-time-was-given t))
  12600. (when (< year 100) (setq year (+ 2000 year)))
  12601. ;; Check of the date is representable
  12602. (if org-read-date-force-compatible-dates
  12603. (progn
  12604. (when (< year 1970)
  12605. (setq year 1970 org-read-date-analyze-forced-year t))
  12606. (when (> year 2037)
  12607. (setq year 2037 org-read-date-analyze-forced-year t)))
  12608. (condition-case nil
  12609. (ignore (org-encode-time second minute hour day month year))
  12610. (error
  12611. (setq year (nth 5 org-defdecode))
  12612. (setq org-read-date-analyze-forced-year t))))
  12613. (setq org-read-date-analyze-futurep futurep)
  12614. (list second minute hour day month year nil -1 nil)))
  12615. (defvar parse-time-weekdays)
  12616. (defun org-read-date-get-relative (s today default)
  12617. "Check string S for special relative date string.
  12618. TODAY and DEFAULT are internal times, for today and for a default.
  12619. Return shift list (N what def-flag)
  12620. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  12621. N is the number of WHATs to shift.
  12622. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  12623. the DEFAULT date rather than TODAY."
  12624. (require 'parse-time)
  12625. (when (and
  12626. (string-match
  12627. (concat
  12628. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  12629. "\\([0-9]+\\)?"
  12630. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  12631. "\\([ \t]\\|$\\)") s)
  12632. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  12633. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  12634. (string-to-char (substring (match-string 1 s) -1))
  12635. ?+))
  12636. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  12637. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  12638. (what (if (match-end 3) (match-string 3 s) "d"))
  12639. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  12640. (date (if rel default today))
  12641. (wday (nth 6 (decode-time date)))
  12642. delta)
  12643. (if wday1
  12644. (progn
  12645. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  12646. (when (= delta 0) (setq delta 7))
  12647. (when (= dir ?-)
  12648. (setq delta (- delta 7))
  12649. (when (= delta 0) (setq delta -7)))
  12650. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  12651. (list delta "d" rel))
  12652. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  12653. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  12654. "Turn a user-specified date into the internal representation.
  12655. The internal representation needed by the calendar is (month day year).
  12656. This is a wrapper to handle the brain-dead convention in calendar that
  12657. user function argument order change dependent on argument order."
  12658. (pcase calendar-date-style
  12659. (`american (list arg1 arg2 arg3))
  12660. (`european (list arg2 arg1 arg3))
  12661. (`iso (list arg2 arg3 arg1))))
  12662. (defun org-eval-in-calendar (form &optional keepdate)
  12663. "Eval FORM in the calendar window and return to current window.
  12664. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  12665. (let ((sf (selected-frame))
  12666. (sw (selected-window)))
  12667. (select-window (get-buffer-window "*Calendar*" t))
  12668. (eval form t)
  12669. (when (and (not keepdate) (calendar-cursor-to-date))
  12670. (let* ((date (calendar-cursor-to-date))
  12671. (time (org-encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  12672. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  12673. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  12674. (select-window sw)
  12675. (select-frame-set-input-focus sf)))
  12676. (defun org-calendar-select ()
  12677. "Return to `org-read-date' with the date currently selected.
  12678. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  12679. (interactive)
  12680. (when (calendar-cursor-to-date)
  12681. (let* ((date (calendar-cursor-to-date))
  12682. (time (org-encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  12683. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  12684. (when (active-minibuffer-window) (exit-minibuffer))))
  12685. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  12686. "Insert a date stamp for the date given by the internal TIME.
  12687. See `format-time-string' for the format of TIME.
  12688. WITH-HM means use the stamp format that includes the time of the day.
  12689. INACTIVE means use square brackets instead of angular ones, so that the
  12690. stamp will not contribute to the agenda.
  12691. PRE and POST are optional strings to be inserted before and after the
  12692. stamp.
  12693. The command returns the inserted time stamp."
  12694. (org-fold-core-ignore-modifications
  12695. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  12696. stamp)
  12697. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  12698. (insert-before-markers-and-inherit (or pre ""))
  12699. (when (listp extra)
  12700. (setq extra (car extra))
  12701. (if (and (stringp extra)
  12702. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  12703. (setq extra (format "-%02d:%02d"
  12704. (string-to-number (match-string 1 extra))
  12705. (string-to-number (match-string 2 extra))))
  12706. (setq extra nil)))
  12707. (when extra
  12708. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  12709. (insert-before-markers-and-inherit (setq stamp (format-time-string fmt time)))
  12710. (insert-before-markers-and-inherit (or post ""))
  12711. (setq org-last-inserted-timestamp stamp))))
  12712. (defun org-toggle-time-stamp-overlays ()
  12713. "Toggle the use of custom time stamp formats."
  12714. (interactive)
  12715. (setq org-display-custom-times (not org-display-custom-times))
  12716. (unless org-display-custom-times
  12717. (let ((p (point-min)) (bmp (buffer-modified-p)))
  12718. (while (setq p (next-single-property-change p 'display))
  12719. (when (and (get-text-property p 'display)
  12720. (eq (get-text-property p 'face) 'org-date))
  12721. (remove-text-properties
  12722. p (setq p (next-single-property-change p 'display))
  12723. '(display t))))
  12724. (set-buffer-modified-p bmp)))
  12725. (org-restart-font-lock)
  12726. (setq org-table-may-need-update t)
  12727. (if org-display-custom-times
  12728. (message "Time stamps are overlaid with custom format")
  12729. (message "Time stamp overlays removed")))
  12730. (defun org-display-custom-time (beg end)
  12731. "Overlay modified time stamp format over timestamp between BEG and END."
  12732. (let* ((ts (buffer-substring beg end))
  12733. t1 with-hm tf time str (off 0))
  12734. (save-match-data
  12735. (setq t1 (org-parse-time-string ts t))
  12736. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  12737. (setq off (- (match-end 0) (match-beginning 0)))))
  12738. (setq end (- end off))
  12739. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  12740. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  12741. time (org-fix-decoded-time t1)
  12742. str (org-add-props
  12743. (format-time-string
  12744. (substring tf 1 -1) (org-encode-time time))
  12745. nil 'mouse-face 'highlight))
  12746. (put-text-property beg end 'display str)))
  12747. (defun org-fix-decoded-time (time)
  12748. "Set 0 instead of nil for the first 6 elements of time.
  12749. Don't touch the rest."
  12750. (let ((n 0))
  12751. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  12752. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  12753. "Difference between TIMESTAMP-STRING and now in days.
  12754. If SECONDS is non-nil, return the difference in seconds."
  12755. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  12756. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  12757. (funcall fdiff nil))))
  12758. (defun org-deadline-close-p (timestamp-string &optional ndays)
  12759. "Is the time in TIMESTAMP-STRING close to the current date?"
  12760. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  12761. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  12762. (not (org-entry-is-done-p))))
  12763. (defun org-get-wdays (ts &optional delay zero-delay)
  12764. "Get the deadline lead time appropriate for timestring TS.
  12765. When DELAY is non-nil, get the delay time for scheduled items
  12766. instead of the deadline lead time. When ZERO-DELAY is non-nil
  12767. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  12768. don't try to find the delay cookie in the scheduled timestamp."
  12769. (let ((tv (if delay org-scheduled-delay-days
  12770. org-deadline-warning-days)))
  12771. (cond
  12772. ((or (and delay (< tv 0))
  12773. (and delay zero-delay (<= tv 0))
  12774. (and (not delay) (<= tv 0)))
  12775. ;; Enforce this value no matter what
  12776. (- tv))
  12777. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  12778. ;; lead time is specified.
  12779. (floor (* (string-to-number (match-string 1 ts))
  12780. (cdr (assoc (match-string 2 ts)
  12781. '(("d" . 1) ("w" . 7)
  12782. ("m" . 30.4) ("y" . 365.25)
  12783. ("h" . 0.041667)))))))
  12784. ;; go for the default.
  12785. (t tv))))
  12786. (defun org-calendar-select-mouse (ev)
  12787. "Return to `org-read-date' with the date currently selected.
  12788. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  12789. (interactive "e")
  12790. (mouse-set-point ev)
  12791. (when (calendar-cursor-to-date)
  12792. (let* ((date (calendar-cursor-to-date))
  12793. (time (org-encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  12794. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  12795. (when (active-minibuffer-window) (exit-minibuffer))))
  12796. (defun org-check-deadlines (ndays)
  12797. "Check if there are any deadlines due or past due.
  12798. A deadline is considered due if it happens within `org-deadline-warning-days'
  12799. days from today's date. If the deadline appears in an entry marked DONE,
  12800. it is not shown. A numeric prefix argument NDAYS can be used to test that
  12801. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  12802. are shown."
  12803. (interactive "P")
  12804. (let* ((org-warn-days
  12805. (cond
  12806. ((equal ndays '(4)) 100000)
  12807. (ndays (prefix-numeric-value ndays))
  12808. (t (abs org-deadline-warning-days))))
  12809. (case-fold-search nil)
  12810. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  12811. (callback
  12812. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  12813. (message "%d deadlines past-due or due within %d days"
  12814. (org-occur regexp nil callback)
  12815. org-warn-days)))
  12816. (defsubst org-re-timestamp (type)
  12817. "Return a regexp for timestamp TYPE.
  12818. Allowed values for TYPE are:
  12819. all: all timestamps
  12820. active: only active timestamps (<...>)
  12821. inactive: only inactive timestamps ([...])
  12822. scheduled: only scheduled timestamps
  12823. deadline: only deadline timestamps
  12824. closed: only closed time-stamps
  12825. When TYPE is nil, fall back on returning a regexp that matches
  12826. both scheduled and deadline timestamps."
  12827. (cl-case type
  12828. (all org-ts-regexp-both)
  12829. (active org-ts-regexp)
  12830. (inactive org-ts-regexp-inactive)
  12831. (scheduled org-scheduled-time-regexp)
  12832. (deadline org-deadline-time-regexp)
  12833. (closed org-closed-time-regexp)
  12834. (otherwise
  12835. (concat "\\<"
  12836. (regexp-opt (list org-deadline-string org-scheduled-string))
  12837. " *<\\([^>]+\\)>"))))
  12838. (defun org-check-before-date (d)
  12839. "Check if there are deadlines or scheduled entries before date D."
  12840. (interactive (list (org-read-date)))
  12841. (let* ((case-fold-search nil)
  12842. (regexp (org-re-timestamp org-ts-type))
  12843. (ts-type org-ts-type)
  12844. (callback
  12845. (lambda ()
  12846. (let ((match (match-string 1)))
  12847. (and (if (memq ts-type '(active inactive all))
  12848. (eq (org-element-type (save-excursion
  12849. (backward-char)
  12850. (org-element-context)))
  12851. 'timestamp)
  12852. (org-at-planning-p))
  12853. (time-less-p
  12854. (org-time-string-to-time match)
  12855. (org-time-string-to-time d)))))))
  12856. (message "%d entries before %s"
  12857. (org-occur regexp nil callback)
  12858. d)))
  12859. (defun org-check-after-date (d)
  12860. "Check if there are deadlines or scheduled entries after date D."
  12861. (interactive (list (org-read-date)))
  12862. (let* ((case-fold-search nil)
  12863. (regexp (org-re-timestamp org-ts-type))
  12864. (ts-type org-ts-type)
  12865. (callback
  12866. (lambda ()
  12867. (let ((match (match-string 1)))
  12868. (and (if (memq ts-type '(active inactive all))
  12869. (eq (org-element-type (save-excursion
  12870. (backward-char)
  12871. (org-element-context)))
  12872. 'timestamp)
  12873. (org-at-planning-p))
  12874. (not (time-less-p
  12875. (org-time-string-to-time match)
  12876. (org-time-string-to-time d))))))))
  12877. (message "%d entries after %s"
  12878. (org-occur regexp nil callback)
  12879. d)))
  12880. (defun org-check-dates-range (start-date end-date)
  12881. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  12882. (interactive (list (org-read-date nil nil nil "Range starts")
  12883. (org-read-date nil nil nil "Range end")))
  12884. (let ((case-fold-search nil)
  12885. (regexp (org-re-timestamp org-ts-type))
  12886. (callback
  12887. (let ((type org-ts-type))
  12888. (lambda ()
  12889. (let ((match (match-string 1)))
  12890. (and
  12891. (if (memq type '(active inactive all))
  12892. (eq (org-element-type (save-excursion
  12893. (backward-char)
  12894. (org-element-context)))
  12895. 'timestamp)
  12896. (org-at-planning-p))
  12897. (not (time-less-p
  12898. (org-time-string-to-time match)
  12899. (org-time-string-to-time start-date)))
  12900. (time-less-p
  12901. (org-time-string-to-time match)
  12902. (org-time-string-to-time end-date))))))))
  12903. (message "%d entries between %s and %s"
  12904. (org-occur regexp nil callback) start-date end-date)))
  12905. (defun org-evaluate-time-range (&optional to-buffer)
  12906. "Evaluate a time range by computing the difference between start and end.
  12907. Normally the result is just printed in the echo area, but with prefix arg
  12908. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  12909. If the time range is actually in a table, the result is inserted into the
  12910. next column.
  12911. For time difference computation, a year is assumed to be exactly 365
  12912. days in order to avoid rounding problems."
  12913. (interactive "P")
  12914. (or
  12915. (org-clock-update-time-maybe)
  12916. (save-excursion
  12917. (unless (org-at-date-range-p t)
  12918. (goto-char (point-at-bol))
  12919. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  12920. (unless (org-at-date-range-p t)
  12921. (user-error "Not at a time-stamp range, and none found in current line")))
  12922. (let* ((ts1 (match-string 1))
  12923. (ts2 (match-string 2))
  12924. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  12925. (match-end (match-end 0))
  12926. (time1 (org-time-string-to-time ts1))
  12927. (time2 (org-time-string-to-time ts2))
  12928. (diff (abs (float-time (time-subtract time2 time1))))
  12929. (negative (time-less-p time2 time1))
  12930. ;; (ys (floor (* 365 24 60 60)))
  12931. (ds (* 24 60 60))
  12932. (hs (* 60 60))
  12933. (fy "%dy %dd %02d:%02d")
  12934. (fy1 "%dy %dd")
  12935. (fd "%dd %02d:%02d")
  12936. (fd1 "%dd")
  12937. (fh "%02d:%02d")
  12938. y d h m align)
  12939. (if havetime
  12940. (setq ; y (floor diff ys) diff (mod diff ys)
  12941. y 0
  12942. d (floor diff ds) diff (mod diff ds)
  12943. h (floor diff hs) diff (mod diff hs)
  12944. m (floor diff 60))
  12945. (setq ; y (floor diff ys) diff (mod diff ys)
  12946. y 0
  12947. d (round diff ds)
  12948. h 0 m 0))
  12949. (if (not to-buffer)
  12950. (message "%s" (org-make-tdiff-string y d h m))
  12951. (if (org-at-table-p)
  12952. (progn
  12953. (goto-char match-end)
  12954. (setq align t)
  12955. (and (looking-at " *|") (goto-char (match-end 0))))
  12956. (goto-char match-end))
  12957. (when (looking-at
  12958. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  12959. (replace-match ""))
  12960. (when negative (insert " -"))
  12961. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  12962. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  12963. (insert " " (format fh h m))))
  12964. (when align (org-table-align))
  12965. (message "Time difference inserted")))))
  12966. (defun org-make-tdiff-string (y d h m)
  12967. (let ((fmt "")
  12968. (l nil))
  12969. (when (> y 0)
  12970. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  12971. (push y l))
  12972. (when (> d 0)
  12973. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  12974. (push d l))
  12975. (when (> h 0)
  12976. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  12977. (push h l))
  12978. (when (> m 0)
  12979. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  12980. (push m l))
  12981. (apply 'format fmt (nreverse l))))
  12982. (defun org-time-string-to-time (s)
  12983. "Convert timestamp string S into internal time."
  12984. (org-encode-time (org-parse-time-string s)))
  12985. (defun org-time-string-to-seconds (s)
  12986. "Convert a timestamp string S into a number of seconds."
  12987. (float-time (org-time-string-to-time s)))
  12988. (define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  12989. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  12990. "Convert time stamp S to an absolute day number.
  12991. If DAYNR in non-nil, and there is a specifier for a cyclic time
  12992. stamp, get the closest date to DAYNR. If PREFER is
  12993. `past' (respectively `future') return a date past (respectively
  12994. after) or equal to DAYNR.
  12995. POS is the location of time stamp S, as a buffer position in
  12996. BUFFER.
  12997. Diary sexp timestamps are matched against DAYNR, when non-nil.
  12998. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  12999. signaled."
  13000. (cond
  13001. ((string-match "\\`%%\\((.*)\\)" s)
  13002. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  13003. ;; only able to match individual dates. If it fails, raise an
  13004. ;; error.
  13005. (if (and daynr
  13006. (org-diary-sexp-entry
  13007. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  13008. daynr
  13009. (signal 'org-diary-sexp-no-match (list s))))
  13010. (daynr (org-closest-date s daynr prefer))
  13011. (t (time-to-days
  13012. (condition-case errdata
  13013. (org-time-string-to-time s)
  13014. (error (error "Bad timestamp `%s'%s\nError was: %s"
  13015. s
  13016. (if (not (and buffer pos)) ""
  13017. (format-message " at %d in buffer `%s'" pos buffer))
  13018. (cdr errdata))))))))
  13019. (defun org-days-to-iso-week (days)
  13020. "Return the ISO week number."
  13021. (require 'cal-iso)
  13022. (car (calendar-iso-from-absolute days)))
  13023. (defun org-small-year-to-year (year)
  13024. "Convert 2-digit years into 4-digit years.
  13025. YEAR is expanded into one of the 30 next years, if possible, or
  13026. into a past one. Any year larger than 99 is returned unchanged."
  13027. (if (>= year 100) year
  13028. (let* ((current (string-to-number (format-time-string "%Y")))
  13029. (century (/ current 100))
  13030. (offset (- year (% current 100))))
  13031. (cond ((> offset 30) (+ (* (1- century) 100) year))
  13032. ((> offset -70) (+ (* century 100) year))
  13033. (t (+ (* (1+ century) 100) year))))))
  13034. (defun org-time-from-absolute (d)
  13035. "Return the time corresponding to date D.
  13036. D may be an absolute day number, or a calendar-type list (month day year)."
  13037. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  13038. (org-encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  13039. (defvar org-agenda-current-date)
  13040. (defun org-calendar-holiday ()
  13041. "List of holidays, for Diary display in Org mode."
  13042. (require 'holidays)
  13043. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  13044. (and hl (mapconcat #'identity hl "; "))))
  13045. (defun org-diary-sexp-entry (sexp entry d)
  13046. "Process a SEXP diary ENTRY for date D."
  13047. (require 'diary-lib)
  13048. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  13049. ;; dynamically.
  13050. (let* ((sexp `(let ((entry ,entry)
  13051. (date ',d))
  13052. ,(car (read-from-string sexp))))
  13053. ;; FIXME: Do not use (eval ... t) in the following sexp as
  13054. ;; diary vars are still using dynamic scope.
  13055. (result (if calendar-debug-sexp (eval sexp)
  13056. (condition-case nil
  13057. (eval sexp)
  13058. (error
  13059. (beep)
  13060. (message "Bad sexp at line %d in %s: %s"
  13061. (org-current-line)
  13062. (buffer-file-name) sexp)
  13063. (sleep-for 2))))))
  13064. (cond ((stringp result) (split-string result "; "))
  13065. ((and (consp result)
  13066. (not (consp (cdr result)))
  13067. (stringp (cdr result))) (cdr result))
  13068. ((and (consp result)
  13069. (stringp (car result))) result)
  13070. (result entry))))
  13071. (defun org-diary-to-ical-string (frombuf)
  13072. "Get iCalendar entries from diary entries in buffer FROMBUF.
  13073. This uses the icalendar.el library."
  13074. (let* ((tmpdir temporary-file-directory)
  13075. (tmpfile (make-temp-name
  13076. (expand-file-name "orgics" tmpdir)))
  13077. buf rtn b e)
  13078. (with-current-buffer frombuf
  13079. (icalendar-export-region (point-min) (point-max) tmpfile)
  13080. (setq buf (find-buffer-visiting tmpfile))
  13081. (set-buffer buf)
  13082. (goto-char (point-min))
  13083. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  13084. (setq b (match-beginning 0)))
  13085. (goto-char (point-max))
  13086. (when (re-search-backward "^END:VEVENT" nil t)
  13087. (setq e (match-end 0)))
  13088. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  13089. (kill-buffer buf)
  13090. (delete-file tmpfile)
  13091. rtn))
  13092. (defun org-closest-date (start current prefer)
  13093. "Return closest date to CURRENT starting from START.
  13094. CURRENT and START are both time stamps.
  13095. When PREFER is `past', return a date that is either CURRENT or
  13096. past. When PREFER is `future', return a date that is either
  13097. CURRENT or future.
  13098. Only time stamps with a repeater are modified. Any other time
  13099. stamp stay unchanged. In any case, return value is an absolute
  13100. day number."
  13101. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  13102. ;; No repeater. Do not shift time stamp.
  13103. (time-to-days (org-time-string-to-time start))
  13104. (let ((value (string-to-number (match-string 1 start)))
  13105. (type (match-string 2 start)))
  13106. (if (= 0 value)
  13107. ;; Repeater with a 0-value is considered as void.
  13108. (time-to-days (org-time-string-to-time start))
  13109. (let* ((base (org-date-to-gregorian start))
  13110. (target (org-date-to-gregorian current))
  13111. (sday (calendar-absolute-from-gregorian base))
  13112. (cday (calendar-absolute-from-gregorian target))
  13113. n1 n2)
  13114. ;; If START is already past CURRENT, just return START.
  13115. (if (<= cday sday) sday
  13116. ;; Compute closest date before (N1) and closest date past
  13117. ;; (N2) CURRENT.
  13118. (pcase type
  13119. ("h"
  13120. (let ((missing-hours
  13121. (mod (+ (- (* 24 (- cday sday))
  13122. (nth 2 (org-parse-time-string start)))
  13123. org-extend-today-until)
  13124. value)))
  13125. (setf n1 (if (= missing-hours 0) cday
  13126. (- cday (1+ (/ missing-hours 24)))))
  13127. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  13128. ((or "d" "w")
  13129. (let ((value (if (equal type "w") (* 7 value) value)))
  13130. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  13131. (setf n2 (+ n1 value))))
  13132. ("m"
  13133. (let* ((add-months
  13134. (lambda (d n)
  13135. ;; Add N months to gregorian date D, i.e.,
  13136. ;; a list (MONTH DAY YEAR). Return a valid
  13137. ;; gregorian date.
  13138. (let ((m (+ (nth 0 d) n)))
  13139. (list (mod m 12)
  13140. (nth 1 d)
  13141. (+ (/ m 12) (nth 2 d))))))
  13142. (months ; Complete months to TARGET.
  13143. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  13144. (- (nth 0 target) (nth 0 base))
  13145. ;; If START's day is greater than
  13146. ;; TARGET's, remove incomplete month.
  13147. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  13148. value)
  13149. value))
  13150. (before (funcall add-months base months)))
  13151. (setf n1 (calendar-absolute-from-gregorian before))
  13152. (setf n2
  13153. (calendar-absolute-from-gregorian
  13154. (funcall add-months before value)))))
  13155. (_
  13156. (let* ((d (nth 1 base))
  13157. (m (nth 0 base))
  13158. (y (nth 2 base))
  13159. (years ; Complete years to TARGET.
  13160. (* (/ (- (nth 2 target)
  13161. y
  13162. ;; If START's month and day are
  13163. ;; greater than TARGET's, remove
  13164. ;; incomplete year.
  13165. (if (or (> (nth 0 target) m)
  13166. (and (= (nth 0 target) m)
  13167. (> (nth 1 target) d)))
  13168. 0
  13169. 1))
  13170. value)
  13171. value))
  13172. (before (list m d (+ y years))))
  13173. (setf n1 (calendar-absolute-from-gregorian before))
  13174. (setf n2 (calendar-absolute-from-gregorian
  13175. (list m d (+ (nth 2 before) value)))))))
  13176. ;; Handle PREFER parameter, if any.
  13177. (cond
  13178. ((eq prefer 'past) (if (= cday n2) n2 n1))
  13179. ((eq prefer 'future) (if (= cday n1) n1 n2))
  13180. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  13181. (defun org-date-to-gregorian (d)
  13182. "Turn any specification of date D into a Gregorian date for the calendar."
  13183. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  13184. ((and (listp d) (= (length d) 3)) d)
  13185. ((stringp d)
  13186. (let ((d (org-parse-time-string d)))
  13187. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  13188. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  13189. (defun org-timestamp-up (&optional arg)
  13190. "Increase the date item at the cursor by one.
  13191. If the cursor is on the year, change the year. If it is on the month,
  13192. the day or the time, change that. If the cursor is on the enclosing
  13193. bracket, change the timestamp type.
  13194. With prefix ARG, change by that many units."
  13195. (interactive "p")
  13196. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  13197. (defun org-timestamp-down (&optional arg)
  13198. "Decrease the date item at the cursor by one.
  13199. If the cursor is on the year, change the year. If it is on the month,
  13200. the day or the time, change that. If the cursor is on the enclosing
  13201. bracket, change the timestamp type.
  13202. With prefix ARG, change by that many units."
  13203. (interactive "p")
  13204. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  13205. (defun org-timestamp-up-day (&optional arg)
  13206. "Increase the date in the time stamp by one day.
  13207. With prefix ARG, change that many days."
  13208. (interactive "p")
  13209. (if (and (not (org-at-timestamp-p 'lax))
  13210. (org-at-heading-p))
  13211. (org-todo 'up)
  13212. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  13213. (defun org-timestamp-down-day (&optional arg)
  13214. "Decrease the date in the time stamp by one day.
  13215. With prefix ARG, change that many days."
  13216. (interactive "p")
  13217. (if (and (not (org-at-timestamp-p 'lax))
  13218. (org-at-heading-p))
  13219. (org-todo 'down)
  13220. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  13221. (defun org-at-timestamp-p (&optional extended)
  13222. "Non-nil if point is inside a timestamp.
  13223. By default, the function only consider syntactically valid active
  13224. timestamps. However, the caller may have a broader definition
  13225. for timestamps. As a consequence, optional argument EXTENDED can
  13226. be set to the following values
  13227. `inactive'
  13228. Include also syntactically valid inactive timestamps.
  13229. `agenda'
  13230. Include timestamps allowed in Agenda, i.e., those in
  13231. properties drawers, planning lines and clock lines.
  13232. `lax'
  13233. Ignore context. The function matches any part of the
  13234. document looking like a timestamp. This includes comments,
  13235. example blocks...
  13236. For backward-compatibility with Org 9.0, every other non-nil
  13237. value is equivalent to `inactive'.
  13238. When at a timestamp, return the position of the point as a symbol
  13239. among `bracket', `after', `year', `month', `hour', `minute',
  13240. `day' or a number of character from the last know part of the
  13241. time stamp. If diary sexp timestamps, any point inside the timestamp
  13242. is considered `day' (i.e. only `bracket', `day', and `after' return
  13243. values are possible).
  13244. When matching, the match groups are the following:
  13245. group 1: year, if any
  13246. group 2: month, if any
  13247. group 3: day number, if any
  13248. group 4: day name, if any
  13249. group 5: hours, if any
  13250. group 6: minutes, if any"
  13251. (let* ((regexp
  13252. (if extended
  13253. (if (eq extended 'agenda)
  13254. (rx-to-string
  13255. `(or (regexp ,org-ts-regexp3)
  13256. (regexp ,org-element--timestamp-regexp)))
  13257. org-ts-regexp3)
  13258. org-ts-regexp2))
  13259. (pos (point))
  13260. (match?
  13261. (let ((boundaries (org-in-regexp regexp)))
  13262. (save-match-data
  13263. (cond ((null boundaries) nil)
  13264. ((eq extended 'lax) t)
  13265. (t
  13266. (or (and (eq extended 'agenda)
  13267. (or (org-at-planning-p)
  13268. (org-at-property-p)
  13269. (and (bound-and-true-p
  13270. org-agenda-include-inactive-timestamps)
  13271. (org-at-clock-log-p))))
  13272. (eq 'timestamp
  13273. (save-excursion
  13274. (when (= pos (cdr boundaries)) (forward-char -1))
  13275. (org-element-type (org-element-context)))))))))))
  13276. (cond
  13277. ((not match?) nil)
  13278. ((= pos (match-beginning 0)) 'bracket)
  13279. ;; Distinguish location right before the closing bracket from
  13280. ;; right after it.
  13281. ((= pos (1- (match-end 0))) 'bracket)
  13282. ((= pos (match-end 0)) 'after)
  13283. ((org-pos-in-match-range pos 2) 'year)
  13284. ((org-pos-in-match-range pos 3) 'month)
  13285. ((org-pos-in-match-range pos 7) 'hour)
  13286. ((org-pos-in-match-range pos 8) 'minute)
  13287. ((or (org-pos-in-match-range pos 4)
  13288. (org-pos-in-match-range pos 5)) 'day)
  13289. ((and (or (match-end 8) (match-end 5))
  13290. (> pos (or (match-end 8) (match-end 5)))
  13291. (< pos (match-end 0)))
  13292. (- pos (or (match-end 8) (match-end 5))))
  13293. (t 'day))))
  13294. (defun org-toggle-timestamp-type ()
  13295. "Toggle the type (<active> or [inactive]) of a time stamp."
  13296. (interactive)
  13297. (when (org-at-timestamp-p 'lax)
  13298. (let ((beg (match-beginning 0)) (end (match-end 0))
  13299. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  13300. (save-excursion
  13301. (goto-char beg)
  13302. (while (re-search-forward "[][<>]" end t)
  13303. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  13304. t t)))
  13305. (message "Timestamp is now %sactive"
  13306. (if (equal (char-after beg) ?<) "" "in")))))
  13307. (defun org-at-clock-log-p ()
  13308. "Non-nil if point is on a clock log line."
  13309. (and (org-match-line org-clock-line-re)
  13310. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  13311. (defvar org-clock-history) ; defined in org-clock.el
  13312. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  13313. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  13314. "Change the date in the time stamp at point.
  13315. The date is changed by N times WHAT. WHAT can be `day', `month',
  13316. `year', `hour', or `minute'. If WHAT is not given, the cursor
  13317. position in the timestamp determines what is changed.
  13318. When optional argument UPDOWN is non-nil, minutes are rounded
  13319. according to `org-time-stamp-rounding-minutes'.
  13320. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like
  13321. \"--2d\"."
  13322. (let ((origin (point))
  13323. (timestamp? (org-at-timestamp-p 'lax))
  13324. origin-cat
  13325. with-hm inactive
  13326. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  13327. extra rem
  13328. ts time time0 fixnext clrgx)
  13329. (unless timestamp? (user-error "Not at a timestamp"))
  13330. (if (and (not what) (eq timestamp? 'bracket))
  13331. (org-toggle-timestamp-type)
  13332. ;; Point isn't on brackets. Remember the part of the time-stamp
  13333. ;; the point was in. Indeed, size of time-stamps may change,
  13334. ;; but point must be kept in the same category nonetheless.
  13335. (setq origin-cat timestamp?)
  13336. (when (and (not what) (not (eq timestamp? 'day))
  13337. org-display-custom-times
  13338. (get-text-property (point) 'display)
  13339. (not (get-text-property (1- (point)) 'display)))
  13340. (setq timestamp? 'day))
  13341. (setq timestamp? (or what timestamp?)
  13342. inactive (= (char-after (match-beginning 0)) ?\[)
  13343. ts (match-string 0))
  13344. (replace-match "")
  13345. (when (string-match
  13346. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  13347. ts)
  13348. (setq extra (match-string 1 ts))
  13349. (when suppress-tmp-delay
  13350. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  13351. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  13352. (setq with-hm t))
  13353. (setq time0 (org-parse-time-string ts))
  13354. (when (and updown
  13355. (eq timestamp? 'minute)
  13356. (not current-prefix-arg))
  13357. ;; This looks like s-up and s-down. Change by one rounding step.
  13358. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  13359. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  13360. (setcar (cdr time0) (+ (nth 1 time0)
  13361. (if (> n 0) (- rem) (- dm rem))))))
  13362. (setq time
  13363. (org-encode-time
  13364. (apply #'list
  13365. (or (car time0) 0)
  13366. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  13367. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  13368. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  13369. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  13370. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  13371. (nthcdr 6 time0))))
  13372. (when (and (memq timestamp? '(hour minute))
  13373. extra
  13374. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  13375. (setq extra (org-modify-ts-extra
  13376. extra
  13377. (if (eq timestamp? 'hour) 2 5)
  13378. n dm)))
  13379. (when (integerp timestamp?)
  13380. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  13381. (when (eq what 'calendar)
  13382. (let ((cal-date (org-get-date-from-calendar)))
  13383. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  13384. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  13385. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  13386. (setcar time0 (or (car time0) 0))
  13387. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  13388. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  13389. (setq time (org-encode-time time0))))
  13390. ;; Insert the new time-stamp, and ensure point stays in the same
  13391. ;; category as before (i.e. not after the last position in that
  13392. ;; category).
  13393. (let ((pos (point)))
  13394. ;; Stay before inserted string. `save-excursion' is of no use.
  13395. (setq org-last-changed-timestamp
  13396. (org-insert-time-stamp time with-hm inactive nil nil extra))
  13397. (goto-char pos))
  13398. (save-match-data
  13399. (looking-at org-ts-regexp3)
  13400. (goto-char
  13401. (pcase origin-cat
  13402. ;; `day' category ends before `hour' if any, or at the end
  13403. ;; of the day name.
  13404. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  13405. (`hour (min (match-end 7) origin))
  13406. (`minute (min (1- (match-end 8)) origin))
  13407. ((pred integerp) (min (1- (match-end 0)) origin))
  13408. ;; Point was right after the time-stamp. However, the
  13409. ;; time-stamp length might have changed, so refer to
  13410. ;; (match-end 0) instead.
  13411. (`after (match-end 0))
  13412. ;; `year' and `month' have both fixed size: point couldn't
  13413. ;; have moved into another part.
  13414. (_ origin))))
  13415. ;; Update clock if on a CLOCK line.
  13416. (org-clock-update-time-maybe)
  13417. ;; Maybe adjust the closest clock in `org-clock-history'
  13418. (when org-clock-adjust-closest
  13419. (if (not (and (org-at-clock-log-p)
  13420. (< 1 (length (delq nil (mapcar 'marker-position
  13421. org-clock-history))))))
  13422. (message "No clock to adjust")
  13423. (cond ((save-excursion ; fix previous clock?
  13424. (re-search-backward org-ts-regexp0 nil t)
  13425. (looking-back (concat org-clock-string " \\[")
  13426. (line-beginning-position)))
  13427. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  13428. ((save-excursion ; fix next clock?
  13429. (re-search-backward org-ts-regexp0 nil t)
  13430. (looking-at (concat org-ts-regexp0 "\\] =>")))
  13431. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  13432. (save-window-excursion
  13433. ;; Find closest clock to point, adjust the previous/next one in history
  13434. (let* ((p (save-excursion (org-back-to-heading t)))
  13435. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  13436. (clfixnth
  13437. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  13438. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  13439. (if (not clfixpos)
  13440. (message "No clock to adjust")
  13441. (save-excursion
  13442. (org-goto-marker-or-bmk clfixpos)
  13443. (org-fold-show-subtree)
  13444. (when (re-search-forward clrgx nil t)
  13445. (goto-char (match-beginning 1))
  13446. (let (org-clock-adjust-closest)
  13447. (org-timestamp-change n timestamp? updown))
  13448. (message "Clock adjusted in %s for heading: %s"
  13449. (file-name-nondirectory (buffer-file-name))
  13450. (org-get-heading t t)))))))))
  13451. ;; Try to recenter the calendar window, if any.
  13452. (when (and org-calendar-follow-timestamp-change
  13453. (get-buffer-window "*Calendar*" t)
  13454. (memq timestamp? '(day month year)))
  13455. (org-recenter-calendar (time-to-days time))))))
  13456. (defun org-modify-ts-extra (s pos n dm)
  13457. "Change the different parts of the lead-time and repeat fields in timestamp."
  13458. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  13459. ng h m new rem)
  13460. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  13461. (cond
  13462. ((or (org-pos-in-match-range pos 2)
  13463. (org-pos-in-match-range pos 3))
  13464. (setq m (string-to-number (match-string 3 s))
  13465. h (string-to-number (match-string 2 s)))
  13466. (if (org-pos-in-match-range pos 2)
  13467. (setq h (+ h n))
  13468. (setq n (* dm (with-no-warnings (cl-signum n))))
  13469. (unless (= 0 (setq rem (% m dm)))
  13470. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  13471. (setq m (+ m n)))
  13472. (when (< m 0) (setq m (+ m 60) h (1- h)))
  13473. (when (> m 59) (setq m (- m 60) h (1+ h)))
  13474. (setq h (mod h 24))
  13475. (setq ng 1 new (format "-%02d:%02d" h m)))
  13476. ((org-pos-in-match-range pos 6)
  13477. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  13478. ((org-pos-in-match-range pos 5)
  13479. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  13480. ((org-pos-in-match-range pos 9)
  13481. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  13482. ((org-pos-in-match-range pos 8)
  13483. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  13484. (when ng
  13485. (setq s (concat
  13486. (substring s 0 (match-beginning ng))
  13487. new
  13488. (substring s (match-end ng))))))
  13489. s))
  13490. (defun org-recenter-calendar (d)
  13491. "If the calendar is visible, recenter it to date D."
  13492. (let ((cwin (get-buffer-window "*Calendar*" t)))
  13493. (when cwin
  13494. (let ((calendar-move-hook nil))
  13495. (with-selected-window cwin
  13496. (calendar-goto-date
  13497. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  13498. (defun org-goto-calendar (&optional arg)
  13499. "Go to the Emacs calendar at the current date.
  13500. If there is a time stamp in the current line, go to that date.
  13501. A prefix ARG can be used to force the current date."
  13502. (interactive "P")
  13503. (let ((calendar-move-hook nil)
  13504. (calendar-view-holidays-initially-flag nil)
  13505. (calendar-view-diary-initially-flag nil)
  13506. diff)
  13507. (when (or (org-at-timestamp-p 'lax)
  13508. (org-match-line (concat ".*" org-ts-regexp)))
  13509. (let ((d1 (time-to-days nil))
  13510. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  13511. (setq diff (- d2 d1))))
  13512. (calendar)
  13513. (calendar-goto-today)
  13514. (when (and diff (not arg)) (calendar-forward-day diff))))
  13515. (defun org-get-date-from-calendar ()
  13516. "Return a list (month day year) of date at point in calendar."
  13517. (with-current-buffer "*Calendar*"
  13518. (save-match-data
  13519. (calendar-cursor-to-date))))
  13520. (defun org-date-from-calendar ()
  13521. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  13522. If there is already a time stamp at the cursor position, update it."
  13523. (interactive)
  13524. (if (org-at-timestamp-p 'lax)
  13525. (org-timestamp-change 0 'calendar)
  13526. (let ((cal-date (org-get-date-from-calendar)))
  13527. (org-insert-time-stamp
  13528. (org-encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  13529. (defcustom org-image-actual-width t
  13530. "When non-nil, use the actual width of images when inlining them.
  13531. When set to a number, use imagemagick (when available) to set the
  13532. image's width to this value.
  13533. When set to a number in a list, try to get the width from any
  13534. #+ATTR.* keyword if it matches a width specification like
  13535. #+ATTR_HTML: :width 300px
  13536. and fall back on that number if none is found.
  13537. When set to nil, try to get the width from an #+ATTR.* keyword
  13538. and fall back on the original width if none is found.
  13539. When set to any other non-nil value, always use the image width.
  13540. This requires Emacs >= 24.1, built with imagemagick support."
  13541. :group 'org-appearance
  13542. :version "24.4"
  13543. :package-version '(Org . "8.0")
  13544. :type '(choice
  13545. (const :tag "Use the image width" t)
  13546. (integer :tag "Use a number of pixels")
  13547. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  13548. (const :tag "Use #+ATTR* or don't resize" nil)))
  13549. (defcustom org-agenda-inhibit-startup nil
  13550. "Inhibit startup when preparing agenda buffers.
  13551. When this variable is t, the initialization of the Org agenda
  13552. buffers is inhibited: e.g. the visibility state is not set, the
  13553. tables are not re-aligned, etc."
  13554. :type 'boolean
  13555. :version "24.3"
  13556. :group 'org-agenda)
  13557. (defcustom org-agenda-ignore-properties nil
  13558. "Avoid updating text properties when building the agenda.
  13559. Properties are used to prepare buffers for effort estimates,
  13560. appointments, statistics and subtree-local categories.
  13561. If you don't use these in the agenda, you can add them to this
  13562. list and agenda building will be a bit faster.
  13563. The value is a list, with zero or more of the symbols `effort', `appt',
  13564. `stats' or `category'."
  13565. :type '(set :greedy t
  13566. (const effort)
  13567. (const appt)
  13568. (const stats)
  13569. (const category))
  13570. :version "26.1"
  13571. :package-version '(Org . "8.3")
  13572. :group 'org-agenda)
  13573. ;;;; Files
  13574. (defun org-save-all-org-buffers ()
  13575. "Save all Org buffers without user confirmation."
  13576. (interactive)
  13577. (message "Saving all Org buffers...")
  13578. (save-some-buffers t (lambda () (and (derived-mode-p 'org-mode) t)))
  13579. (when (featurep 'org-id) (org-id-locations-save))
  13580. (message "Saving all Org buffers... done"))
  13581. (defun org-revert-all-org-buffers ()
  13582. "Revert all Org buffers.
  13583. Prompt for confirmation when there are unsaved changes.
  13584. Be sure you know what you are doing before letting this function
  13585. overwrite your changes.
  13586. This function is useful in a setup where one tracks Org files
  13587. with a version control system, to revert on one machine after pulling
  13588. changes from another. I believe the procedure must be like this:
  13589. 1. \\[org-save-all-org-buffers]
  13590. 2. Pull changes from the other machine, resolve conflicts
  13591. 3. \\[org-revert-all-org-buffers]"
  13592. (interactive)
  13593. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  13594. (user-error "Abort"))
  13595. (save-excursion
  13596. (save-window-excursion
  13597. (dolist (b (buffer-list))
  13598. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  13599. (with-current-buffer b buffer-file-name))
  13600. (pop-to-buffer-same-window b)
  13601. (revert-buffer t 'no-confirm)))
  13602. (when (and (featurep 'org-id) org-id-track-globally)
  13603. (org-id-locations-load)))))
  13604. ;;;; Agenda files
  13605. ;;;###autoload
  13606. (defun org-switchb (&optional arg)
  13607. "Switch between Org buffers.
  13608. With `\\[universal-argument]' prefix, restrict available buffers to files.
  13609. With `\\[universal-argument] \\[universal-argument]' \
  13610. prefix, restrict available buffers to agenda files."
  13611. (interactive "P")
  13612. (let ((blist (org-buffer-list
  13613. (cond ((equal arg '(4)) 'files)
  13614. ((equal arg '(16)) 'agenda)))))
  13615. (pop-to-buffer-same-window
  13616. (completing-read "Org buffer: "
  13617. (mapcar #'list (mapcar #'buffer-name blist))
  13618. nil t))))
  13619. (defun org-agenda-files (&optional unrestricted archives)
  13620. "Get the list of agenda files.
  13621. Optional UNRESTRICTED means return the full list even if a restriction
  13622. is currently in place.
  13623. When ARCHIVES is t, include all archive files that are really being
  13624. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  13625. `org-agenda-archives-mode' is t."
  13626. (let ((files
  13627. (cond
  13628. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  13629. ((stringp org-agenda-files) (org-read-agenda-file-list))
  13630. ((listp org-agenda-files) org-agenda-files)
  13631. (t (error "Invalid value of `org-agenda-files'")))))
  13632. (setq files (apply 'append
  13633. (mapcar (lambda (f)
  13634. (if (file-directory-p f)
  13635. (directory-files
  13636. f t org-agenda-file-regexp)
  13637. (list (expand-file-name f org-directory))))
  13638. files)))
  13639. (when org-agenda-skip-unavailable-files
  13640. (setq files (delq nil
  13641. (mapcar (lambda (file)
  13642. (and (file-readable-p file) file))
  13643. files))))
  13644. (when (or (eq archives t)
  13645. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  13646. (setq files (org-add-archive-files files)))
  13647. files))
  13648. (defun org-agenda-file-p (&optional file)
  13649. "Return non-nil, if FILE is an agenda file.
  13650. If FILE is omitted, use the file associated with the current
  13651. buffer."
  13652. (let ((fname (or file (buffer-file-name))))
  13653. (and fname
  13654. (member (file-truename fname)
  13655. (mapcar #'file-truename (org-agenda-files t))))))
  13656. (defun org-edit-agenda-file-list ()
  13657. "Edit the list of agenda files.
  13658. Depending on setup, this either uses customize to edit the variable
  13659. `org-agenda-files', or it visits the file that is holding the list. In the
  13660. latter case, the buffer is set up in a way that saving it automatically kills
  13661. the buffer and restores the previous window configuration."
  13662. (interactive)
  13663. (if (stringp org-agenda-files)
  13664. (let ((cw (current-window-configuration)))
  13665. (find-file org-agenda-files)
  13666. (setq-local org-window-configuration cw)
  13667. (add-hook 'after-save-hook
  13668. (lambda ()
  13669. (set-window-configuration
  13670. (prog1 org-window-configuration
  13671. (kill-buffer (current-buffer))))
  13672. (org-install-agenda-files-menu)
  13673. (message "New agenda file list installed"))
  13674. nil 'local)
  13675. (message "%s" (substitute-command-keys
  13676. "Edit list and finish with \\[save-buffer]")))
  13677. (customize-variable 'org-agenda-files)))
  13678. (defun org-store-new-agenda-file-list (list)
  13679. "Set new value for the agenda file list and save it correctly."
  13680. (if (stringp org-agenda-files)
  13681. (let ((fe (org-read-agenda-file-list t)) b u)
  13682. (while (setq b (find-buffer-visiting org-agenda-files))
  13683. (kill-buffer b))
  13684. (with-temp-file org-agenda-files
  13685. (insert
  13686. (mapconcat
  13687. (lambda (f) ;; Keep un-expanded entries.
  13688. (if (setq u (assoc f fe))
  13689. (cdr u)
  13690. f))
  13691. list "\n")
  13692. "\n")))
  13693. (let ((org-mode-hook nil) (org-inhibit-startup t)
  13694. (org-insert-mode-line-in-empty-file nil))
  13695. (setq org-agenda-files list)
  13696. (customize-save-variable 'org-agenda-files org-agenda-files))))
  13697. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  13698. "Read the list of agenda files from a file.
  13699. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  13700. filenames, used by `org-store-new-agenda-file-list' to write back
  13701. un-expanded file names."
  13702. (when (file-directory-p org-agenda-files)
  13703. (error "`org-agenda-files' cannot be a single directory"))
  13704. (when (stringp org-agenda-files)
  13705. (with-temp-buffer
  13706. (insert-file-contents org-agenda-files)
  13707. (mapcar
  13708. (lambda (f)
  13709. (let ((e (expand-file-name (substitute-in-file-name f)
  13710. org-directory)))
  13711. (if pair-with-expansion
  13712. (cons e f)
  13713. e)))
  13714. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  13715. ;;;###autoload
  13716. (defun org-cycle-agenda-files ()
  13717. "Cycle through the files in `org-agenda-files'.
  13718. If the current buffer visits an agenda file, find the next one in the list.
  13719. If the current buffer does not, find the first agenda file."
  13720. (interactive)
  13721. (let* ((fs (or (org-agenda-files t)
  13722. (user-error "No agenda files")))
  13723. (files (copy-sequence fs))
  13724. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  13725. file)
  13726. (when tcf
  13727. (while (and (setq file (pop files))
  13728. (not (equal (file-truename file) tcf)))))
  13729. (find-file (car (or files fs)))
  13730. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  13731. (defun org-agenda-file-to-front (&optional to-end)
  13732. "Move/add the current file to the top of the agenda file list.
  13733. If the file is not present in the list, it is added to the front. If it is
  13734. present, it is moved there. With optional argument TO-END, add/move to the
  13735. end of the list."
  13736. (interactive "P")
  13737. (let ((org-agenda-skip-unavailable-files nil)
  13738. (file-alist (mapcar (lambda (x)
  13739. (cons (file-truename x) x))
  13740. (org-agenda-files t)))
  13741. (ctf (file-truename
  13742. (or buffer-file-name
  13743. (user-error "Please save the current buffer to a file"))))
  13744. x had)
  13745. (setq x (assoc ctf file-alist) had x)
  13746. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  13747. (if to-end
  13748. (setq file-alist (append (delq x file-alist) (list x)))
  13749. (setq file-alist (cons x (delq x file-alist))))
  13750. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  13751. (org-install-agenda-files-menu)
  13752. (message "File %s to %s of agenda file list"
  13753. (if had "moved" "added") (if to-end "end" "front"))))
  13754. (defun org-remove-file (&optional file)
  13755. "Remove current file from the list of files in variable `org-agenda-files'.
  13756. These are the files which are being checked for agenda entries.
  13757. Optional argument FILE means use this file instead of the current."
  13758. (interactive)
  13759. (let* ((org-agenda-skip-unavailable-files nil)
  13760. (file (or file buffer-file-name
  13761. (user-error "Current buffer does not visit a file")))
  13762. (true-file (file-truename file))
  13763. (afile (abbreviate-file-name file))
  13764. (files (delq nil (mapcar
  13765. (lambda (x)
  13766. (unless (equal true-file
  13767. (file-truename x))
  13768. x))
  13769. (org-agenda-files t)))))
  13770. (if (not (= (length files) (length (org-agenda-files t))))
  13771. (progn
  13772. (org-store-new-agenda-file-list files)
  13773. (org-install-agenda-files-menu)
  13774. (message "Removed from Org Agenda list: %s" afile))
  13775. (message "File was not in list: %s (not removed)" afile))))
  13776. (defun org-file-menu-entry (file)
  13777. (vector file (list 'find-file file) t))
  13778. (defun org-check-agenda-file (file)
  13779. "Make sure FILE exists. If not, ask user what to do."
  13780. (unless (file-exists-p file)
  13781. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  13782. (abbreviate-file-name file))
  13783. (let ((r (downcase (read-char-exclusive))))
  13784. (cond
  13785. ((equal r ?r)
  13786. (org-remove-file file)
  13787. (throw 'nextfile t))
  13788. (t (user-error "Abort"))))))
  13789. (defun org-get-agenda-file-buffer (file)
  13790. "Get an agenda buffer visiting FILE.
  13791. If the buffer needs to be created, add it to the list of buffers
  13792. which might be released later."
  13793. (let ((buf (org-find-base-buffer-visiting file)))
  13794. (if buf
  13795. buf ; just return it
  13796. ;; Make a new buffer and remember it
  13797. (setq buf (find-file-noselect file))
  13798. (when buf (push buf org-agenda-new-buffers))
  13799. buf)))
  13800. (defun org-release-buffers (blist)
  13801. "Release all buffers in list, asking the user for confirmation when needed.
  13802. When a buffer is unmodified, it is just killed. When modified, it is saved
  13803. \(if the user agrees) and then killed."
  13804. (let (file)
  13805. (dolist (buf blist)
  13806. (setq file (buffer-file-name buf))
  13807. (when (and (buffer-modified-p buf)
  13808. file
  13809. (y-or-n-p (format "Save file %s? " file)))
  13810. (with-current-buffer buf (save-buffer)))
  13811. (kill-buffer buf))))
  13812. (defun org-agenda-prepare-buffers (files)
  13813. "Create buffers for all agenda files, protect archived trees and comments."
  13814. (interactive)
  13815. (let ((inhibit-read-only t)
  13816. (org-inhibit-startup org-agenda-inhibit-startup))
  13817. (setq org-tag-alist-for-agenda nil
  13818. org-tag-groups-alist-for-agenda nil)
  13819. (dolist (file files)
  13820. (catch 'nextfile
  13821. (with-current-buffer
  13822. (if (bufferp file)
  13823. file
  13824. (org-check-agenda-file file)
  13825. (org-get-agenda-file-buffer file))
  13826. (org-with-wide-buffer
  13827. (org-set-regexps-and-options 'tags-only)
  13828. (or (memq 'category org-agenda-ignore-properties)
  13829. (org-refresh-category-properties))
  13830. (or (memq 'stats org-agenda-ignore-properties)
  13831. (org-refresh-stats-properties))
  13832. (or (memq 'effort org-agenda-ignore-properties)
  13833. (unless org-element-use-cache
  13834. (org-refresh-effort-properties)))
  13835. (or (memq 'appt org-agenda-ignore-properties)
  13836. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  13837. (setq org-todo-keywords-for-agenda
  13838. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  13839. (setq org-done-keywords-for-agenda
  13840. (append org-done-keywords-for-agenda org-done-keywords))
  13841. (setq org-todo-keyword-alist-for-agenda
  13842. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  13843. (setq org-tag-alist-for-agenda
  13844. (org--tag-add-to-alist
  13845. org-tag-alist-for-agenda
  13846. org-current-tag-alist))
  13847. ;; Merge current file's tag groups into global
  13848. ;; `org-tag-groups-alist-for-agenda'.
  13849. (when org-group-tags
  13850. (dolist (alist org-tag-groups-alist)
  13851. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  13852. (if old
  13853. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  13854. (push alist org-tag-groups-alist-for-agenda)))))))))
  13855. (setq org-todo-keywords-for-agenda
  13856. (org-uniquify org-todo-keywords-for-agenda))
  13857. (setq org-todo-keyword-alist-for-agenda
  13858. (org-uniquify org-todo-keyword-alist-for-agenda))))
  13859. ;;;; CDLaTeX minor mode
  13860. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  13861. "Keymap for the minor `org-cdlatex-mode'.")
  13862. (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
  13863. (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
  13864. (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
  13865. (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
  13866. (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
  13867. (defvar org-cdlatex-texmathp-advice-is-done nil
  13868. "Flag remembering if we have applied the advice to texmathp already.")
  13869. (define-minor-mode org-cdlatex-mode
  13870. "Toggle the minor `org-cdlatex-mode'.
  13871. This mode supports entering LaTeX environment and math in LaTeX fragments
  13872. in Org mode.
  13873. \\{org-cdlatex-mode-map}"
  13874. :lighter " OCDL"
  13875. (when org-cdlatex-mode
  13876. (require 'cdlatex)
  13877. (run-hooks 'cdlatex-mode-hook)
  13878. (cdlatex-compute-tables))
  13879. (unless org-cdlatex-texmathp-advice-is-done
  13880. (setq org-cdlatex-texmathp-advice-is-done t)
  13881. (advice-add 'texmathp :around #'org--math-always-on)))
  13882. (defun org--math-always-on (orig-fun &rest args)
  13883. "Always return t in Org buffers.
  13884. This is because we want to insert math symbols without dollars even outside
  13885. the LaTeX math segments. If Org mode thinks that point is actually inside
  13886. an embedded LaTeX fragment, let `texmathp' do its job.
  13887. `\\[org-cdlatex-mode-map]'"
  13888. (interactive)
  13889. (cond
  13890. ((not (derived-mode-p 'org-mode)) (apply orig-fun args))
  13891. ((eq this-command 'cdlatex-math-symbol)
  13892. (setq texmathp-why '("cdlatex-math-symbol in org-mode" . 0))
  13893. t)
  13894. (t
  13895. (let ((p (org-inside-LaTeX-fragment-p)))
  13896. (when p ;; FIXME: Shouldn't we return t when `p' is nil?
  13897. (if (member (car p)
  13898. (plist-get org-format-latex-options :matchers))
  13899. (progn
  13900. (setq texmathp-why '("Org mode embedded math" . 0))
  13901. t)
  13902. (apply orig-fun args)))))))
  13903. (defun turn-on-org-cdlatex ()
  13904. "Unconditionally turn on `org-cdlatex-mode'."
  13905. (org-cdlatex-mode 1))
  13906. (defun org-try-cdlatex-tab ()
  13907. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  13908. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  13909. - inside a LaTeX fragment, or
  13910. - after the first word in a line, where an abbreviation expansion could
  13911. insert a LaTeX environment."
  13912. (when org-cdlatex-mode
  13913. (cond
  13914. ;; Before any word on the line: No expansion possible.
  13915. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  13916. ;; Just after first word on the line: Expand it. Make sure it
  13917. ;; cannot happen on headlines, though.
  13918. ((save-excursion
  13919. (skip-chars-backward "a-zA-Z0-9*")
  13920. (skip-chars-backward " \t")
  13921. (and (bolp) (not (org-at-heading-p))))
  13922. (cdlatex-tab) t)
  13923. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  13924. (defun org-cdlatex-underscore-caret (&optional _arg)
  13925. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  13926. Revert to the normal definition outside of these fragments."
  13927. (interactive "P")
  13928. (if (org-inside-LaTeX-fragment-p)
  13929. (call-interactively 'cdlatex-sub-superscript)
  13930. (let (org-cdlatex-mode)
  13931. (call-interactively (key-binding (vector last-input-event))))))
  13932. (defun org-cdlatex-math-modify (&optional _arg)
  13933. "Execute `cdlatex-math-modify' in LaTeX fragments.
  13934. Revert to the normal definition outside of these fragments."
  13935. (interactive "P")
  13936. (if (org-inside-LaTeX-fragment-p)
  13937. (call-interactively 'cdlatex-math-modify)
  13938. (let (org-cdlatex-mode)
  13939. (call-interactively (key-binding (vector last-input-event))))))
  13940. (defun org-cdlatex-environment-indent (&optional environment item)
  13941. "Execute `cdlatex-environment' and indent the inserted environment.
  13942. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  13943. The inserted environment is indented to current indentation
  13944. unless point is at the beginning of the line, in which the
  13945. environment remains unintended."
  13946. (interactive)
  13947. ;; cdlatex-environment always return nil. Therefore, capture output
  13948. ;; first and determine if an environment was selected.
  13949. (let* ((beg (point-marker))
  13950. (end (copy-marker (point) t))
  13951. (inserted (progn
  13952. (ignore-errors (cdlatex-environment environment item))
  13953. (< beg end)))
  13954. ;; Figure out how many lines to move forward after the
  13955. ;; environment has been inserted.
  13956. (lines (when inserted
  13957. (save-excursion
  13958. (- (cl-loop while (< beg (point))
  13959. with x = 0
  13960. do (forward-line -1)
  13961. (cl-incf x)
  13962. finally return x)
  13963. (if (progn (goto-char beg)
  13964. (and (progn (skip-chars-forward " \t") (eolp))
  13965. (progn (skip-chars-backward " \t") (bolp))))
  13966. 1 0)))))
  13967. (env (org-trim (delete-and-extract-region beg end))))
  13968. (when inserted
  13969. ;; Get indentation of next line unless at column 0.
  13970. (let ((ind (if (bolp) 0
  13971. (save-excursion
  13972. (org-return t)
  13973. (prog1 (current-indentation)
  13974. (when (progn (skip-chars-forward " \t") (eolp))
  13975. (delete-region beg (point)))))))
  13976. (bol (progn (skip-chars-backward " \t") (bolp))))
  13977. ;; Insert a newline before environment unless at column zero
  13978. ;; to "escape" the current line. Insert a newline if
  13979. ;; something is one the same line as \end{ENVIRONMENT}.
  13980. (insert
  13981. (concat (unless bol "\n") env
  13982. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  13983. (unless (zerop ind)
  13984. (save-excursion
  13985. (goto-char beg)
  13986. (while (< (point) end)
  13987. (unless (eolp) (indent-line-to ind))
  13988. (forward-line))))
  13989. (goto-char beg)
  13990. (forward-line lines)
  13991. (indent-line-to ind)))
  13992. (set-marker beg nil)
  13993. (set-marker end nil)))
  13994. ;;;; LaTeX fragments
  13995. (defun org-inside-LaTeX-fragment-p ()
  13996. "Test if point is inside a LaTeX fragment.
  13997. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  13998. sequence appearing also before point.
  13999. Even though the matchers for math are configurable, this function assumes
  14000. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  14001. delimiters are skipped when they have been removed by customization.
  14002. The return value is nil, or a cons cell with the delimiter and the
  14003. position of this delimiter.
  14004. This function does a reasonably good job, but can locally be fooled by
  14005. for example currency specifications. For example it will assume being in
  14006. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  14007. fragments that are properly closed, but during editing, we have to live
  14008. with the uncertainty caused by missing closing delimiters. This function
  14009. looks only before point, not after."
  14010. (catch 'exit
  14011. (let ((pos (point))
  14012. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  14013. (lim (progn
  14014. (re-search-backward (concat "^\\(" paragraph-start "\\)") nil
  14015. 'move)
  14016. (point)))
  14017. dd-on str (start 0) m re)
  14018. (goto-char pos)
  14019. (when dodollar
  14020. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  14021. re (nth 1 (assoc "$" org-latex-regexps)))
  14022. (while (string-match re str start)
  14023. (cond
  14024. ((= (match-end 0) (length str))
  14025. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  14026. ((= (match-end 0) (- (length str) 5))
  14027. (throw 'exit nil))
  14028. (t (setq start (match-end 0))))))
  14029. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  14030. (goto-char pos)
  14031. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  14032. (and (match-beginning 2) (throw 'exit nil))
  14033. ;; count $$
  14034. (while (re-search-backward "\\$\\$" lim t)
  14035. (setq dd-on (not dd-on)))
  14036. (goto-char pos)
  14037. (when dd-on (cons "$$" m))))))
  14038. (defun org-inside-latex-macro-p ()
  14039. "Is point inside a LaTeX macro or its arguments?"
  14040. (save-match-data
  14041. (org-in-regexp
  14042. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  14043. (defun org--make-preview-overlay (beg end image &optional imagetype)
  14044. "Build an overlay between BEG and END using IMAGE file.
  14045. Argument IMAGETYPE is the extension of the displayed image,
  14046. as a string. It defaults to \"png\"."
  14047. (let ((ov (make-overlay beg end))
  14048. (imagetype (or (intern imagetype) 'png)))
  14049. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  14050. (overlay-put ov 'evaporate t)
  14051. (overlay-put ov
  14052. 'modification-hooks
  14053. (list (lambda (o _flag _beg _end &optional _l)
  14054. (delete-overlay o))))
  14055. (overlay-put ov
  14056. 'display
  14057. (list 'image :type imagetype :file image :ascent 'center))))
  14058. (defun org-clear-latex-preview (&optional beg end)
  14059. "Remove all overlays with LaTeX fragment images in current buffer.
  14060. When optional arguments BEG and END are non-nil, remove all
  14061. overlays between them instead. Return a non-nil value when some
  14062. overlays were removed, nil otherwise."
  14063. (let ((overlays
  14064. (cl-remove-if-not
  14065. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  14066. (overlays-in (or beg (point-min)) (or end (point-max))))))
  14067. (mapc #'delete-overlay overlays)
  14068. overlays))
  14069. (defun org--latex-preview-region (beg end)
  14070. "Preview LaTeX fragments between BEG and END.
  14071. BEG and END are buffer positions."
  14072. (let ((file (buffer-file-name (buffer-base-buffer))))
  14073. (save-excursion
  14074. (org-format-latex
  14075. (concat org-preview-latex-image-directory "org-ltximg")
  14076. beg end
  14077. ;; Emacs cannot overlay images from remote hosts. Create it in
  14078. ;; `temporary-file-directory' instead.
  14079. (if (or (not file) (file-remote-p file))
  14080. temporary-file-directory
  14081. default-directory)
  14082. 'overlays nil 'forbuffer org-preview-latex-default-process))))
  14083. (defun org-latex-preview (&optional arg)
  14084. "Toggle preview of the LaTeX fragment at point.
  14085. If the cursor is on a LaTeX fragment, create the image and
  14086. overlay it over the source code, if there is none. Remove it
  14087. otherwise. If there is no fragment at point, display images for
  14088. all fragments in the current section. With an active region,
  14089. display images for all fragments in the region.
  14090. With a `\\[universal-argument]' prefix argument ARG, clear images \
  14091. for all fragments
  14092. in the current section.
  14093. With a `\\[universal-argument] \\[universal-argument]' prefix \
  14094. argument ARG, display image for all
  14095. fragments in the buffer.
  14096. With a `\\[universal-argument] \\[universal-argument] \
  14097. \\[universal-argument]' prefix argument ARG, clear image for all
  14098. fragments in the buffer."
  14099. (interactive "P")
  14100. (cond
  14101. ((not (display-graphic-p)) nil)
  14102. ;; Clear whole buffer.
  14103. ((equal arg '(64))
  14104. (org-clear-latex-preview (point-min) (point-max))
  14105. (message "LaTeX previews removed from buffer"))
  14106. ;; Preview whole buffer.
  14107. ((equal arg '(16))
  14108. (message "Creating LaTeX previews in buffer...")
  14109. (org--latex-preview-region (point-min) (point-max))
  14110. (message "Creating LaTeX previews in buffer... done."))
  14111. ;; Clear current section.
  14112. ((equal arg '(4))
  14113. (org-clear-latex-preview
  14114. (if (use-region-p)
  14115. (region-beginning)
  14116. (if (org-before-first-heading-p) (point-min)
  14117. (save-excursion
  14118. (org-with-limited-levels (org-back-to-heading t) (point)))))
  14119. (if (use-region-p)
  14120. (region-end)
  14121. (org-with-limited-levels (org-entry-end-position)))))
  14122. ((use-region-p)
  14123. (message "Creating LaTeX previews in region...")
  14124. (org--latex-preview-region (region-beginning) (region-end))
  14125. (message "Creating LaTeX previews in region... done."))
  14126. ;; Toggle preview on LaTeX code at point.
  14127. ((let ((datum (org-element-context)))
  14128. (and (memq (org-element-type datum) '(latex-environment latex-fragment))
  14129. (let ((beg (org-element-property :begin datum))
  14130. (end (org-element-property :end datum)))
  14131. (if (org-clear-latex-preview beg end)
  14132. (message "LaTeX preview removed")
  14133. (message "Creating LaTeX preview...")
  14134. (org--latex-preview-region beg end)
  14135. (message "Creating LaTeX preview... done."))
  14136. t))))
  14137. ;; Preview current section.
  14138. (t
  14139. (let ((beg (if (org-before-first-heading-p) (point-min)
  14140. (save-excursion
  14141. (org-with-limited-levels (org-back-to-heading t) (point)))))
  14142. (end (org-with-limited-levels (org-entry-end-position))))
  14143. (message "Creating LaTeX previews in section...")
  14144. (org--latex-preview-region beg end)
  14145. (message "Creating LaTeX previews in section... done.")))))
  14146. (defun org-format-latex
  14147. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  14148. "Replace LaTeX fragments with links to an image.
  14149. The function takes care of creating the replacement image.
  14150. Only consider fragments between BEG and END when those are
  14151. provided.
  14152. When optional argument OVERLAYS is non-nil, display the image on
  14153. top of the fragment instead of replacing it.
  14154. PROCESSING-TYPE is the conversion method to use, as a symbol.
  14155. Some of the options can be changed using the variable
  14156. `org-format-latex-options', which see."
  14157. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  14158. (unless (eq processing-type 'verbatim)
  14159. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  14160. (cnt 0)
  14161. checkdir-flag)
  14162. (goto-char (or beg (point-min)))
  14163. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  14164. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  14165. (overlay-recenter (or end (point-max))))
  14166. (while (re-search-forward math-regexp end t)
  14167. (unless (and overlays
  14168. (eq (get-char-property (point) 'org-overlay-type)
  14169. 'org-latex-overlay))
  14170. (let* ((context (org-element-context))
  14171. (type (org-element-type context)))
  14172. (when (memq type '(latex-environment latex-fragment))
  14173. (let ((block-type (eq type 'latex-environment))
  14174. (value (org-element-property :value context))
  14175. (beg (org-element-property :begin context))
  14176. (end (save-excursion
  14177. (goto-char (org-element-property :end context))
  14178. (skip-chars-backward " \r\t\n")
  14179. (point))))
  14180. (cond
  14181. ((eq processing-type 'mathjax)
  14182. ;; Prepare for MathJax processing.
  14183. (if (not (string-match "\\`\\$\\$?" value))
  14184. (goto-char end)
  14185. (delete-region beg end)
  14186. (if (string= (match-string 0 value) "$$")
  14187. (insert "\\[" (substring value 2 -2) "\\]")
  14188. (insert "\\(" (substring value 1 -1) "\\)"))))
  14189. ((eq processing-type 'html)
  14190. (goto-char beg)
  14191. (delete-region beg end)
  14192. (insert (org-format-latex-as-html value)))
  14193. ((assq processing-type org-preview-latex-process-alist)
  14194. ;; Process to an image.
  14195. (cl-incf cnt)
  14196. (goto-char beg)
  14197. (let* ((processing-info
  14198. (cdr (assq processing-type org-preview-latex-process-alist)))
  14199. (face (face-at-point))
  14200. ;; Get the colors from the face at point.
  14201. (fg
  14202. (let ((color (plist-get org-format-latex-options
  14203. :foreground)))
  14204. (if forbuffer
  14205. (cond
  14206. ((eq color 'auto)
  14207. (face-attribute face :foreground nil 'default))
  14208. ((eq color 'default)
  14209. (face-attribute 'default :foreground nil))
  14210. (t color))
  14211. color)))
  14212. (bg
  14213. (let ((color (plist-get org-format-latex-options
  14214. :background)))
  14215. (if forbuffer
  14216. (cond
  14217. ((eq color 'auto)
  14218. (face-attribute face :background nil 'default))
  14219. ((eq color 'default)
  14220. (face-attribute 'default :background nil))
  14221. (t color))
  14222. color)))
  14223. (hash (sha1 (prin1-to-string
  14224. (list org-format-latex-header
  14225. org-latex-default-packages-alist
  14226. org-latex-packages-alist
  14227. org-format-latex-options
  14228. forbuffer value fg bg))))
  14229. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  14230. (absprefix (expand-file-name prefix dir))
  14231. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  14232. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  14233. (sep (and block-type "\n\n"))
  14234. (link (concat sep "[[file:" linkfile "]]" sep))
  14235. (options
  14236. (org-combine-plists
  14237. org-format-latex-options
  14238. `(:foreground ,fg :background ,bg))))
  14239. (when msg (message msg cnt))
  14240. (unless checkdir-flag ; Ensure the directory exists.
  14241. (setq checkdir-flag t)
  14242. (let ((todir (file-name-directory absprefix)))
  14243. (unless (file-directory-p todir)
  14244. (make-directory todir t))))
  14245. (unless (file-exists-p movefile)
  14246. (org-create-formula-image
  14247. value movefile options forbuffer processing-type))
  14248. (if overlays
  14249. (progn
  14250. (dolist (o (overlays-in beg end))
  14251. (when (eq (overlay-get o 'org-overlay-type)
  14252. 'org-latex-overlay)
  14253. (delete-overlay o)))
  14254. (org--make-preview-overlay beg end movefile imagetype)
  14255. (goto-char end))
  14256. (delete-region beg end)
  14257. (insert
  14258. (org-add-props link
  14259. (list 'org-latex-src
  14260. (replace-regexp-in-string "\"" "" value)
  14261. 'org-latex-src-embed-type
  14262. (if block-type 'paragraph 'character)))))))
  14263. ((eq processing-type 'mathml)
  14264. ;; Process to MathML.
  14265. (unless (org-format-latex-mathml-available-p)
  14266. (user-error "LaTeX to MathML converter not configured"))
  14267. (cl-incf cnt)
  14268. (when msg (message msg cnt))
  14269. (goto-char beg)
  14270. (delete-region beg end)
  14271. (insert (org-format-latex-as-mathml
  14272. value block-type prefix dir)))
  14273. (t
  14274. (error "Unknown conversion process %s for LaTeX fragments"
  14275. processing-type)))))))))))
  14276. (defun org-create-math-formula (latex-frag &optional mathml-file)
  14277. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  14278. Use `org-latex-to-mathml-convert-command'. If the conversion is
  14279. successful, return the portion between \"<math...> </math>\"
  14280. elements otherwise return nil. When MATHML-FILE is specified,
  14281. write the results in to that file. When invoked as an
  14282. interactive command, prompt for LATEX-FRAG, with initial value
  14283. set to the current active region and echo the results for user
  14284. inspection."
  14285. (interactive (list (let ((frag (when (org-region-active-p)
  14286. (buffer-substring-no-properties
  14287. (region-beginning) (region-end)))))
  14288. (read-string "LaTeX Fragment: " frag nil frag))))
  14289. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  14290. (let* ((tmp-in-file
  14291. (let ((file (file-relative-name
  14292. (make-temp-name (expand-file-name "ltxmathml-in")))))
  14293. (write-region latex-frag nil file)
  14294. file))
  14295. (tmp-out-file (file-relative-name
  14296. (make-temp-name (expand-file-name "ltxmathml-out"))))
  14297. (cmd (format-spec
  14298. org-latex-to-mathml-convert-command
  14299. `((?j . ,(and org-latex-to-mathml-jar-file
  14300. (shell-quote-argument
  14301. (expand-file-name
  14302. org-latex-to-mathml-jar-file))))
  14303. (?I . ,(shell-quote-argument tmp-in-file))
  14304. (?i . ,latex-frag)
  14305. (?o . ,(shell-quote-argument tmp-out-file)))))
  14306. mathml shell-command-output)
  14307. (when (called-interactively-p 'any)
  14308. (unless (org-format-latex-mathml-available-p)
  14309. (user-error "LaTeX to MathML converter not configured")))
  14310. (message "Running %s" cmd)
  14311. (setq shell-command-output (shell-command-to-string cmd))
  14312. (setq mathml
  14313. (when (file-readable-p tmp-out-file)
  14314. (with-current-buffer (find-file-noselect tmp-out-file t)
  14315. (goto-char (point-min))
  14316. (when (re-search-forward
  14317. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  14318. (regexp-quote
  14319. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  14320. nil t)
  14321. (prog1 (match-string 0) (kill-buffer))))))
  14322. (cond
  14323. (mathml
  14324. (setq mathml
  14325. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  14326. (when mathml-file
  14327. (write-region mathml nil mathml-file))
  14328. (when (called-interactively-p 'any)
  14329. (message mathml)))
  14330. ((warn "LaTeX to MathML conversion failed")
  14331. (message shell-command-output)))
  14332. (delete-file tmp-in-file)
  14333. (when (file-exists-p tmp-out-file)
  14334. (delete-file tmp-out-file))
  14335. mathml))
  14336. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  14337. prefix &optional dir)
  14338. "Use `org-create-math-formula' but check local cache first."
  14339. (let* ((absprefix (expand-file-name prefix dir))
  14340. (print-length nil) (print-level nil)
  14341. (formula-id (concat
  14342. "formula-"
  14343. (sha1
  14344. (prin1-to-string
  14345. (list latex-frag
  14346. org-latex-to-mathml-convert-command)))))
  14347. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  14348. (formula-cache-dir (file-name-directory formula-cache)))
  14349. (unless (file-directory-p formula-cache-dir)
  14350. (make-directory formula-cache-dir t))
  14351. (unless (file-exists-p formula-cache)
  14352. (org-create-math-formula latex-frag formula-cache))
  14353. (if (file-exists-p formula-cache)
  14354. ;; Successful conversion. Return the link to MathML file.
  14355. (org-add-props
  14356. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  14357. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  14358. 'org-latex-src-embed-type (if latex-frag-type
  14359. 'paragraph 'character)))
  14360. ;; Failed conversion. Return the LaTeX fragment verbatim
  14361. latex-frag)))
  14362. (defun org-format-latex-as-html (latex-fragment)
  14363. "Convert LATEX-FRAGMENT to HTML.
  14364. This uses `org-latex-to-html-convert-command', which see."
  14365. (let ((cmd (format-spec org-latex-to-html-convert-command
  14366. `((?i . ,latex-fragment)))))
  14367. (message "Running %s" cmd)
  14368. (shell-command-to-string cmd)))
  14369. (defun org--get-display-dpi ()
  14370. "Get the DPI of the display.
  14371. The function assumes that the display has the same pixel width in
  14372. the horizontal and vertical directions."
  14373. (if (display-graphic-p)
  14374. (round (/ (display-pixel-height)
  14375. (/ (display-mm-height) 25.4)))
  14376. (error "Attempt to calculate the dpi of a non-graphic display")))
  14377. (defun org-create-formula-image
  14378. (string tofile options buffer &optional processing-type)
  14379. "Create an image from LaTeX source using external processes.
  14380. The LaTeX STRING is saved to a temporary LaTeX file, then
  14381. converted to an image file by process PROCESSING-TYPE defined in
  14382. `org-preview-latex-process-alist'. A nil value defaults to
  14383. `org-preview-latex-default-process'.
  14384. The generated image file is eventually moved to TOFILE.
  14385. The OPTIONS argument controls the size, foreground color and
  14386. background color of the generated image.
  14387. When BUFFER non-nil, this function is used for LaTeX previewing.
  14388. Otherwise, it is used to deal with LaTeX snippets showed in
  14389. a HTML file."
  14390. (let* ((processing-type (or processing-type
  14391. org-preview-latex-default-process))
  14392. (processing-info
  14393. (cdr (assq processing-type org-preview-latex-process-alist)))
  14394. (programs (plist-get processing-info :programs))
  14395. (error-message (or (plist-get processing-info :message) ""))
  14396. (image-input-type (plist-get processing-info :image-input-type))
  14397. (image-output-type (plist-get processing-info :image-output-type))
  14398. (post-clean (or (plist-get processing-info :post-clean)
  14399. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  14400. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  14401. (latex-header
  14402. (or (plist-get processing-info :latex-header)
  14403. (org-latex-make-preamble
  14404. (org-export-get-environment (org-export-get-backend 'latex))
  14405. org-format-latex-header
  14406. 'snippet)))
  14407. (latex-compiler (plist-get processing-info :latex-compiler))
  14408. (tmpdir temporary-file-directory)
  14409. (texfilebase (make-temp-name
  14410. (expand-file-name "orgtex" tmpdir)))
  14411. (texfile (concat texfilebase ".tex"))
  14412. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  14413. '(1.0 . 1.0)))
  14414. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  14415. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  14416. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  14417. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  14418. "Black"))
  14419. (bg (or (plist-get options (if buffer :background :html-background))
  14420. "Transparent"))
  14421. (image-converter
  14422. (or (and (string= bg "Transparent")
  14423. (plist-get processing-info :transparent-image-converter))
  14424. (plist-get processing-info :image-converter)))
  14425. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  14426. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  14427. (dolist (program programs)
  14428. (org-check-external-command program error-message))
  14429. (if (eq fg 'default)
  14430. (setq fg (org-latex-color :foreground))
  14431. (setq fg (org-latex-color-format fg)))
  14432. (setq bg (cond
  14433. ((eq bg 'default) (org-latex-color :background))
  14434. ((string= bg "Transparent") nil)
  14435. (t (org-latex-color-format bg))))
  14436. ;; Remove TeX \par at end of snippet to avoid trailing space.
  14437. (if (string-suffix-p string "\n")
  14438. (aset string (1- (length string)) ?%)
  14439. (setq string (concat string "%")))
  14440. (with-temp-file texfile
  14441. (insert latex-header)
  14442. (insert "\n\\begin{document}\n"
  14443. "\\definecolor{fg}{rgb}{" fg "}%\n"
  14444. (if bg
  14445. (concat "\\definecolor{bg}{rgb}{" bg "}%\n"
  14446. "\n\\pagecolor{bg}%\n")
  14447. "")
  14448. "\n{\\color{fg}\n"
  14449. string
  14450. "\n}\n"
  14451. "\n\\end{document}\n"))
  14452. (let* ((err-msg (format "Please adjust `%s' part of \
  14453. `org-preview-latex-process-alist'."
  14454. processing-type))
  14455. (image-input-file
  14456. (org-compile-file
  14457. texfile latex-compiler image-input-type err-msg log-buf))
  14458. (image-output-file
  14459. (org-compile-file
  14460. image-input-file image-converter image-output-type err-msg log-buf
  14461. `((?D . ,(shell-quote-argument (format "%s" dpi)))
  14462. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  14463. (copy-file image-output-file tofile 'replace)
  14464. (dolist (e post-clean)
  14465. (when (file-exists-p (concat texfilebase e))
  14466. (delete-file (concat texfilebase e))))
  14467. image-output-file)))
  14468. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  14469. "Fill a LaTeX header template TPL.
  14470. In the template, the following place holders will be recognized:
  14471. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  14472. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  14473. [PACKAGES] \\usepackage statements for PKG
  14474. [NO-PACKAGES] do not include PKG
  14475. [EXTRA] the string EXTRA
  14476. [NO-EXTRA] do not include EXTRA
  14477. For backward compatibility, if both the positive and the negative place
  14478. holder is missing, the positive one (without the \"NO-\") will be
  14479. assumed to be present at the end of the template.
  14480. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  14481. EXTRA is a string.
  14482. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  14483. (let (rpl (end ""))
  14484. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  14485. (setq rpl (if (or (match-end 1) (not def-pkg))
  14486. "" (org-latex-packages-to-string def-pkg snippets-p t))
  14487. tpl (replace-match rpl t t tpl))
  14488. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  14489. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  14490. (setq rpl (if (or (match-end 1) (not pkg))
  14491. "" (org-latex-packages-to-string pkg snippets-p t))
  14492. tpl (replace-match rpl t t tpl))
  14493. (when pkg (setq end
  14494. (concat end "\n"
  14495. (org-latex-packages-to-string pkg snippets-p)))))
  14496. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  14497. (setq rpl (if (or (match-end 1) (not extra))
  14498. "" (concat extra "\n"))
  14499. tpl (replace-match rpl t t tpl))
  14500. (when (and extra (string-match "\\S-" extra))
  14501. (setq end (concat end "\n" extra))))
  14502. (if (string-match "\\S-" end)
  14503. (concat tpl "\n" end)
  14504. tpl)))
  14505. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  14506. "Turn an alist of packages into a string with the \\usepackage macros."
  14507. (setq pkg (mapconcat (lambda(p)
  14508. (cond
  14509. ((stringp p) p)
  14510. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  14511. (format "%% Package %s omitted" (cadr p)))
  14512. ((equal "" (car p))
  14513. (format "\\usepackage{%s}" (cadr p)))
  14514. (t
  14515. (format "\\usepackage[%s]{%s}"
  14516. (car p) (cadr p)))))
  14517. pkg
  14518. "\n"))
  14519. (if newline (concat pkg "\n") pkg))
  14520. (defun org-dvipng-color (attr)
  14521. "Return a RGB color specification for dvipng."
  14522. (org-dvipng-color-format (face-attribute 'default attr nil)))
  14523. (defun org-dvipng-color-format (color-name)
  14524. "Convert COLOR-NAME to a RGB color value for dvipng."
  14525. (apply #'format "rgb %s %s %s"
  14526. (mapcar 'org-normalize-color
  14527. (color-values color-name))))
  14528. (defun org-latex-color (attr)
  14529. "Return a RGB color for the LaTeX color package."
  14530. (org-latex-color-format (face-attribute 'default attr nil)))
  14531. (defun org-latex-color-format (color-name)
  14532. "Convert COLOR-NAME to a RGB color value."
  14533. (apply #'format "%s,%s,%s"
  14534. (mapcar 'org-normalize-color
  14535. (color-values color-name))))
  14536. (defun org-normalize-color (value)
  14537. "Return string to be used as color value for an RGB component."
  14538. (format "%g" (/ value 65535.0)))
  14539. ;; Image display
  14540. (defvar-local org-inline-image-overlays nil)
  14541. (defun org-toggle-inline-images (&optional include-linked)
  14542. "Toggle the display of inline images.
  14543. INCLUDE-LINKED is passed to `org-display-inline-images'."
  14544. (interactive "P")
  14545. (if org-inline-image-overlays
  14546. (progn
  14547. (org-remove-inline-images)
  14548. (when (called-interactively-p 'interactive)
  14549. (message "Inline image display turned off")))
  14550. (org-display-inline-images include-linked)
  14551. (when (called-interactively-p 'interactive)
  14552. (message (if org-inline-image-overlays
  14553. (format "%d images displayed inline"
  14554. (length org-inline-image-overlays))
  14555. "No images to display inline")))))
  14556. (defun org-redisplay-inline-images ()
  14557. "Assure display of inline images and refresh them."
  14558. (interactive)
  14559. (org-toggle-inline-images)
  14560. (unless org-inline-image-overlays
  14561. (org-toggle-inline-images)))
  14562. ;; For without-x builds.
  14563. (declare-function image-refresh "image" (spec &optional frame))
  14564. (defcustom org-display-remote-inline-images 'skip
  14565. "How to display remote inline images.
  14566. Possible values of this option are:
  14567. skip Don't display remote images.
  14568. download Always download and display remote images.
  14569. cache Display remote images, and open them in separate buffers
  14570. for caching. Silently update the image buffer when a file
  14571. change is detected."
  14572. :group 'org-appearance
  14573. :package-version '(Org . "9.4")
  14574. :type '(choice
  14575. (const :tag "Ignore remote images" skip)
  14576. (const :tag "Always display remote images" download)
  14577. (const :tag "Display and silently update remote images" cache))
  14578. :safe #'symbolp)
  14579. (defun org--create-inline-image (file width)
  14580. "Create image located at FILE, or return nil.
  14581. WIDTH is the width of the image. The image may not be created
  14582. according to the value of `org-display-remote-inline-images'."
  14583. (let* ((remote? (file-remote-p file))
  14584. (file-or-data
  14585. (pcase org-display-remote-inline-images
  14586. ((guard (not remote?)) file)
  14587. (`download (with-temp-buffer
  14588. (set-buffer-multibyte nil)
  14589. (insert-file-contents-literally file)
  14590. (buffer-string)))
  14591. (`cache (let ((revert-without-query '(".")))
  14592. (with-current-buffer (find-file-noselect file)
  14593. (buffer-string))))
  14594. (`skip nil)
  14595. (other
  14596. (message "Invalid value of `org-display-remote-inline-images': %S"
  14597. other)
  14598. nil))))
  14599. (when file-or-data
  14600. (create-image file-or-data
  14601. (and (image-type-available-p 'imagemagick)
  14602. width
  14603. 'imagemagick)
  14604. remote?
  14605. :width width :scale 1))))
  14606. (defun org-display-inline-images (&optional include-linked refresh beg end)
  14607. "Display inline images.
  14608. An inline image is a link which follows either of these
  14609. conventions:
  14610. 1. Its path is a file with an extension matching return value
  14611. from `image-file-name-regexp' and it has no contents.
  14612. 2. Its description consists in a single link of the previous
  14613. type. In this case, that link must be a well-formed plain
  14614. or angle link, i.e., it must have an explicit \"file\" type.
  14615. Equip each image with the key-map `image-map'.
  14616. When optional argument INCLUDE-LINKED is non-nil, also links with
  14617. a text description part will be inlined. This can be nice for
  14618. a quick look at those images, but it does not reflect what
  14619. exported files will look like.
  14620. When optional argument REFRESH is non-nil, refresh existing
  14621. images between BEG and END. This will create new image displays
  14622. only if necessary.
  14623. BEG and END define the considered part. They default to the
  14624. buffer boundaries with possible narrowing."
  14625. (interactive "P")
  14626. (when (display-graphic-p)
  14627. (unless refresh
  14628. (org-remove-inline-images)
  14629. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  14630. (let ((end (or end (point-max))))
  14631. (org-with-point-at (or beg (point-min))
  14632. (let* ((case-fold-search t)
  14633. (file-extension-re (image-file-name-regexp))
  14634. (link-abbrevs (mapcar #'car
  14635. (append org-link-abbrev-alist-local
  14636. org-link-abbrev-alist)))
  14637. ;; Check absolute, relative file names and explicit
  14638. ;; "file:" links. Also check link abbreviations since
  14639. ;; some might expand to "file" links.
  14640. (file-types-re
  14641. (format "\\[\\[\\(?:file%s:\\|attachment:\\|[./~]\\)\\|\\]\\[\\(<?file:\\)"
  14642. (if (not link-abbrevs) ""
  14643. (concat "\\|" (regexp-opt link-abbrevs))))))
  14644. (while (re-search-forward file-types-re end t)
  14645. (let* ((link (org-element-lineage
  14646. (save-match-data (org-element-context))
  14647. '(link) t))
  14648. (linktype (org-element-property :type link))
  14649. (inner-start (match-beginning 1))
  14650. (path
  14651. (cond
  14652. ;; No link at point; no inline image.
  14653. ((not link) nil)
  14654. ;; File link without a description. Also handle
  14655. ;; INCLUDE-LINKED here since it should have
  14656. ;; precedence over the next case. I.e., if link
  14657. ;; contains filenames in both the path and the
  14658. ;; description, prioritize the path only when
  14659. ;; INCLUDE-LINKED is non-nil.
  14660. ((or (not (org-element-property :contents-begin link))
  14661. include-linked)
  14662. (and (or (equal "file" linktype)
  14663. (equal "attachment" linktype))
  14664. (org-element-property :path link)))
  14665. ;; Link with a description. Check if description
  14666. ;; is a filename. Even if Org doesn't have syntax
  14667. ;; for those -- clickable image -- constructs, fake
  14668. ;; them, as in `org-export-insert-image-links'.
  14669. ((not inner-start) nil)
  14670. (t
  14671. (org-with-point-at inner-start
  14672. (and (looking-at
  14673. (if (char-equal ?< (char-after inner-start))
  14674. org-link-angle-re
  14675. org-link-plain-re))
  14676. ;; File name must fill the whole
  14677. ;; description.
  14678. (= (org-element-property :contents-end link)
  14679. (match-end 0))
  14680. (match-string 2)))))))
  14681. (when (and path (string-match-p file-extension-re path))
  14682. (let ((file (if (equal "attachment" linktype)
  14683. (progn
  14684. (require 'org-attach)
  14685. (ignore-errors (org-attach-expand path)))
  14686. (expand-file-name path))))
  14687. (when (and file (file-exists-p file))
  14688. (let ((width (org-display-inline-image--width link))
  14689. (old (get-char-property-and-overlay
  14690. (org-element-property :begin link)
  14691. 'org-image-overlay)))
  14692. (if (and (car-safe old) refresh)
  14693. (image-refresh (overlay-get (cdr old) 'display))
  14694. (let ((image (org--create-inline-image file width)))
  14695. (when image
  14696. (let ((ov (make-overlay
  14697. (org-element-property :begin link)
  14698. (progn
  14699. (goto-char
  14700. (org-element-property :end link))
  14701. (skip-chars-backward " \t")
  14702. (point)))))
  14703. (overlay-put ov 'display image)
  14704. (overlay-put ov 'face 'default)
  14705. (overlay-put ov 'org-image-overlay t)
  14706. (overlay-put
  14707. ov 'modification-hooks
  14708. (list 'org-display-inline-remove-overlay))
  14709. (when (boundp 'image-map)
  14710. (overlay-put ov 'keymap image-map))
  14711. (push ov org-inline-image-overlays))))))))))))))))
  14712. (defvar visual-fill-column-width) ; Silence compiler warning
  14713. (defun org-display-inline-image--width (link)
  14714. "Determine the display width of the image LINK, in pixels.
  14715. - When `org-image-actual-width' is t, the image's pixel width is used.
  14716. - When `org-image-actual-width' is a number, that value will is used.
  14717. - When `org-image-actual-width' is nil or a list, the first :width attribute
  14718. set (if it exists) is used to set the image width. A width of X% is
  14719. divided by 100.
  14720. If no :width attribute is given and `org-image-actual-width' is a list with
  14721. a number as the car, then that number is used as the default value.
  14722. If the value is a float between 0 and 2, it interpreted as that proportion
  14723. of the text width in the buffer."
  14724. ;; Apply `org-image-actual-width' specifications.
  14725. (cond
  14726. ((eq org-image-actual-width t) nil)
  14727. ((listp org-image-actual-width)
  14728. (let* ((case-fold-search t)
  14729. (par (org-element-lineage link '(paragraph)))
  14730. (attr-re "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)")
  14731. (par-end (org-element-property :post-affiliated par))
  14732. ;; Try to find an attribute providing a :width.
  14733. (attr-width
  14734. (when (and par (org-with-point-at
  14735. (org-element-property :begin par)
  14736. (re-search-forward attr-re par-end t)))
  14737. (match-string 1)))
  14738. (width
  14739. (cond
  14740. ;; Treat :width t as if `org-image-actual-width' were t.
  14741. ((string= attr-width "t") nil)
  14742. ;; Fallback to `org-image-actual-width' if no interprable width is given.
  14743. ((or (null attr-width)
  14744. (string-match-p "\\`[^0-9]" attr-width))
  14745. (car org-image-actual-width))
  14746. ;; Convert numeric widths to numbers, converting percentages.
  14747. ((string-match-p "\\`[0-9.]+%" attr-width)
  14748. (/ (string-to-number attr-width) 100.0))
  14749. (t (string-to-number attr-width)))))
  14750. (if (and (floatp width) (<= 0.0 width 2.0))
  14751. ;; A float in [0,2] should be interpereted as this portion of
  14752. ;; the text width in the window. This works well with cases like
  14753. ;; #+attr_latex: :width 0.X\{line,page,column,etc.}width,
  14754. ;; as the "0.X" is pulled out as a float. We use 2 as the upper
  14755. ;; bound as cases such as 1.2\linewidth are feasible.
  14756. (round (* width
  14757. (window-pixel-width)
  14758. (/ (or (and (bound-and-true-p visual-fill-column-mode)
  14759. (or visual-fill-column-width auto-fill-function))
  14760. (when auto-fill-function fill-column)
  14761. (- (window-text-width) (line-number-display-width)))
  14762. (float (window-total-width)))))
  14763. width)))
  14764. ((numberp org-image-actual-width)
  14765. org-image-actual-width)
  14766. (t nil)))
  14767. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  14768. "Remove inline-display overlay if a corresponding region is modified."
  14769. (let ((inhibit-modification-hooks t))
  14770. (when (and ov after)
  14771. (delete ov org-inline-image-overlays)
  14772. (delete-overlay ov))))
  14773. (defun org-remove-inline-images ()
  14774. "Remove inline display of images."
  14775. (interactive)
  14776. (mapc #'delete-overlay org-inline-image-overlays)
  14777. (setq org-inline-image-overlays nil))
  14778. (defvar org-self-insert-command-undo-counter 0)
  14779. (defvar org-speed-command nil)
  14780. (defun org-fix-tags-on-the-fly ()
  14781. "Align tags in headline at point.
  14782. Unlike `org-align-tags', this function does nothing if point is
  14783. either not currently on a tagged headline or on a tag."
  14784. (when (and (org-match-line org-tag-line-re)
  14785. (< (point) (match-beginning 1)))
  14786. (org-align-tags)))
  14787. (defun org-self-insert-command (N)
  14788. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  14789. If the cursor is in a table looking at whitespace, the whitespace is
  14790. overwritten, and the table is not marked as requiring realignment."
  14791. (interactive "p")
  14792. (org-fold-check-before-invisible-edit 'insert)
  14793. (cond
  14794. ((and org-use-speed-commands
  14795. (let ((kv (this-command-keys-vector)))
  14796. (setq org-speed-command
  14797. (run-hook-with-args-until-success
  14798. 'org-speed-command-hook
  14799. (make-string 1 (aref kv (1- (length kv))))))))
  14800. (cond
  14801. ((commandp org-speed-command)
  14802. (setq this-command org-speed-command)
  14803. (call-interactively org-speed-command))
  14804. ((functionp org-speed-command)
  14805. (funcall org-speed-command))
  14806. ((consp org-speed-command)
  14807. (eval org-speed-command t))
  14808. (t (let (org-use-speed-commands)
  14809. (call-interactively 'org-self-insert-command)))))
  14810. ((and
  14811. (= N 1)
  14812. (not (org-region-active-p))
  14813. (org-at-table-p)
  14814. (progn
  14815. ;; Check if we blank the field, and if that triggers align.
  14816. (and (featurep 'org-table)
  14817. org-table-auto-blank-field
  14818. (memq last-command
  14819. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  14820. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  14821. ;; Got extra space, this field does not determine
  14822. ;; column width.
  14823. (let (org-table-may-need-update) (org-table-blank-field))
  14824. ;; No extra space, this field may determine column
  14825. ;; width.
  14826. (org-table-blank-field)))
  14827. t)
  14828. (looking-at "[^|\n]* |"))
  14829. ;; There is room for insertion without re-aligning the table.
  14830. (self-insert-command N)
  14831. (org-table-with-shrunk-field
  14832. (save-excursion
  14833. (skip-chars-forward "^|")
  14834. ;; Do not delete last space, which is
  14835. ;; `org-table-separator-space', but the regular space before
  14836. ;; it.
  14837. (delete-region (- (point) 2) (1- (point))))))
  14838. (t
  14839. (setq org-table-may-need-update t)
  14840. (self-insert-command N)
  14841. (org-fix-tags-on-the-fly)
  14842. (when org-self-insert-cluster-for-undo
  14843. (if (not (eq last-command 'org-self-insert-command))
  14844. (setq org-self-insert-command-undo-counter 1)
  14845. (if (>= org-self-insert-command-undo-counter 20)
  14846. (setq org-self-insert-command-undo-counter 1)
  14847. (and (> org-self-insert-command-undo-counter 0)
  14848. buffer-undo-list (listp buffer-undo-list)
  14849. (not (cadr buffer-undo-list)) ; remove nil entry
  14850. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  14851. (setq org-self-insert-command-undo-counter
  14852. (1+ org-self-insert-command-undo-counter))))))))
  14853. (defun org-delete-backward-char (N)
  14854. "Like `delete-backward-char', insert whitespace at field end in tables.
  14855. When deleting backwards, in tables this function will insert whitespace in
  14856. front of the next \"|\" separator, to keep the table aligned. The table will
  14857. still be marked for re-alignment if the field did fill the entire column,
  14858. because, in this case the deletion might narrow the column."
  14859. (interactive "p")
  14860. (save-match-data
  14861. (org-fold-check-before-invisible-edit 'delete-backward)
  14862. (if (and (= N 1)
  14863. (not overwrite-mode)
  14864. (not (org-region-active-p))
  14865. (not (eq (char-before) ?|))
  14866. (save-excursion (skip-chars-backward " \t") (not (bolp)))
  14867. (looking-at-p ".*?|")
  14868. (org-at-table-p))
  14869. (progn (forward-char -1) (org-delete-char 1))
  14870. (backward-delete-char N)
  14871. (org-fix-tags-on-the-fly))))
  14872. (defun org-delete-char (N)
  14873. "Like `delete-char', but insert whitespace at field end in tables.
  14874. When deleting characters, in tables this function will insert whitespace in
  14875. front of the next \"|\" separator, to keep the table aligned. The table will
  14876. still be marked for re-alignment if the field did fill the entire column,
  14877. because, in this case the deletion might narrow the column."
  14878. (interactive "p")
  14879. (save-match-data
  14880. (org-fold-check-before-invisible-edit 'delete)
  14881. (cond
  14882. ((or (/= N 1)
  14883. (eq (char-after) ?|)
  14884. (save-excursion (skip-chars-backward " \t") (bolp))
  14885. (not (org-at-table-p)))
  14886. (delete-char N)
  14887. (org-fix-tags-on-the-fly))
  14888. ((looking-at ".\\(.*?\\)|")
  14889. (let* ((update? org-table-may-need-update)
  14890. (noalign (looking-at-p ".*? |")))
  14891. (delete-char 1)
  14892. (org-table-with-shrunk-field
  14893. (save-excursion
  14894. ;; Last space is `org-table-separator-space', so insert
  14895. ;; a regular one before it instead.
  14896. (goto-char (- (match-end 0) 2))
  14897. (insert " ")))
  14898. ;; If there were two spaces at the end, this field does not
  14899. ;; determine the width of the column.
  14900. (when noalign (setq org-table-may-need-update update?))))
  14901. (t
  14902. (delete-char N)))))
  14903. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  14904. (put 'org-self-insert-command 'delete-selection
  14905. (lambda ()
  14906. (not (run-hook-with-args-until-success
  14907. 'self-insert-uses-region-functions))))
  14908. (put 'orgtbl-self-insert-command 'delete-selection
  14909. (lambda ()
  14910. (not (run-hook-with-args-until-success
  14911. 'self-insert-uses-region-functions))))
  14912. (put 'org-delete-char 'delete-selection 'supersede)
  14913. (put 'org-delete-backward-char 'delete-selection 'supersede)
  14914. (put 'org-yank 'delete-selection 'yank)
  14915. (put 'org-return 'delete-selection t)
  14916. ;; Make `flyspell-mode' delay after some commands
  14917. (put 'org-self-insert-command 'flyspell-delayed t)
  14918. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  14919. (put 'org-delete-char 'flyspell-delayed t)
  14920. (put 'org-delete-backward-char 'flyspell-delayed t)
  14921. ;; Make pabbrev-mode expand after Org mode commands
  14922. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  14923. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  14924. (defun org-transpose-words ()
  14925. "Transpose words for Org.
  14926. This uses the `org-mode-transpose-word-syntax-table' syntax
  14927. table, which interprets characters in `org-emphasis-alist' as
  14928. word constituents."
  14929. (interactive)
  14930. (with-syntax-table org-mode-transpose-word-syntax-table
  14931. (call-interactively 'transpose-words)))
  14932. (defvar org-ctrl-c-ctrl-c-hook nil
  14933. "Hook for functions attaching themselves to `C-c C-c'.
  14934. This can be used to add additional functionality to the `C-c C-c'
  14935. key which executes context-dependent commands. This hook is run
  14936. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  14937. run after the last test.
  14938. Each function will be called with no arguments. The function
  14939. must check if the context is appropriate for it to act. If yes,
  14940. it should do its thing and then return a non-nil value. If the
  14941. context is wrong, just do nothing and return nil.")
  14942. (defvar org-ctrl-c-ctrl-c-final-hook nil
  14943. "Hook for functions attaching themselves to `C-c C-c'.
  14944. This can be used to add additional functionality to the `C-c C-c'
  14945. key which executes context-dependent commands. This hook is run
  14946. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  14947. before the first test.
  14948. Each function will be called with no arguments. The function
  14949. must check if the context is appropriate for it to act. If yes,
  14950. it should do its thing and then return a non-nil value. If the
  14951. context is wrong, just do nothing and return nil.")
  14952. (defvar org-tab-after-check-for-table-hook nil
  14953. "Hook for functions to attach themselves to TAB.
  14954. See `org-ctrl-c-ctrl-c-hook' for more information.
  14955. This hook runs after it has been established that the cursor is not in a
  14956. table, but before checking if the cursor is in a headline or if global cycling
  14957. should be done.
  14958. If any function in this hook returns t, not other actions like visibility
  14959. cycling will be done.")
  14960. (defvar org-tab-after-check-for-cycling-hook nil
  14961. "Hook for functions to attach themselves to TAB.
  14962. See `org-ctrl-c-ctrl-c-hook' for more information.
  14963. This hook runs after it has been established that not table field motion and
  14964. not visibility should be done because of current context. This is probably
  14965. the place where a package like yasnippets can hook in.")
  14966. (defvar org-tab-before-tab-emulation-hook nil
  14967. "Hook for functions to attach themselves to TAB.
  14968. See `org-ctrl-c-ctrl-c-hook' for more information.
  14969. This hook runs after every other options for TAB have been exhausted, but
  14970. before indentation and \t insertion takes place.")
  14971. (defvar org-metaleft-hook nil
  14972. "Hook for functions attaching themselves to `M-left'.
  14973. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14974. (defvar org-metaright-hook nil
  14975. "Hook for functions attaching themselves to `M-right'.
  14976. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14977. (defvar org-metaup-hook nil
  14978. "Hook for functions attaching themselves to `M-up'.
  14979. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14980. (defvar org-metadown-hook nil
  14981. "Hook for functions attaching themselves to `M-down'.
  14982. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14983. (defvar org-shiftmetaleft-hook nil
  14984. "Hook for functions attaching themselves to `M-S-left'.
  14985. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14986. (defvar org-shiftmetaright-hook nil
  14987. "Hook for functions attaching themselves to `M-S-right'.
  14988. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14989. (defvar org-shiftmetaup-hook nil
  14990. "Hook for functions attaching themselves to `M-S-up'.
  14991. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14992. (defvar org-shiftmetadown-hook nil
  14993. "Hook for functions attaching themselves to `M-S-down'.
  14994. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14995. (defvar org-metareturn-hook nil
  14996. "Hook for functions attaching themselves to `M-RET'.
  14997. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14998. (defvar org-shiftup-hook nil
  14999. "Hook for functions attaching themselves to `S-up'.
  15000. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15001. (defvar org-shiftup-final-hook nil
  15002. "Hook for functions attaching themselves to `S-up'.
  15003. This one runs after all other options except shift-select have been excluded.
  15004. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15005. (defvar org-shiftdown-hook nil
  15006. "Hook for functions attaching themselves to `S-down'.
  15007. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15008. (defvar org-shiftdown-final-hook nil
  15009. "Hook for functions attaching themselves to `S-down'.
  15010. This one runs after all other options except shift-select have been excluded.
  15011. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15012. (defvar org-shiftleft-hook nil
  15013. "Hook for functions attaching themselves to `S-left'.
  15014. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15015. (defvar org-shiftleft-final-hook nil
  15016. "Hook for functions attaching themselves to `S-left'.
  15017. This one runs after all other options except shift-select have been excluded.
  15018. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15019. (defvar org-shiftright-hook nil
  15020. "Hook for functions attaching themselves to `S-right'.
  15021. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15022. (defvar org-shiftright-final-hook nil
  15023. "Hook for functions attaching themselves to `S-right'.
  15024. This one runs after all other options except shift-select have been excluded.
  15025. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15026. (defun org-modifier-cursor-error ()
  15027. "Throw an error, a modified cursor command was applied in wrong context."
  15028. (user-error "This command is active in special context like tables, headlines or items"))
  15029. (defun org-shiftselect-error ()
  15030. "Throw an error because Shift-Cursor command was applied in wrong context."
  15031. (if (and (boundp 'shift-select-mode) shift-select-mode)
  15032. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  15033. (user-error "This command works only in special context like headlines or timestamps")))
  15034. (defun org-call-for-shift-select (cmd)
  15035. (let ((this-command-keys-shift-translated t))
  15036. (call-interactively cmd)))
  15037. (defun org-shifttab (&optional arg)
  15038. "Global visibility cycling or move to previous table field.
  15039. Call `org-table-previous-field' within a table.
  15040. When ARG is nil, cycle globally through visibility states.
  15041. When ARG is a numeric prefix, show contents of this level."
  15042. (interactive "P")
  15043. (cond
  15044. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  15045. ((integerp arg)
  15046. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  15047. (message "Content view to level: %d" arg)
  15048. (org-cycle-content (prefix-numeric-value arg2))
  15049. (org-cycle-show-empty-lines t)
  15050. (setq org-cycle-global-status 'overview)
  15051. (run-hook-with-args 'org-cycle-hook 'overview)))
  15052. (t (call-interactively 'org-cycle-global))))
  15053. (defun org-shiftmetaleft ()
  15054. "Promote subtree or delete table column.
  15055. Calls `org-promote-subtree', `org-outdent-item-tree', or
  15056. `org-table-delete-column', depending on context. See the
  15057. individual commands for more information."
  15058. (interactive)
  15059. (cond
  15060. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  15061. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  15062. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  15063. ((if (not (org-region-active-p)) (org-at-item-p)
  15064. (save-excursion (goto-char (region-beginning))
  15065. (org-at-item-p)))
  15066. (call-interactively 'org-outdent-item-tree))
  15067. (t (org-modifier-cursor-error))))
  15068. (defun org-shiftmetaright ()
  15069. "Demote subtree or insert table column.
  15070. Calls `org-demote-subtree', `org-indent-item-tree', or
  15071. `org-table-insert-column', depending on context. See the
  15072. individual commands for more information."
  15073. (interactive)
  15074. (cond
  15075. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  15076. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  15077. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  15078. ((if (not (org-region-active-p)) (org-at-item-p)
  15079. (save-excursion (goto-char (region-beginning))
  15080. (org-at-item-p)))
  15081. (call-interactively 'org-indent-item-tree))
  15082. (t (org-modifier-cursor-error))))
  15083. (defun org-shiftmetaup (&optional _arg)
  15084. "Drag the line at point up.
  15085. In a table, kill the current row.
  15086. On a clock timestamp, update the value of the timestamp like `S-<up>'
  15087. but also adjust the previous clocked item in the clock history.
  15088. Everywhere else, drag the line at point up."
  15089. (interactive "P")
  15090. (cond
  15091. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  15092. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  15093. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15094. (call-interactively 'org-timestamp-up)))
  15095. (t (call-interactively 'org-drag-line-backward))))
  15096. (defun org-shiftmetadown (&optional _arg)
  15097. "Drag the line at point down.
  15098. In a table, insert an empty row at the current line.
  15099. On a clock timestamp, update the value of the timestamp like `S-<down>'
  15100. but also adjust the previous clocked item in the clock history.
  15101. Everywhere else, drag the line at point down."
  15102. (interactive "P")
  15103. (cond
  15104. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  15105. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  15106. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15107. (call-interactively 'org-timestamp-down)))
  15108. (t (call-interactively 'org-drag-line-forward))))
  15109. (defsubst org-hidden-tree-error ()
  15110. (user-error
  15111. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  15112. (defun org-metaleft (&optional _arg)
  15113. "Promote heading, list item at point or move table column left.
  15114. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  15115. depending on context. With no specific context, calls the Emacs
  15116. default `backward-word'. See the individual commands for more
  15117. information.
  15118. This function runs the hook `org-metaleft-hook' as a first step,
  15119. and returns at first non-nil value."
  15120. (interactive "P")
  15121. (cond
  15122. ((run-hook-with-args-until-success 'org-metaleft-hook))
  15123. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  15124. ((org-with-limited-levels
  15125. (or (org-at-heading-p)
  15126. (and (org-region-active-p)
  15127. (save-excursion
  15128. (goto-char (region-beginning))
  15129. (org-at-heading-p)))))
  15130. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15131. (call-interactively 'org-do-promote))
  15132. ;; At an inline task.
  15133. ((org-at-heading-p)
  15134. (call-interactively 'org-inlinetask-promote))
  15135. ((or (org-at-item-p)
  15136. (and (org-region-active-p)
  15137. (save-excursion
  15138. (goto-char (region-beginning))
  15139. (org-at-item-p))))
  15140. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15141. (call-interactively 'org-outdent-item))
  15142. (t (call-interactively 'backward-word))))
  15143. (defun org-metaright (&optional _arg)
  15144. "Demote heading, list item at point or move table column right.
  15145. In front of a drawer or a block keyword, indent it correctly.
  15146. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  15147. `org-indent-drawer' or `org-indent-block' depending on context.
  15148. With no specific context, calls the Emacs default `forward-word'.
  15149. See the individual commands for more information.
  15150. This function runs the hook `org-metaright-hook' as a first step,
  15151. and returns at first non-nil value."
  15152. (interactive "P")
  15153. (cond
  15154. ((run-hook-with-args-until-success 'org-metaright-hook))
  15155. ((org-at-table-p) (call-interactively 'org-table-move-column))
  15156. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  15157. ((org-at-block-p) (call-interactively 'org-indent-block))
  15158. ((org-with-limited-levels
  15159. (or (org-at-heading-p)
  15160. (and (org-region-active-p)
  15161. (save-excursion
  15162. (goto-char (region-beginning))
  15163. (org-at-heading-p)))))
  15164. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15165. (call-interactively 'org-do-demote))
  15166. ;; At an inline task.
  15167. ((org-at-heading-p)
  15168. (call-interactively 'org-inlinetask-demote))
  15169. ((or (org-at-item-p)
  15170. (and (org-region-active-p)
  15171. (save-excursion
  15172. (goto-char (region-beginning))
  15173. (org-at-item-p))))
  15174. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15175. (call-interactively 'org-indent-item))
  15176. (t (call-interactively 'forward-word))))
  15177. (defun org-check-for-hidden (what)
  15178. "Check if there are hidden headlines/items in the current visual line.
  15179. WHAT can be either `headlines' or `items'. If the current line is
  15180. an outline or item heading and it has a folded subtree below it,
  15181. this function returns t, nil otherwise."
  15182. (let ((re (cond
  15183. ((eq what 'headlines) org-outline-regexp-bol)
  15184. ((eq what 'items) (org-item-beginning-re))
  15185. (t (error "This should not happen"))))
  15186. beg end)
  15187. (save-excursion
  15188. (catch 'exit
  15189. (unless (org-region-active-p)
  15190. (setq beg (point-at-bol))
  15191. (beginning-of-line 2)
  15192. (while (and (not (eobp)) ;; this is like `next-line'
  15193. (org-invisible-p (1- (point))))
  15194. (beginning-of-line 2))
  15195. (setq end (point))
  15196. (goto-char beg)
  15197. (goto-char (point-at-eol))
  15198. (setq end (max end (point)))
  15199. (while (re-search-forward re end t)
  15200. (when (org-invisible-p (match-beginning 0))
  15201. (throw 'exit t))))
  15202. nil))))
  15203. (defun org-metaup (&optional _arg)
  15204. "Move subtree up or move table row up.
  15205. Calls `org-move-subtree-up' or `org-table-move-row' or
  15206. `org-move-item-up', depending on context. See the individual commands
  15207. for more information."
  15208. (interactive "P")
  15209. (cond
  15210. ((run-hook-with-args-until-success 'org-metaup-hook))
  15211. ((org-region-active-p)
  15212. (let* ((a (save-excursion
  15213. (goto-char (region-beginning))
  15214. (line-beginning-position)))
  15215. (b (save-excursion
  15216. (goto-char (region-end))
  15217. (if (bolp) (1- (point)) (line-end-position))))
  15218. (c (save-excursion
  15219. (goto-char a)
  15220. (move-beginning-of-line 0)
  15221. (point)))
  15222. (d (save-excursion
  15223. (goto-char a)
  15224. (move-end-of-line 0)
  15225. (point))))
  15226. (transpose-regions a b c d)
  15227. (goto-char c)))
  15228. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  15229. ((and (featurep 'org-inlinetask)
  15230. (org-inlinetask-in-task-p))
  15231. (org-drag-element-backward))
  15232. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  15233. ((org-at-item-p) (call-interactively 'org-move-item-up))
  15234. (t (org-drag-element-backward))))
  15235. (defun org-metadown (&optional _arg)
  15236. "Move subtree down or move table row down.
  15237. Calls `org-move-subtree-down' or `org-table-move-row' or
  15238. `org-move-item-down', depending on context. See the individual
  15239. commands for more information."
  15240. (interactive "P")
  15241. (cond
  15242. ((run-hook-with-args-until-success 'org-metadown-hook))
  15243. ((org-region-active-p)
  15244. (let* ((a (save-excursion
  15245. (goto-char (region-beginning))
  15246. (line-beginning-position)))
  15247. (b (save-excursion
  15248. (goto-char (region-end))
  15249. (if (bolp) (1- (point)) (line-end-position))))
  15250. (c (save-excursion
  15251. (goto-char b)
  15252. (move-beginning-of-line (if (bolp) 1 2))
  15253. (point)))
  15254. (d (save-excursion
  15255. (goto-char b)
  15256. (move-end-of-line (if (bolp) 1 2))
  15257. (point))))
  15258. (transpose-regions a b c d)
  15259. (goto-char d)))
  15260. ((org-at-table-p) (call-interactively 'org-table-move-row))
  15261. ((and (featurep 'org-inlinetask)
  15262. (org-inlinetask-in-task-p))
  15263. (org-drag-element-forward))
  15264. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  15265. ((org-at-item-p) (call-interactively 'org-move-item-down))
  15266. (t (org-drag-element-forward))))
  15267. (defun org-shiftup (&optional arg)
  15268. "Act on current element according to context.
  15269. Call `org-timestamp-up' or `org-priority-up', or
  15270. `org-previous-item', or `org-table-move-cell-up'. See the
  15271. individual commands for more information."
  15272. (interactive "P")
  15273. (cond
  15274. ((run-hook-with-args-until-success 'org-shiftup-hook))
  15275. ((and org-support-shift-select (org-region-active-p))
  15276. (org-call-for-shift-select 'previous-line))
  15277. ((org-at-timestamp-p 'lax)
  15278. (call-interactively (if org-edit-timestamp-down-means-later
  15279. 'org-timestamp-down 'org-timestamp-up)))
  15280. ((and (not (eq org-support-shift-select 'always))
  15281. org-priority-enable-commands
  15282. (org-at-heading-p))
  15283. (call-interactively 'org-priority-up))
  15284. ((and (not org-support-shift-select) (org-at-item-p))
  15285. (call-interactively 'org-previous-item))
  15286. ((org-clocktable-try-shift 'up arg))
  15287. ((and (not (eq org-support-shift-select 'always))
  15288. (org-at-table-p))
  15289. (org-table-move-cell-up))
  15290. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  15291. (org-support-shift-select
  15292. (org-call-for-shift-select 'previous-line))
  15293. (t (org-shiftselect-error))))
  15294. (defun org-shiftdown (&optional arg)
  15295. "Act on current element according to context.
  15296. Call `org-timestamp-down' or `org-priority-down', or
  15297. `org-next-item', or `org-table-move-cell-down'. See the
  15298. individual commands for more information."
  15299. (interactive "P")
  15300. (cond
  15301. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  15302. ((and org-support-shift-select (org-region-active-p))
  15303. (org-call-for-shift-select 'next-line))
  15304. ((org-at-timestamp-p 'lax)
  15305. (call-interactively (if org-edit-timestamp-down-means-later
  15306. 'org-timestamp-up 'org-timestamp-down)))
  15307. ((and (not (eq org-support-shift-select 'always))
  15308. org-priority-enable-commands
  15309. (org-at-heading-p))
  15310. (call-interactively 'org-priority-down))
  15311. ((and (not org-support-shift-select) (org-at-item-p))
  15312. (call-interactively 'org-next-item))
  15313. ((org-clocktable-try-shift 'down arg))
  15314. ((and (not (eq org-support-shift-select 'always))
  15315. (org-at-table-p))
  15316. (org-table-move-cell-down))
  15317. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  15318. (org-support-shift-select
  15319. (org-call-for-shift-select 'next-line))
  15320. (t (org-shiftselect-error))))
  15321. (defun org-shiftright (&optional arg)
  15322. "Act on the current element according to context.
  15323. This does one of the following:
  15324. - switch a timestamp at point one day into the future
  15325. - on a headline, switch to the next TODO keyword
  15326. - on an item, switch entire list to the next bullet type
  15327. - on a property line, switch to the next allowed value
  15328. - on a clocktable definition line, move time block into the future
  15329. - in a table, move a single cell right"
  15330. (interactive "P")
  15331. (cond
  15332. ((run-hook-with-args-until-success 'org-shiftright-hook))
  15333. ((and org-support-shift-select (org-region-active-p))
  15334. (org-call-for-shift-select 'forward-char))
  15335. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  15336. ((and (not (eq org-support-shift-select 'always))
  15337. (org-at-heading-p))
  15338. (let ((org-inhibit-logging
  15339. (not org-treat-S-cursor-todo-selection-as-state-change))
  15340. (org-inhibit-blocking
  15341. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15342. (org-call-with-arg 'org-todo 'right)))
  15343. ((or (and org-support-shift-select
  15344. (not (eq org-support-shift-select 'always))
  15345. (org-at-item-bullet-p))
  15346. (and (not org-support-shift-select) (org-at-item-p)))
  15347. (org-call-with-arg 'org-cycle-list-bullet nil))
  15348. ((and (not (eq org-support-shift-select 'always))
  15349. (org-at-property-p))
  15350. (call-interactively 'org-property-next-allowed-value))
  15351. ((org-clocktable-try-shift 'right arg))
  15352. ((and (not (eq org-support-shift-select 'always))
  15353. (org-at-table-p))
  15354. (org-table-move-cell-right))
  15355. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  15356. (org-support-shift-select
  15357. (org-call-for-shift-select 'forward-char))
  15358. (t (org-shiftselect-error))))
  15359. (defun org-shiftleft (&optional arg)
  15360. "Act on current element according to context.
  15361. This does one of the following:
  15362. - switch a timestamp at point one day into the past
  15363. - on a headline, switch to the previous TODO keyword.
  15364. - on an item, switch entire list to the previous bullet type
  15365. - on a property line, switch to the previous allowed value
  15366. - on a clocktable definition line, move time block into the past
  15367. - in a table, move a single cell left"
  15368. (interactive "P")
  15369. (cond
  15370. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  15371. ((and org-support-shift-select (org-region-active-p))
  15372. (org-call-for-shift-select 'backward-char))
  15373. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  15374. ((and (not (eq org-support-shift-select 'always))
  15375. (org-at-heading-p))
  15376. (let ((org-inhibit-logging
  15377. (not org-treat-S-cursor-todo-selection-as-state-change))
  15378. (org-inhibit-blocking
  15379. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15380. (org-call-with-arg 'org-todo 'left)))
  15381. ((or (and org-support-shift-select
  15382. (not (eq org-support-shift-select 'always))
  15383. (org-at-item-bullet-p))
  15384. (and (not org-support-shift-select) (org-at-item-p)))
  15385. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  15386. ((and (not (eq org-support-shift-select 'always))
  15387. (org-at-property-p))
  15388. (call-interactively 'org-property-previous-allowed-value))
  15389. ((org-clocktable-try-shift 'left arg))
  15390. ((and (not (eq org-support-shift-select 'always))
  15391. (org-at-table-p))
  15392. (org-table-move-cell-left))
  15393. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  15394. (org-support-shift-select
  15395. (org-call-for-shift-select 'backward-char))
  15396. (t (org-shiftselect-error))))
  15397. (defun org-shiftcontrolright ()
  15398. "Switch to next TODO set."
  15399. (interactive)
  15400. (cond
  15401. ((and org-support-shift-select (org-region-active-p))
  15402. (org-call-for-shift-select 'forward-word))
  15403. ((and (not (eq org-support-shift-select 'always))
  15404. (org-at-heading-p))
  15405. (org-call-with-arg 'org-todo 'nextset))
  15406. (org-support-shift-select
  15407. (org-call-for-shift-select 'forward-word))
  15408. (t (org-shiftselect-error))))
  15409. (defun org-shiftcontrolleft ()
  15410. "Switch to previous TODO set."
  15411. (interactive)
  15412. (cond
  15413. ((and org-support-shift-select (org-region-active-p))
  15414. (org-call-for-shift-select 'backward-word))
  15415. ((and (not (eq org-support-shift-select 'always))
  15416. (org-at-heading-p))
  15417. (org-call-with-arg 'org-todo 'previousset))
  15418. (org-support-shift-select
  15419. (org-call-for-shift-select 'backward-word))
  15420. (t (org-shiftselect-error))))
  15421. (defun org-shiftcontrolup (&optional n)
  15422. "Change timestamps synchronously up in CLOCK log lines.
  15423. Optional argument N tells to change by that many units."
  15424. (interactive "P")
  15425. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  15426. (let (org-support-shift-select)
  15427. (org-clock-timestamps-up n))
  15428. (user-error "Not at a clock log")))
  15429. (defun org-shiftcontroldown (&optional n)
  15430. "Change timestamps synchronously down in CLOCK log lines.
  15431. Optional argument N tells to change by that many units."
  15432. (interactive "P")
  15433. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  15434. (let (org-support-shift-select)
  15435. (org-clock-timestamps-down n))
  15436. (user-error "Not at a clock log")))
  15437. (defun org-increase-number-at-point (&optional inc)
  15438. "Increment the number at point.
  15439. With an optional prefix numeric argument INC, increment using
  15440. this numeric value."
  15441. (interactive "p")
  15442. (if (not (number-at-point))
  15443. (user-error "Not on a number")
  15444. (unless inc (setq inc 1))
  15445. (let ((pos (point))
  15446. (beg (skip-chars-backward "-+^/*0-9eE."))
  15447. (end (skip-chars-forward "-+^/*0-9eE.")) nap)
  15448. (setq nap (buffer-substring-no-properties
  15449. (+ pos beg) (+ pos beg end)))
  15450. (delete-region (+ pos beg) (+ pos beg end))
  15451. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  15452. (when (org-at-table-p)
  15453. (org-table-align)
  15454. (org-table-end-of-field 1))))
  15455. (defun org-decrease-number-at-point (&optional inc)
  15456. "Decrement the number at point.
  15457. With an optional prefix numeric argument INC, decrement using
  15458. this numeric value."
  15459. (interactive "p")
  15460. (org-increase-number-at-point (- (or inc 1))))
  15461. (defun org-ctrl-c-ret ()
  15462. "Call `org-table-hline-and-move' or `org-insert-heading'."
  15463. (interactive)
  15464. (cond
  15465. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  15466. (t (call-interactively 'org-insert-heading))))
  15467. (defun org-copy-visible (beg end)
  15468. "Copy the visible parts of the region."
  15469. (interactive "r")
  15470. (let ((result ""))
  15471. (while (/= beg end)
  15472. (if (eq org-fold-core-style 'text-properties)
  15473. (progn
  15474. (while (org-invisible-p beg)
  15475. (setq beg (org-fold-next-visibility-change beg end)))
  15476. (let ((next (org-fold-next-visibility-change beg end)))
  15477. (setq result (concat result (buffer-substring beg next)))
  15478. (setq beg next)))
  15479. (when (invisible-p beg)
  15480. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  15481. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  15482. (setq result (concat result (buffer-substring beg next)))
  15483. (setq beg next))))
  15484. (setq deactivate-mark t)
  15485. (kill-new result)
  15486. (message "Visible strings have been copied to the kill ring.")))
  15487. (defun org-copy-special ()
  15488. "Copy region in table or copy current subtree.
  15489. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  15490. context. See the individual commands for more information."
  15491. (interactive)
  15492. (call-interactively
  15493. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  15494. (defun org-cut-special ()
  15495. "Cut region in table or cut current subtree.
  15496. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  15497. context. See the individual commands for more information."
  15498. (interactive)
  15499. (call-interactively
  15500. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  15501. (defun org-paste-special (arg)
  15502. "Paste rectangular region into table, or past subtree relative to level.
  15503. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  15504. See the individual commands for more information."
  15505. (interactive "P")
  15506. (if (org-at-table-p)
  15507. (org-table-paste-rectangle)
  15508. (org-paste-subtree arg)))
  15509. (defun org-edit-special (&optional arg)
  15510. "Call a special editor for the element at point.
  15511. When at a table, call the formula editor with `org-table-edit-formulas'.
  15512. When in a source code block, call `org-edit-src-code'.
  15513. When in a fixed-width region, call `org-edit-fixed-width-region'.
  15514. When in an export block, call `org-edit-export-block'.
  15515. When in a LaTeX environment, call `org-edit-latex-environment'.
  15516. When at an INCLUDE, SETUPFILE or BIBLIOGRAPHY keyword, visit the included file.
  15517. When at a footnote reference, call `org-edit-footnote-reference'.
  15518. When at a planning line call, `org-deadline' and/or `org-schedule'.
  15519. When at an active timestamp, call `org-time-stamp'.
  15520. When at an inactive timestamp, call `org-time-stamp-inactive'.
  15521. On a link, call `ffap' to visit the link at point.
  15522. Otherwise, return a user error."
  15523. (interactive "P")
  15524. (let ((element (org-element-at-point)))
  15525. (barf-if-buffer-read-only)
  15526. (pcase (org-element-type element)
  15527. (`src-block
  15528. (if (not arg) (org-edit-src-code)
  15529. (let* ((info (org-babel-get-src-block-info))
  15530. (lang (nth 0 info))
  15531. (params (nth 2 info))
  15532. (session (cdr (assq :session params))))
  15533. (if (not session) (org-edit-src-code)
  15534. ;; At a source block with a session and function called
  15535. ;; with an ARG: switch to the buffer related to the
  15536. ;; inferior process.
  15537. (switch-to-buffer
  15538. (funcall (intern (concat "org-babel-prep-session:" lang))
  15539. session params))))))
  15540. (`keyword
  15541. (unless (member (org-element-property :key element)
  15542. '("BIBLIOGRAPHY" "INCLUDE" "SETUPFILE"))
  15543. (user-error "No special environment to edit here"))
  15544. (let ((value (org-element-property :value element)))
  15545. (unless (org-string-nw-p value) (user-error "No file to edit"))
  15546. (let ((file (and (string-match "\\`\"\\(.*?\\)\"\\|\\S-+" value)
  15547. (or (match-string 1 value)
  15548. (match-string 0 value)))))
  15549. (when (org-url-p file)
  15550. (user-error "Files located with a URL cannot be edited"))
  15551. (org-link-open-from-string
  15552. (format "[[%s]]" (expand-file-name file))))))
  15553. (`table
  15554. (if (eq (org-element-property :type element) 'table.el)
  15555. (org-edit-table.el)
  15556. (call-interactively 'org-table-edit-formulas)))
  15557. ;; Only Org tables contain `table-row' type elements.
  15558. (`table-row (call-interactively 'org-table-edit-formulas))
  15559. (`example-block (org-edit-src-code))
  15560. (`export-block (org-edit-export-block))
  15561. (`fixed-width (org-edit-fixed-width-region))
  15562. (`latex-environment (org-edit-latex-environment))
  15563. (`planning
  15564. (let ((proplist (cadr element)))
  15565. (mapc #'call-interactively
  15566. (remq nil
  15567. (list
  15568. (when (plist-get proplist :deadline) #'org-deadline)
  15569. (when (plist-get proplist :scheduled) #'org-schedule))))))
  15570. (_
  15571. ;; No notable element at point. Though, we may be at a link or
  15572. ;; a footnote reference, which are objects. Thus, scan deeper.
  15573. (let ((context (org-element-context element)))
  15574. (pcase (org-element-type context)
  15575. (`footnote-reference (org-edit-footnote-reference))
  15576. (`inline-src-block (org-edit-inline-src-code))
  15577. (`latex-fragment (org-edit-latex-fragment))
  15578. (`timestamp (if (eq 'inactive (org-element-property :type context))
  15579. (call-interactively #'org-time-stamp-inactive)
  15580. (call-interactively #'org-time-stamp)))
  15581. (`link (call-interactively #'ffap))
  15582. (_ (user-error "No special environment to edit here"))))))))
  15583. (defun org-ctrl-c-ctrl-c (&optional arg)
  15584. "Set tags in headline, or update according to changed information at point.
  15585. This command does many different things, depending on context:
  15586. - If column view is active, in agenda or org buffers, quit it.
  15587. - If there are highlights, remove them.
  15588. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  15589. this is what we do.
  15590. - If the cursor is on a statistics cookie, update it.
  15591. - If the cursor is in a headline, in an agenda or an org buffer,
  15592. prompt for tags and insert them into the current line, aligned
  15593. to `org-tags-column'. When called with prefix arg, realign all
  15594. tags in the current buffer.
  15595. - If the cursor is in one of the special #+KEYWORD lines, this
  15596. triggers scanning the buffer for these lines and updating the
  15597. information.
  15598. - If the cursor is inside a table, realign the table. This command
  15599. works even if the automatic table editor has been turned off.
  15600. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  15601. the entire table.
  15602. - If the cursor is at a footnote reference or definition, jump to
  15603. the corresponding definition or references, respectively.
  15604. - If the cursor is a the beginning of a dynamic block, update it.
  15605. - If the current buffer is a capture buffer, close note and file it.
  15606. - If the cursor is on a <<<target>>>, update radio targets and
  15607. corresponding links in this buffer.
  15608. - If the cursor is on a numbered item in a plain list, renumber the
  15609. ordered list.
  15610. - If the cursor is on a checkbox, toggle it.
  15611. - If the cursor is on a code block, evaluate it. The variable
  15612. `org-confirm-babel-evaluate' can be used to control prompting
  15613. before code block evaluation, by default every code block
  15614. evaluation requires confirmation. Code block evaluation can be
  15615. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  15616. (interactive "P")
  15617. (cond
  15618. ((bound-and-true-p org-columns-overlays) (org-columns-quit))
  15619. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  15620. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  15621. (org-remove-occur-highlights)
  15622. (message "Temporary highlights/overlays removed from current buffer"))
  15623. ((and (local-variable-p 'org-finish-function)
  15624. (fboundp org-finish-function))
  15625. (funcall org-finish-function))
  15626. ((org-babel-hash-at-point))
  15627. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  15628. (t
  15629. (let* ((context
  15630. (org-element-lineage
  15631. (org-element-context)
  15632. ;; Limit to supported contexts.
  15633. '(babel-call clock dynamic-block footnote-definition
  15634. footnote-reference inline-babel-call inline-src-block
  15635. inlinetask item keyword node-property paragraph
  15636. plain-list planning property-drawer radio-target
  15637. src-block statistics-cookie table table-cell table-row
  15638. timestamp)
  15639. t))
  15640. (radio-list-p (org-at-radio-list-p))
  15641. (type (org-element-type context)))
  15642. ;; For convenience: at the first line of a paragraph on the same
  15643. ;; line as an item, apply function on that item instead.
  15644. (when (eq type 'paragraph)
  15645. (let ((parent (org-element-property :parent context)))
  15646. (when (and (eq (org-element-type parent) 'item)
  15647. (= (line-beginning-position)
  15648. (org-element-property :begin parent)))
  15649. (setq context parent)
  15650. (setq type 'item))))
  15651. ;; Act according to type of element or object at point.
  15652. ;;
  15653. ;; Do nothing on a blank line, except if it is contained in
  15654. ;; a source block. Hence, we first check if point is in such
  15655. ;; a block and then if it is at a blank line.
  15656. (pcase type
  15657. ((or `inline-src-block `src-block)
  15658. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  15659. (org-babel-eval-wipe-error-buffer)
  15660. (org-babel-execute-src-block
  15661. current-prefix-arg (org-babel-get-src-block-info nil context))))
  15662. ((guard (org-match-line "[ \t]*$"))
  15663. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  15664. (user-error
  15665. (substitute-command-keys
  15666. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  15667. ((or `babel-call `inline-babel-call)
  15668. (let ((info (org-babel-lob-get-info context)))
  15669. (when info (org-babel-execute-src-block nil info))))
  15670. (`clock (org-clock-update-time-maybe))
  15671. (`dynamic-block
  15672. (save-excursion
  15673. (goto-char (org-element-property :post-affiliated context))
  15674. (org-update-dblock)))
  15675. (`footnote-definition
  15676. (goto-char (org-element-property :post-affiliated context))
  15677. (call-interactively 'org-footnote-action))
  15678. (`footnote-reference (call-interactively #'org-footnote-action))
  15679. ((or `headline `inlinetask)
  15680. (save-excursion (goto-char (org-element-property :begin context))
  15681. (call-interactively #'org-set-tags-command)))
  15682. (`item
  15683. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  15684. ;; unconditionally, whereas `C-u' will toggle its presence.
  15685. ;; Without a universal argument, if the item has a checkbox,
  15686. ;; toggle it. Otherwise repair the list.
  15687. (if (or radio-list-p
  15688. (and (boundp org-list-checkbox-radio-mode)
  15689. org-list-checkbox-radio-mode))
  15690. (org-toggle-radio-button arg)
  15691. (let* ((box (org-element-property :checkbox context))
  15692. (struct (org-element-property :structure context))
  15693. (old-struct (copy-tree struct))
  15694. (parents (org-list-parents-alist struct))
  15695. (prevs (org-list-prevs-alist struct))
  15696. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  15697. (org-list-set-checkbox
  15698. (org-element-property :begin context) struct
  15699. (cond ((equal arg '(16)) "[-]")
  15700. ((and (not box) (equal arg '(4))) "[ ]")
  15701. ((or (not box) (equal arg '(4))) nil)
  15702. ((eq box 'on) "[ ]")
  15703. (t "[X]")))
  15704. ;; Mimic `org-list-write-struct' but with grabbing a return
  15705. ;; value from `org-list-struct-fix-box'.
  15706. (org-list-struct-fix-ind struct parents 2)
  15707. (org-list-struct-fix-item-end struct)
  15708. (org-list-struct-fix-bul struct prevs)
  15709. (org-list-struct-fix-ind struct parents)
  15710. (let ((block-item
  15711. (org-list-struct-fix-box struct parents prevs orderedp)))
  15712. (if (and box (equal struct old-struct))
  15713. (if (equal arg '(16))
  15714. (message "Checkboxes already reset")
  15715. (user-error "Cannot toggle this checkbox: %s"
  15716. (if (eq box 'on)
  15717. "all subitems checked"
  15718. "unchecked subitems")))
  15719. (org-list-struct-apply-struct struct old-struct)
  15720. (org-update-checkbox-count-maybe))
  15721. (when block-item
  15722. (message "Checkboxes were removed due to empty box at line %d"
  15723. (org-current-line block-item)))))))
  15724. (`plain-list
  15725. ;; At a plain list, with a double C-u argument, set
  15726. ;; checkboxes of each item to "[-]", whereas a single one
  15727. ;; will toggle their presence according to the state of the
  15728. ;; first item in the list. Without an argument, repair the
  15729. ;; list.
  15730. (if (or radio-list-p
  15731. (and (boundp org-list-checkbox-radio-mode)
  15732. org-list-checkbox-radio-mode))
  15733. (org-toggle-radio-button arg)
  15734. (let* ((begin (org-element-property :contents-begin context))
  15735. (struct (org-element-property :structure context))
  15736. (old-struct (copy-tree struct))
  15737. (first-box (save-excursion
  15738. (goto-char begin)
  15739. (looking-at org-list-full-item-re)
  15740. (match-string-no-properties 3)))
  15741. (new-box (cond ((equal arg '(16)) "[-]")
  15742. ((equal arg '(4)) (unless first-box "[ ]"))
  15743. ((equal first-box "[X]") "[ ]")
  15744. (t "[X]"))))
  15745. (cond
  15746. (arg
  15747. (dolist (pos
  15748. (org-list-get-all-items
  15749. begin struct (org-list-prevs-alist struct)))
  15750. (org-list-set-checkbox pos struct new-box)))
  15751. ((and first-box (eq (point) begin))
  15752. ;; For convenience, when point is at bol on the first
  15753. ;; item of the list and no argument is provided, simply
  15754. ;; toggle checkbox of that item, if any.
  15755. (org-list-set-checkbox begin struct new-box)))
  15756. (when (equal
  15757. (org-list-write-struct
  15758. struct (org-list-parents-alist struct) old-struct)
  15759. old-struct)
  15760. (message "Cannot update this checkbox"))
  15761. (org-update-checkbox-count-maybe))))
  15762. (`keyword
  15763. (let ((org-inhibit-startup-visibility-stuff t)
  15764. (org-startup-align-all-tables nil))
  15765. (when (boundp 'org-table-coordinate-overlays)
  15766. (mapc #'delete-overlay org-table-coordinate-overlays)
  15767. (setq org-table-coordinate-overlays nil))
  15768. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  15769. (message "Local setup has been refreshed"))
  15770. ((or `property-drawer `node-property)
  15771. (call-interactively #'org-property-action))
  15772. (`radio-target
  15773. (call-interactively #'org-update-radio-target-regexp))
  15774. (`statistics-cookie
  15775. (call-interactively #'org-update-statistics-cookies))
  15776. ((or `table `table-cell `table-row)
  15777. ;; At a table, generate a plot if on the #+plot line,
  15778. ;; recalculate every field and align it otherwise. Also
  15779. ;; send the table if necessary.
  15780. (cond
  15781. ((and (org-match-line "[ \t]*#\\+plot:")
  15782. (< (point) (org-element-property :post-affiliated context)))
  15783. (org-plot/gnuplot))
  15784. ;; If the table has a `table.el' type, just give up.
  15785. ((eq (org-element-property :type context) 'table.el)
  15786. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  15787. Use `\\[org-edit-special]' to edit table.el tables")))
  15788. ;; At a table row or cell, maybe recalculate line but always
  15789. ;; align table.
  15790. ((or (eq type 'table)
  15791. ;; Check if point is at a TBLFM line.
  15792. (and (eq type 'table-row)
  15793. (= (point) (org-element-property :end context))))
  15794. (save-excursion
  15795. (if (org-at-TBLFM-p)
  15796. (progn (require 'org-table)
  15797. (org-table-calc-current-TBLFM))
  15798. (goto-char (org-element-property :contents-begin context))
  15799. (org-call-with-arg 'org-table-recalculate (or arg t))
  15800. (orgtbl-send-table 'maybe))))
  15801. (t
  15802. (org-table-maybe-eval-formula)
  15803. (cond (arg (call-interactively #'org-table-recalculate))
  15804. ((org-table-maybe-recalculate-line))
  15805. (t (org-table-align))))))
  15806. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  15807. (org-timestamp-change 0 'day))
  15808. ((and `nil (guard (org-at-heading-p)))
  15809. ;; When point is on an unsupported object type, we can miss
  15810. ;; the fact that it also is at a heading. Handle it here.
  15811. (call-interactively #'org-set-tags-command))
  15812. ((guard
  15813. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  15814. (_
  15815. (user-error
  15816. (substitute-command-keys
  15817. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  15818. (defun org-mode-restart ()
  15819. "Restart `org-mode'."
  15820. (interactive)
  15821. (let ((indent-status (bound-and-true-p org-indent-mode)))
  15822. (funcall major-mode)
  15823. (hack-local-variables)
  15824. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  15825. (org-indent-mode -1))
  15826. (org-reset-file-cache))
  15827. (message "%s restarted" major-mode))
  15828. (defun org-kill-note-or-show-branches ()
  15829. "Abort storing current note, or show just branches."
  15830. (interactive)
  15831. (cond (org-finish-function
  15832. (let ((org-note-abort t)) (funcall org-finish-function)))
  15833. ((org-before-first-heading-p)
  15834. (org-fold-show-branches-buffer)
  15835. (org-fold-hide-archived-subtrees (point-min) (point-max)))
  15836. (t
  15837. (let ((beg (progn (org-back-to-heading) (point)))
  15838. (end (save-excursion (org-end-of-subtree t t) (point))))
  15839. (org-fold-hide-subtree)
  15840. (org-fold-show-branches)
  15841. (org-fold-hide-archived-subtrees beg end)))))
  15842. (defun org-delete-indentation (&optional arg)
  15843. "Join current line to previous and fix whitespace at join.
  15844. If previous line is a headline add to headline title. Otherwise
  15845. the function calls `delete-indentation'.
  15846. I.e. with a non-nil optional argument, join the line with the
  15847. following one. If there is a region then join the lines in that
  15848. region."
  15849. (interactive "*P")
  15850. (if (save-excursion
  15851. (beginning-of-line (if arg 1 0))
  15852. (let ((case-fold-search nil))
  15853. (looking-at org-complex-heading-regexp)))
  15854. ;; At headline.
  15855. (let ((tags-column (when (match-beginning 5)
  15856. (save-excursion (goto-char (match-beginning 5))
  15857. (current-column))))
  15858. (string (concat " " (progn (when arg (forward-line 1))
  15859. (org-trim (delete-and-extract-region
  15860. (line-beginning-position)
  15861. (line-end-position)))))))
  15862. (unless (bobp) (delete-region (point) (1- (point))))
  15863. (goto-char (or (match-end 4)
  15864. (match-beginning 5)
  15865. (match-end 0)))
  15866. (skip-chars-backward " \t")
  15867. (save-excursion (insert string))
  15868. ;; Adjust alignment of tags.
  15869. (cond
  15870. ((not tags-column)) ;no tags
  15871. (org-auto-align-tags (org-align-tags))
  15872. (t (org--align-tags-here tags-column)))) ;preserve tags column
  15873. (let ((current-prefix-arg arg))
  15874. (call-interactively #'delete-indentation))))
  15875. (defun org-open-line (n)
  15876. "Insert a new row in tables, call `open-line' elsewhere.
  15877. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  15878. As a special case, when a document starts with a table, allow to
  15879. call `open-line' on the very first character."
  15880. (interactive "*p")
  15881. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  15882. (org-table-insert-row)
  15883. (open-line n)))
  15884. (defun org--newline (indent arg interactive)
  15885. "Call `newline-and-indent' or just `newline'.
  15886. If INDENT is non-nil, call `newline-and-indent' with ARG to
  15887. indent unconditionally; otherwise, call `newline' with ARG and
  15888. INTERACTIVE, which can trigger indentation if
  15889. `electric-indent-mode' is enabled."
  15890. (if indent
  15891. (org-newline-and-indent arg)
  15892. (newline arg interactive)))
  15893. (defun org-return (&optional indent arg interactive)
  15894. "Goto next table row or insert a newline.
  15895. Calls `org-table-next-row' or `newline', depending on context.
  15896. When optional INDENT argument is non-nil, call
  15897. `newline-and-indent' with ARG, otherwise call `newline' with ARG
  15898. and INTERACTIVE.
  15899. When `org-return-follows-link' is non-nil and point is on
  15900. a timestamp or a link, call `org-open-at-point'. However, it
  15901. will not happen if point is in a table or on a \"dead\"
  15902. object (e.g., within a comment). In these case, you need to use
  15903. `org-open-at-point' directly."
  15904. (interactive "i\nP\np")
  15905. (let* ((context (if org-return-follows-link (org-element-context)
  15906. (org-element-at-point)))
  15907. (element-type (org-element-type context)))
  15908. (cond
  15909. ;; In a table, call `org-table-next-row'. However, before first
  15910. ;; column or after last one, split the table.
  15911. ((or (and (eq 'table element-type)
  15912. (not (eq 'table.el (org-element-property :type context)))
  15913. (>= (point) (org-element-property :contents-begin context))
  15914. (< (point) (org-element-property :contents-end context)))
  15915. (org-element-lineage context '(table-row table-cell) t))
  15916. (if (or (looking-at-p "[ \t]*$")
  15917. (save-excursion (skip-chars-backward " \t") (bolp)))
  15918. (insert "\n")
  15919. (org-table-justify-field-maybe)
  15920. (call-interactively #'org-table-next-row)))
  15921. ;; On a link or a timestamp, call `org-open-at-point' if
  15922. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  15923. ;; locations, e.g., in a comment, as `org-open-at-point'.
  15924. ((and org-return-follows-link
  15925. (or (and (eq 'link element-type)
  15926. ;; Ensure point is not on the white spaces after
  15927. ;; the link.
  15928. (let ((origin (point)))
  15929. (org-with-point-at (org-element-property :end context)
  15930. (skip-chars-backward " \t")
  15931. (> (point) origin))))
  15932. (org-in-regexp org-ts-regexp-both nil t)
  15933. (org-in-regexp org-tsr-regexp-both nil t)
  15934. (org-in-regexp org-link-any-re nil t)))
  15935. (call-interactively #'org-open-at-point))
  15936. ;; Insert newline in heading, but preserve tags.
  15937. ((and (not (bolp))
  15938. (let ((case-fold-search nil))
  15939. (org-match-line org-complex-heading-regexp)))
  15940. ;; At headline. Split line. However, if point is on keyword,
  15941. ;; priority cookie or tags, do not break any of them: add
  15942. ;; a newline after the headline instead.
  15943. (let ((tags-column (and (match-beginning 5)
  15944. (save-excursion (goto-char (match-beginning 5))
  15945. (current-column))))
  15946. (string
  15947. (when (and (match-end 4) (org-point-in-group (point) 4))
  15948. (delete-and-extract-region (point) (match-end 4)))))
  15949. ;; Adjust tag alignment.
  15950. (cond
  15951. ((not (and tags-column string)))
  15952. (org-auto-align-tags (org-align-tags))
  15953. (t (org--align-tags-here tags-column))) ;preserve tags column
  15954. (end-of-line)
  15955. (org-fold-show-entry)
  15956. (org--newline indent arg interactive)
  15957. (when string (save-excursion (insert (org-trim string))))))
  15958. ;; In a list, make sure indenting keeps trailing text within.
  15959. ((and (not (eolp))
  15960. (org-element-lineage context '(item)))
  15961. (let ((trailing-data
  15962. (delete-and-extract-region (point) (line-end-position))))
  15963. (org--newline indent arg interactive)
  15964. (save-excursion (insert trailing-data))))
  15965. (t
  15966. ;; Do not auto-fill when point is in an Org property drawer.
  15967. (let ((auto-fill-function (and (not (org-at-property-p))
  15968. auto-fill-function)))
  15969. (org--newline indent arg interactive))))))
  15970. (defun org-return-and-maybe-indent ()
  15971. "Goto next table row, or insert a newline, maybe indented.
  15972. Call `org-table-next-row' or `org-return', depending on context.
  15973. See the individual commands for more information.
  15974. When inserting a newline, if `org-adapt-indentation' is t:
  15975. indent the line if `electric-indent-mode' is disabled, don't
  15976. indent it if it is enabled."
  15977. (interactive)
  15978. (org-return (not electric-indent-mode)))
  15979. (defun org-ctrl-c-tab (&optional arg)
  15980. "Toggle columns width in a table, or show children.
  15981. Call `org-table-toggle-column-width' if point is in a table.
  15982. Otherwise provide a compact view of the children. ARG is the
  15983. level to hide."
  15984. (interactive "p")
  15985. (cond
  15986. ((org-at-table-p)
  15987. (call-interactively #'org-table-toggle-column-width))
  15988. ((org-before-first-heading-p)
  15989. (save-excursion
  15990. (org-fold-flag-above-first-heading)
  15991. (org-fold-hide-sublevels (or arg 1))))
  15992. (t
  15993. (org-fold-hide-subtree)
  15994. (org-fold-show-children arg))))
  15995. (defun org-ctrl-c-star ()
  15996. "Compute table, or change heading status of lines.
  15997. Calls `org-table-recalculate' or `org-toggle-heading',
  15998. depending on context."
  15999. (interactive)
  16000. (cond
  16001. ((org-at-table-p)
  16002. (call-interactively 'org-table-recalculate))
  16003. (t
  16004. ;; Convert all lines in region to list items
  16005. (call-interactively 'org-toggle-heading))))
  16006. (defun org-ctrl-c-minus ()
  16007. "Insert separator line in table or modify bullet status of line.
  16008. Also turns a plain line or a region of lines into list items.
  16009. Calls `org-table-insert-hline', `org-toggle-item', or
  16010. `org-cycle-list-bullet', depending on context."
  16011. (interactive)
  16012. (cond
  16013. ((org-at-table-p)
  16014. (call-interactively 'org-table-insert-hline))
  16015. ((org-region-active-p)
  16016. (call-interactively 'org-toggle-item))
  16017. ((org-in-item-p)
  16018. (call-interactively 'org-cycle-list-bullet))
  16019. (t
  16020. (call-interactively 'org-toggle-item))))
  16021. (defun org-toggle-heading (&optional nstars)
  16022. "Convert headings to normal text, or items or text to headings.
  16023. If there is no active region, only convert the current line.
  16024. With a `\\[universal-argument]' prefix, convert the whole list at
  16025. point into heading.
  16026. In a region:
  16027. - If the first non blank line is a headline, remove the stars
  16028. from all headlines in the region.
  16029. - If it is a normal line, turn each and every normal line (i.e.,
  16030. not an heading or an item) in the region into headings. If you
  16031. want to convert only the first line of this region, use one
  16032. universal prefix argument.
  16033. - If it is a plain list item, turn all plain list items into headings.
  16034. When converting a line into a heading, the number of stars is chosen
  16035. such that the lines become children of the current entry. However,
  16036. when a numeric prefix argument is given, its value determines the
  16037. number of stars to add."
  16038. (interactive "P")
  16039. (let ((skip-blanks
  16040. ;; Return beginning of first non-blank line, starting from
  16041. ;; line at POS.
  16042. (lambda (pos)
  16043. (save-excursion
  16044. (goto-char pos)
  16045. (while (org-at-comment-p) (forward-line))
  16046. (skip-chars-forward " \r\t\n")
  16047. (point-at-bol))))
  16048. beg end toggled)
  16049. ;; Determine boundaries of changes. If a universal prefix has
  16050. ;; been given, put the list in a region. If region ends at a bol,
  16051. ;; do not consider the last line to be in the region.
  16052. (when (and current-prefix-arg (org-at-item-p))
  16053. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  16054. (org-mark-element))
  16055. (if (org-region-active-p)
  16056. (setq beg (funcall skip-blanks (region-beginning))
  16057. end (copy-marker (save-excursion
  16058. (goto-char (region-end))
  16059. (if (bolp) (point) (point-at-eol)))))
  16060. (setq beg (funcall skip-blanks (point-at-bol))
  16061. end (copy-marker (point-at-eol))))
  16062. ;; Ensure inline tasks don't count as headings.
  16063. (org-with-limited-levels
  16064. (save-excursion
  16065. (goto-char beg)
  16066. (cond
  16067. ;; Case 1. Started at an heading: de-star headings.
  16068. ((org-at-heading-p)
  16069. (while (< (point) end)
  16070. (when (org-at-heading-p)
  16071. (looking-at org-outline-regexp) (replace-match "")
  16072. (setq toggled t))
  16073. (forward-line)))
  16074. ;; Case 2. Started at an item: change items into headlines.
  16075. ;; One star will be added by `org-list-to-subtree'.
  16076. ((org-at-item-p)
  16077. (while (< (point) end)
  16078. (when (org-at-item-p)
  16079. ;; Pay attention to cases when region ends before list.
  16080. (let* ((struct (org-list-struct))
  16081. (list-end
  16082. (min (org-list-get-bottom-point struct) (1+ end))))
  16083. (save-restriction
  16084. (narrow-to-region (point) list-end)
  16085. (insert (org-list-to-subtree
  16086. (org-list-to-lisp t)
  16087. (pcase (org-current-level)
  16088. (`nil 1)
  16089. (l (1+ (org-reduced-level l)))))
  16090. "\n")))
  16091. (setq toggled t))
  16092. (forward-line)))
  16093. ;; Case 3. Started at normal text: make every line an heading,
  16094. ;; skipping headlines and items.
  16095. (t (let* ((stars
  16096. (make-string
  16097. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  16098. (add-stars
  16099. (cond (nstars "") ; stars from prefix only
  16100. ((equal stars "") "*") ; before first heading
  16101. (org-odd-levels-only "**") ; inside heading, odd
  16102. (t "*"))) ; inside heading, oddeven
  16103. (rpl (concat stars add-stars " "))
  16104. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  16105. (while (< (point) (if (equal nstars '(4)) lend end))
  16106. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  16107. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  16108. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  16109. (forward-line)))))))
  16110. (unless toggled (message "Cannot toggle heading from here"))))
  16111. (defun org-meta-return (&optional arg)
  16112. "Insert a new heading or wrap a region in a table.
  16113. Calls `org-insert-heading', `org-insert-item' or
  16114. `org-table-wrap-region', depending on context. When called with
  16115. an argument, unconditionally call `org-insert-heading'."
  16116. (interactive "P")
  16117. (org-fold-check-before-invisible-edit 'insert)
  16118. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  16119. (call-interactively (cond (arg #'org-insert-heading)
  16120. ((org-at-table-p) #'org-table-wrap-region)
  16121. ((org-in-item-p) #'org-insert-item)
  16122. (t #'org-insert-heading)))))
  16123. ;;; Menu entries
  16124. (defsubst org-in-subtree-not-table-p ()
  16125. "Are we in a subtree and not in a table?"
  16126. (and (not (org-before-first-heading-p))
  16127. (not (org-at-table-p))))
  16128. ;; Define the Org mode menus
  16129. (easy-menu-define org-org-menu org-mode-map "Org menu."
  16130. `("Org"
  16131. ("Show/Hide"
  16132. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  16133. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  16134. ["Sparse Tree..." org-sparse-tree t]
  16135. ["Reveal Context" org-fold-reveal t]
  16136. ["Show All" org-fold-show-all t]
  16137. "--"
  16138. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  16139. "--"
  16140. ["New Heading" org-insert-heading t]
  16141. ("Navigate Headings"
  16142. ["Up" outline-up-heading t]
  16143. ["Next" outline-next-visible-heading t]
  16144. ["Previous" outline-previous-visible-heading t]
  16145. ["Next Same Level" outline-forward-same-level t]
  16146. ["Previous Same Level" outline-backward-same-level t]
  16147. "--"
  16148. ["Jump" org-goto t])
  16149. ("Edit Structure"
  16150. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  16151. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  16152. "--"
  16153. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  16154. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  16155. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  16156. "--"
  16157. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  16158. "--"
  16159. ["Copy visible text" org-copy-visible t]
  16160. "--"
  16161. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  16162. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  16163. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  16164. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  16165. "--"
  16166. ["Sort Region/Children" org-sort t]
  16167. "--"
  16168. ["Convert to odd levels" org-convert-to-odd-levels t]
  16169. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  16170. ("Editing"
  16171. ["Emphasis..." org-emphasize t]
  16172. ["Add block structure" org-insert-structure-template t]
  16173. ["Edit Source Example" org-edit-special t]
  16174. "--"
  16175. ["Footnote new/jump" org-footnote-action t]
  16176. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  16177. ("Archive"
  16178. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  16179. "--"
  16180. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  16181. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  16182. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)])
  16183. "--"
  16184. ("Hyperlinks"
  16185. ["Store Link (Global)" org-store-link t]
  16186. ["Find existing link to here" org-occur-link-in-agenda-files t]
  16187. ["Insert Link" org-insert-link t]
  16188. ["Follow Link" org-open-at-point t]
  16189. "--"
  16190. ["Next link" org-next-link t]
  16191. ["Previous link" org-previous-link t]
  16192. "--"
  16193. ["Descriptive Links"
  16194. org-toggle-link-display
  16195. :style radio
  16196. :selected org-descriptive-links
  16197. ]
  16198. ["Literal Links"
  16199. org-toggle-link-display
  16200. :style radio
  16201. :selected (not org-descriptive-links)])
  16202. "--"
  16203. ("TODO Lists"
  16204. ["TODO/DONE/-" org-todo t]
  16205. ("Select keyword"
  16206. ["Next keyword" org-shiftright (org-at-heading-p)]
  16207. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  16208. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  16209. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  16210. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  16211. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  16212. ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  16213. "--"
  16214. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  16215. :selected org-enforce-todo-dependencies :style toggle :active t]
  16216. "Settings for tree at point"
  16217. ["Do Children sequentially" org-toggle-ordered-property :style radio
  16218. :selected (org-entry-get nil "ORDERED")
  16219. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16220. ["Do Children parallel" org-toggle-ordered-property :style radio
  16221. :selected (not (org-entry-get nil "ORDERED"))
  16222. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16223. "--"
  16224. ["Set Priority" org-priority t]
  16225. ["Priority Up" org-shiftup t]
  16226. ["Priority Down" org-shiftdown t]
  16227. "--"
  16228. ["Get news from all feeds" org-feed-update-all t]
  16229. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  16230. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  16231. ("TAGS and Properties"
  16232. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  16233. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  16234. "--"
  16235. ["Set property" org-set-property (not (org-before-first-heading-p))]
  16236. ["Column view of properties" org-columns t]
  16237. ["Insert Column View DBlock" org-columns-insert-dblock t])
  16238. ("Dates and Scheduling"
  16239. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  16240. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  16241. ("Change Date"
  16242. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  16243. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  16244. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  16245. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  16246. ["Compute Time Range" org-evaluate-time-range t]
  16247. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  16248. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  16249. "--"
  16250. ["Custom time format" org-toggle-time-stamp-overlays
  16251. :style radio :selected org-display-custom-times]
  16252. "--"
  16253. ["Goto Calendar" org-goto-calendar t]
  16254. ["Date from Calendar" org-date-from-calendar t]
  16255. "--"
  16256. ["Start/Restart Timer" org-timer-start t]
  16257. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  16258. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  16259. ["Insert Timer String" org-timer t]
  16260. ["Insert Timer Item" org-timer-item t])
  16261. ("Logging work"
  16262. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  16263. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  16264. ["Clock out" org-clock-out t]
  16265. ["Clock cancel" org-clock-cancel t]
  16266. "--"
  16267. ["Mark as default task" org-clock-mark-default-task t]
  16268. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  16269. ["Goto running clock" org-clock-goto t]
  16270. "--"
  16271. ["Display times" org-clock-display t]
  16272. ["Create clock table" org-clock-report t]
  16273. "--"
  16274. ["Record DONE time"
  16275. (progn (setq org-log-done (not org-log-done))
  16276. (message "Switching to %s will %s record a timestamp"
  16277. (car org-done-keywords)
  16278. (if org-log-done "automatically" "not")))
  16279. :style toggle :selected org-log-done])
  16280. "--"
  16281. ["Agenda Command..." org-agenda t]
  16282. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  16283. ("File List for Agenda")
  16284. ("Special views current file"
  16285. ["TODO Tree" org-show-todo-tree t]
  16286. ["Check Deadlines" org-check-deadlines t]
  16287. ["Tags/Property tree" org-match-sparse-tree t])
  16288. "--"
  16289. ["Export/Publish..." org-export-dispatch t]
  16290. ("LaTeX"
  16291. ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  16292. :style toggle :selected org-cdlatex-mode]
  16293. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  16294. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  16295. ["Modify math symbol" org-cdlatex-math-modify
  16296. (org-inside-LaTeX-fragment-p)]
  16297. ["Insert citation" org-reftex-citation t])
  16298. "--"
  16299. ("Documentation"
  16300. ["Show Version" org-version t]
  16301. ["Info Documentation" org-info t]
  16302. ["Browse Org News" org-browse-news t])
  16303. ("Customize"
  16304. ["Browse Org Group" org-customize t]
  16305. "--"
  16306. ["Expand This Menu" org-create-customize-menu t])
  16307. ["Send bug report" org-submit-bug-report t]
  16308. "--"
  16309. ("Refresh/Reload"
  16310. ["Refresh setup current buffer" org-mode-restart t]
  16311. ["Reload Org (after update)" org-reload t]
  16312. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])))
  16313. (easy-menu-define org-tbl-menu org-mode-map "Org Table menu."
  16314. '("Table"
  16315. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  16316. ["Next Field" org-cycle (org-at-table-p)]
  16317. ["Previous Field" org-shifttab (org-at-table-p)]
  16318. ["Next Row" org-return (org-at-table-p)]
  16319. "--"
  16320. ["Blank Field" org-table-blank-field (org-at-table-p)]
  16321. ["Edit Field" org-table-edit-field (org-at-table-p)]
  16322. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  16323. "--"
  16324. ("Column"
  16325. ["Move Column Left" org-metaleft (org-at-table-p)]
  16326. ["Move Column Right" org-metaright (org-at-table-p)]
  16327. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  16328. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  16329. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  16330. ("Row"
  16331. ["Move Row Up" org-metaup (org-at-table-p)]
  16332. ["Move Row Down" org-metadown (org-at-table-p)]
  16333. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  16334. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  16335. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  16336. "--"
  16337. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  16338. ("Rectangle"
  16339. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  16340. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  16341. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  16342. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  16343. "--"
  16344. ("Calculate"
  16345. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  16346. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  16347. ["Edit Formulas" org-edit-special (org-at-table-p)]
  16348. "--"
  16349. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  16350. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  16351. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  16352. "--"
  16353. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  16354. "--"
  16355. ["Sum Column/Rectangle" org-table-sum
  16356. (or (org-at-table-p) (org-region-active-p))]
  16357. ["Which Column?" org-table-current-column (org-at-table-p)])
  16358. ["Debug Formulas"
  16359. org-table-toggle-formula-debugger
  16360. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  16361. ["Show Col/Row Numbers"
  16362. org-table-toggle-coordinate-overlays
  16363. :style toggle
  16364. :selected (bound-and-true-p org-table-overlay-coordinates)]
  16365. "--"
  16366. ["Create" org-table-create (not (org-at-table-p))]
  16367. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  16368. ["Import from File" org-table-import (not (org-at-table-p))]
  16369. ["Export to File" org-table-export (org-at-table-p)]
  16370. "--"
  16371. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  16372. "--"
  16373. ("Plot"
  16374. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  16375. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  16376. (defun org-info (&optional node)
  16377. "Read documentation for Org in the info system.
  16378. With optional NODE, go directly to that node."
  16379. (interactive)
  16380. (info (format "(org)%s" (or node ""))))
  16381. (defun org-browse-news ()
  16382. "Browse the news for the latest major release."
  16383. (interactive)
  16384. (browse-url "https://orgmode.org/Changes.html"))
  16385. ;;;###autoload
  16386. (defun org-submit-bug-report ()
  16387. "Submit a bug report on Org via mail.
  16388. Don't hesitate to report any problems or inaccurate documentation.
  16389. If you don't have setup sending mail from (X)Emacs, please copy the
  16390. output buffer into your mail program, as it gives us important
  16391. information about your Org version and configuration."
  16392. (interactive)
  16393. (require 'reporter)
  16394. (defvar reporter-prompt-for-summary-p)
  16395. (org-load-modules-maybe)
  16396. (org-require-autoloaded-modules)
  16397. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  16398. (reporter-submit-bug-report
  16399. "emacs-orgmode@gnu.org"
  16400. (org-version nil 'full)
  16401. (let (list)
  16402. (save-window-excursion
  16403. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  16404. (delete-other-windows)
  16405. (erase-buffer)
  16406. (insert "You are about to submit a bug report to the Org mailing list.
  16407. If your report is about Org installation, please read this section:
  16408. https://orgmode.org/org.html#Installation
  16409. Please read https://orgmode.org/org.html#Feedback on how to make
  16410. a good report, it will help Org contributors fixing your problem.
  16411. Search https://lists.gnu.org/archive/html/emacs-orgmode/ to see
  16412. if the issue you are about to raise has already been dealt with.
  16413. We also would like to add your full Org and Outline configuration
  16414. to the bug report. It will help us debugging the issue.
  16415. *HOWEVER*, some variables you have customized may contain private
  16416. information. The names of customers, colleagues, or friends, might
  16417. appear in the form of file names, tags, todo states or search strings.
  16418. If you answer \"yes\" to the prompt, you might want to check and remove
  16419. such private information before sending the email.")
  16420. (add-text-properties (point-min) (point-max) '(face org-warning))
  16421. (when (yes-or-no-p "Include your Org configuration ")
  16422. (mapatoms
  16423. (lambda (v)
  16424. (and (boundp v)
  16425. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  16426. (or (and (symbol-value v)
  16427. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  16428. (and
  16429. (get v 'custom-type) (get v 'standard-value)
  16430. (not (equal (symbol-value v)
  16431. (eval (car (get v 'standard-value)) t)))))
  16432. (push v list)))))
  16433. (kill-buffer (get-buffer "*Warn about privacy*"))
  16434. list))
  16435. nil nil
  16436. "Remember to cover the basics, that is, what you expected to happen and
  16437. what in fact did happen. You don't know how to make a good report? See
  16438. https://orgmode.org/manual/Feedback.html#Feedback
  16439. Your bug report will be posted to the Org mailing list.
  16440. ------------------------------------------------------------------------")
  16441. (save-excursion
  16442. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  16443. (replace-match "\\1[BUG] \\3 [\\2]")))))
  16444. (defun org-install-agenda-files-menu ()
  16445. "Install agenda file menu."
  16446. (let ((bl (buffer-list)))
  16447. (save-excursion
  16448. (while bl
  16449. (set-buffer (pop bl))
  16450. (when (derived-mode-p 'org-mode) (setq bl nil)))
  16451. (when (derived-mode-p 'org-mode)
  16452. (easy-menu-change
  16453. '("Org") "File List for Agenda"
  16454. (append
  16455. (list
  16456. ["Edit File List" (org-edit-agenda-file-list) t]
  16457. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  16458. ["Remove Current File from List" org-remove-file t]
  16459. ["Cycle through agenda files" org-cycle-agenda-files t]
  16460. ["Occur in all agenda files" org-occur-in-agenda-files t]
  16461. "--")
  16462. (mapcar 'org-file-menu-entry
  16463. ;; Prevent initialization from failing.
  16464. (ignore-errors (org-agenda-files t)))))))))
  16465. ;;;; Documentation
  16466. (defun org-require-autoloaded-modules ()
  16467. (interactive)
  16468. (mapc #'require
  16469. '(org-agenda org-archive org-attach org-clock org-colview org-id
  16470. org-table org-timer)))
  16471. ;;;###autoload
  16472. (defun org-reload (&optional uncompiled)
  16473. "Reload all Org Lisp files.
  16474. With prefix arg UNCOMPILED, load the uncompiled versions."
  16475. (interactive "P")
  16476. (require 'loadhist)
  16477. (let* ((org-dir (org-find-library-dir "org"))
  16478. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  16479. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  16480. (remove-re (format "\\`%s\\'"
  16481. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  16482. (feats (delete-dups
  16483. (mapcar 'file-name-sans-extension
  16484. (mapcar 'file-name-nondirectory
  16485. (delq nil
  16486. (mapcar 'feature-file
  16487. features))))))
  16488. (lfeat (append
  16489. (sort
  16490. (setq feats
  16491. (delq nil (mapcar
  16492. (lambda (f)
  16493. (if (and (string-match feature-re f)
  16494. (not (string-match remove-re f)))
  16495. f nil))
  16496. feats)))
  16497. 'string-lessp)
  16498. (list "org-version" "org")))
  16499. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  16500. load-uncore load-misses)
  16501. (setq load-misses
  16502. (delq 't
  16503. (mapcar (lambda (f)
  16504. (or (org-load-noerror-mustsuffix (concat org-dir f))
  16505. (and (string= org-dir contrib-dir)
  16506. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  16507. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  16508. (push f load-uncore)
  16509. 't)
  16510. f))
  16511. lfeat)))
  16512. (when load-uncore
  16513. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  16514. (if (> (length load-uncore) 1) "s were" " was")
  16515. (reverse load-uncore)))
  16516. (if load-misses
  16517. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  16518. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  16519. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  16520. ;;;###autoload
  16521. (defun org-customize ()
  16522. "Call the customize function with org as argument."
  16523. (interactive)
  16524. (org-load-modules-maybe)
  16525. (org-require-autoloaded-modules)
  16526. (customize-browse 'org))
  16527. (defun org-create-customize-menu ()
  16528. "Create a full customization menu for Org mode, insert it into the menu."
  16529. (interactive)
  16530. (org-load-modules-maybe)
  16531. (org-require-autoloaded-modules)
  16532. (easy-menu-change
  16533. '("Org") "Customize"
  16534. `(["Browse Org group" org-customize t]
  16535. "--"
  16536. ,(customize-menu-create 'org)
  16537. ["Set" Custom-set t]
  16538. ["Save" Custom-save t]
  16539. ["Reset to Current" Custom-reset-current t]
  16540. ["Reset to Saved" Custom-reset-saved t]
  16541. ["Reset to Standard Settings" Custom-reset-standard t]))
  16542. (message "\"Org\"-menu now contains full customization menu"))
  16543. ;;;; Miscellaneous stuff
  16544. ;;; Generally useful functions
  16545. (defun org-in-clocktable-p ()
  16546. "Check if the cursor is in a clocktable."
  16547. (let ((pos (point)) start)
  16548. (save-excursion
  16549. (end-of-line 1)
  16550. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  16551. (setq start (match-beginning 0))
  16552. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  16553. (>= (match-end 0) pos)
  16554. start))))
  16555. (defun org-in-verbatim-emphasis ()
  16556. (save-match-data
  16557. (and (org-in-regexp org-verbatim-re 2)
  16558. (>= (point) (match-beginning 3))
  16559. (<= (point) (match-end 4)))))
  16560. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  16561. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  16562. (if (and marker (marker-buffer marker)
  16563. (buffer-live-p (marker-buffer marker)))
  16564. (progn
  16565. (pop-to-buffer-same-window (marker-buffer marker))
  16566. (when (or (> marker (point-max)) (< marker (point-min)))
  16567. (widen))
  16568. (goto-char marker)
  16569. (org-fold-show-context 'org-goto))
  16570. (if bookmark
  16571. (bookmark-jump bookmark)
  16572. (error "Cannot find location"))))
  16573. (defun org-quote-csv-field (s)
  16574. "Quote field for inclusion in CSV material."
  16575. (if (string-match "[\",]" s)
  16576. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  16577. s))
  16578. (defun org-force-self-insert (N)
  16579. "Needed to enforce self-insert under remapping."
  16580. (interactive "p")
  16581. (self-insert-command N))
  16582. (defun org-quote-vert (s)
  16583. "Replace \"|\" with \"\\vert\"."
  16584. (while (string-match "|" s)
  16585. (setq s (replace-match "\\vert" t t s)))
  16586. s)
  16587. (defun org-uuidgen-p (s)
  16588. "Is S an ID created by UUIDGEN?"
  16589. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  16590. (defun org-in-src-block-p (&optional inside element)
  16591. "Whether point is in a code source block.
  16592. When INSIDE is non-nil, don't consider we are within a source
  16593. block when point is at #+BEGIN_SRC or #+END_SRC.
  16594. When ELEMENT is provided, it is considered to be element at point."
  16595. (save-match-data (setq element (or element (org-element-at-point))))
  16596. (when (eq 'src-block (org-element-type element))
  16597. (or (not inside)
  16598. (not (or (= (line-beginning-position)
  16599. (org-element-property :post-affiliated element))
  16600. (= (1+ (line-end-position))
  16601. (- (org-element-property :end element)
  16602. (org-element-property :post-blank element))))))))
  16603. (defun org-context ()
  16604. "Return a list of contexts of the current cursor position.
  16605. If several contexts apply, all are returned.
  16606. Each context entry is a list with a symbol naming the context, and
  16607. two positions indicating start and end of the context. Possible
  16608. contexts are:
  16609. :headline anywhere in a headline
  16610. :headline-stars on the leading stars in a headline
  16611. :todo-keyword on a TODO keyword (including DONE) in a headline
  16612. :tags on the TAGS in a headline
  16613. :priority on the priority cookie in a headline
  16614. :item on the first line of a plain list item
  16615. :item-bullet on the bullet/number of a plain list item
  16616. :checkbox on the checkbox in a plain list item
  16617. :table in an Org table
  16618. :table-special on a special filed in a table
  16619. :table-table in a table.el table
  16620. :clocktable in a clocktable
  16621. :src-block in a source block
  16622. :link on a hyperlink
  16623. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  16624. :latex-fragment on a LaTeX fragment
  16625. :latex-preview on a LaTeX fragment with overlaid preview image
  16626. This function expects the position to be visible because it uses font-lock
  16627. faces as a help to recognize the following contexts: :table-special, :link,
  16628. and :keyword."
  16629. (let* ((f (get-text-property (point) 'face))
  16630. (faces (if (listp f) f (list f)))
  16631. (case-fold-search t)
  16632. (p (point)) clist o)
  16633. ;; First the large context
  16634. (cond
  16635. ((org-at-heading-p)
  16636. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  16637. (when (progn
  16638. (beginning-of-line 1)
  16639. (looking-at org-todo-line-tags-regexp))
  16640. (push (org-point-in-group p 1 :headline-stars) clist)
  16641. (push (org-point-in-group p 2 :todo-keyword) clist)
  16642. (push (org-point-in-group p 4 :tags) clist))
  16643. (goto-char p)
  16644. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  16645. (when (looking-at "\\[#[A-Z0-9]\\]")
  16646. (push (org-point-in-group p 0 :priority) clist)))
  16647. ((org-at-item-p)
  16648. (push (org-point-in-group p 2 :item-bullet) clist)
  16649. (push (list :item (point-at-bol)
  16650. (save-excursion (org-end-of-item) (point)))
  16651. clist)
  16652. (and (org-at-item-checkbox-p)
  16653. (push (org-point-in-group p 0 :checkbox) clist)))
  16654. ((org-at-table-p)
  16655. (push (list :table (org-table-begin) (org-table-end)) clist)
  16656. (when (memq 'org-formula faces)
  16657. (push (list :table-special
  16658. (previous-single-property-change p 'face)
  16659. (next-single-property-change p 'face))
  16660. clist)))
  16661. ((org-at-table-p 'any)
  16662. (push (list :table-table) clist)))
  16663. (goto-char p)
  16664. (let ((case-fold-search t))
  16665. ;; New the "medium" contexts: clocktables, source blocks
  16666. (cond ((org-in-clocktable-p)
  16667. (push (list :clocktable
  16668. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  16669. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  16670. (match-beginning 1))
  16671. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  16672. (match-end 0)))
  16673. clist))
  16674. ((org-in-src-block-p)
  16675. (push (list :src-block
  16676. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  16677. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  16678. (match-beginning 1))
  16679. (and (search-forward "#+END_SRC" nil t)
  16680. (match-beginning 0)))
  16681. clist))))
  16682. (goto-char p)
  16683. ;; Now the small context
  16684. (cond
  16685. ((org-at-timestamp-p)
  16686. (push (org-point-in-group p 0 :timestamp) clist))
  16687. ((memq 'org-link faces)
  16688. (push (list :link
  16689. (previous-single-property-change p 'face)
  16690. (next-single-property-change p 'face))
  16691. clist))
  16692. ((memq 'org-special-keyword faces)
  16693. (push (list :keyword
  16694. (previous-single-property-change p 'face)
  16695. (next-single-property-change p 'face))
  16696. clist))
  16697. ((setq o (cl-some
  16698. (lambda (o)
  16699. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  16700. o))
  16701. (overlays-at (point))))
  16702. (push (list :latex-fragment
  16703. (overlay-start o) (overlay-end o))
  16704. clist)
  16705. (push (list :latex-preview
  16706. (overlay-start o) (overlay-end o))
  16707. clist))
  16708. ((org-inside-LaTeX-fragment-p)
  16709. ;; FIXME: positions wrong.
  16710. (push (list :latex-fragment (point) (point)) clist)))
  16711. (setq clist (nreverse (delq nil clist)))
  16712. clist))
  16713. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  16714. "Non-nil when point is between matches of START-RE and END-RE.
  16715. Also return a non-nil value when point is on one of the matches.
  16716. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  16717. buffer positions. Default values are the positions of headlines
  16718. surrounding the point.
  16719. The functions returns a cons cell whose car (resp. cdr) is the
  16720. position before START-RE (resp. after END-RE)."
  16721. (save-match-data
  16722. (let ((pos (point))
  16723. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  16724. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  16725. beg end)
  16726. (save-excursion
  16727. ;; Point is on a block when on START-RE or if START-RE can be
  16728. ;; found before it...
  16729. (and (or (org-in-regexp start-re)
  16730. (re-search-backward start-re limit-up t))
  16731. (setq beg (match-beginning 0))
  16732. ;; ... and END-RE after it...
  16733. (goto-char (match-end 0))
  16734. (re-search-forward end-re limit-down t)
  16735. (> (setq end (match-end 0)) pos)
  16736. ;; ... without another START-RE in-between.
  16737. (goto-char (match-beginning 0))
  16738. (not (re-search-backward start-re (1+ beg) t))
  16739. ;; Return value.
  16740. (cons beg end))))))
  16741. (defun org-in-block-p (names)
  16742. "Non-nil when point belongs to a block whose name belongs to NAMES.
  16743. NAMES is a list of strings containing names of blocks.
  16744. Return first block name matched, or nil. Beware that in case of
  16745. nested blocks, the returned name may not belong to the closest
  16746. block from point."
  16747. (save-match-data
  16748. (catch 'exit
  16749. (let ((case-fold-search t)
  16750. (lim-up (save-excursion (outline-previous-heading)))
  16751. (lim-down (save-excursion (outline-next-heading))))
  16752. (dolist (name names)
  16753. (let ((n (regexp-quote name)))
  16754. (when (org-between-regexps-p
  16755. (concat "^[ \t]*#\\+begin_" n)
  16756. (concat "^[ \t]*#\\+end_" n)
  16757. lim-up lim-down)
  16758. (throw 'exit n)))))
  16759. nil)))
  16760. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  16761. "Call `multi-occur' with buffers for all agenda files."
  16762. (interactive "sOrg-files matching: ")
  16763. (let* ((files (org-agenda-files))
  16764. (tnames (mapcar #'file-truename files))
  16765. (extra org-agenda-text-search-extra-files))
  16766. (when (eq (car extra) 'agenda-archives)
  16767. (setq extra (cdr extra))
  16768. (setq files (org-add-archive-files files)))
  16769. (dolist (f extra)
  16770. (unless (member (file-truename f) tnames)
  16771. (unless (member f files) (setq files (append files (list f))))
  16772. (setq tnames (append tnames (list (file-truename f))))))
  16773. (multi-occur
  16774. (mapcar (lambda (x)
  16775. (with-current-buffer
  16776. ;; FIXME: Why not just (find-file-noselect x)?
  16777. ;; Is it to avoid the "revert buffer" prompt?
  16778. (or (get-file-buffer x) (find-file-noselect x))
  16779. (widen)
  16780. (current-buffer)))
  16781. files)
  16782. regexp)))
  16783. (add-hook 'occur-mode-find-occurrence-hook
  16784. (lambda () (when (derived-mode-p 'org-mode) (org-fold-reveal))))
  16785. (defun org-occur-link-in-agenda-files ()
  16786. "Create a link and search for it in the agendas.
  16787. The link is not stored in `org-stored-links', it is just created
  16788. for the search purpose."
  16789. (interactive)
  16790. (let ((link (condition-case nil
  16791. (org-store-link nil)
  16792. (error "Unable to create a link to here"))))
  16793. (org-occur-in-agenda-files (regexp-quote link))))
  16794. (defun org-back-over-empty-lines ()
  16795. "Move backwards over whitespace, to the beginning of the first empty line.
  16796. Returns the number of empty lines passed."
  16797. (let ((pos (point)))
  16798. (if (cdr (assq 'heading org-blank-before-new-entry))
  16799. (skip-chars-backward " \t\n\r")
  16800. (unless (eobp)
  16801. (forward-line -1)))
  16802. (beginning-of-line 2)
  16803. (goto-char (min (point) pos))
  16804. (count-lines (point) pos)))
  16805. ;;; TODO: Only called once, from ox-odt which should probably use
  16806. ;;; org-export-inline-image-p or something.
  16807. (defun org-file-image-p (file)
  16808. "Return non-nil if FILE is an image."
  16809. (save-match-data
  16810. (string-match (image-file-name-regexp) file)))
  16811. (defun org-get-cursor-date (&optional with-time)
  16812. "Return the date at cursor in as a time.
  16813. This works in the calendar and in the agenda, anywhere else it just
  16814. returns the current time.
  16815. If WITH-TIME is non-nil, returns the time of the event at point (in
  16816. the agenda) or the current time of the day; otherwise returns the
  16817. earliest time on the cursor date that Org treats as that date
  16818. (bearing in mind `org-extend-today-until')."
  16819. (let (date day defd tp hod mod)
  16820. (when with-time
  16821. (setq tp (get-text-property (point) 'time))
  16822. (when (and tp (string-match "\\([0-2]?[0-9]\\):\\([0-5][0-9]\\)" tp))
  16823. (setq hod (string-to-number (match-string 1 tp))
  16824. mod (string-to-number (match-string 2 tp))))
  16825. (or tp (let ((now (decode-time)))
  16826. (setq hod (nth 2 now)
  16827. mod (nth 1 now)))))
  16828. (cond
  16829. ((eq major-mode 'calendar-mode)
  16830. (setq date (calendar-cursor-to-date)
  16831. defd (org-encode-time 0 (or mod 0) (or hod org-extend-today-until)
  16832. (nth 1 date) (nth 0 date) (nth 2 date))))
  16833. ((eq major-mode 'org-agenda-mode)
  16834. (setq day (get-text-property (point) 'day))
  16835. (when day
  16836. (setq date (calendar-gregorian-from-absolute day)
  16837. defd (org-encode-time 0 (or mod 0) (or hod org-extend-today-until)
  16838. (nth 1 date) (nth 0 date) (nth 2 date))))))
  16839. (or defd (current-time))))
  16840. (defun org-mark-subtree (&optional up)
  16841. "Mark the current subtree.
  16842. This puts point at the start of the current subtree, and mark at
  16843. the end. If a numeric prefix UP is given, move up into the
  16844. hierarchy of headlines by UP levels before marking the subtree."
  16845. (interactive "P")
  16846. (org-with-limited-levels
  16847. (cond ((org-at-heading-p) (beginning-of-line))
  16848. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  16849. (t (outline-previous-visible-heading 1))))
  16850. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  16851. (if (called-interactively-p 'any)
  16852. (call-interactively 'org-mark-element)
  16853. (org-mark-element)))
  16854. ;;; Indentation
  16855. (defvar org-element-greater-elements)
  16856. (defun org--get-expected-indentation (element contentsp)
  16857. "Expected indentation column for current line, according to ELEMENT.
  16858. ELEMENT is an element containing point. CONTENTSP is non-nil
  16859. when indentation is to be computed according to contents of
  16860. ELEMENT."
  16861. (let ((type (org-element-type element))
  16862. (start (org-element-property :begin element))
  16863. (post-affiliated (org-element-property :post-affiliated element)))
  16864. (org-with-wide-buffer
  16865. (cond
  16866. (contentsp
  16867. (cl-case type
  16868. ((diary-sexp footnote-definition) 0)
  16869. (section
  16870. (org--get-expected-indentation
  16871. (org-element-property :parent element)
  16872. t))
  16873. ((headline inlinetask nil)
  16874. (if (not org-adapt-indentation) 0
  16875. (let ((level (org-current-level)))
  16876. (if level (1+ level) 0))))
  16877. ((item plain-list) (org-list-item-body-column post-affiliated))
  16878. (t
  16879. (goto-char start)
  16880. (current-indentation))))
  16881. ((memq type '(headline inlinetask nil))
  16882. (if (org-match-line "[ \t]*$")
  16883. (org--get-expected-indentation element t)
  16884. 0))
  16885. ((memq type '(diary-sexp footnote-definition)) 0)
  16886. ;; First paragraph of a footnote definition or an item.
  16887. ;; Indent like parent.
  16888. ((< (line-beginning-position) start)
  16889. (org--get-expected-indentation
  16890. (org-element-property :parent element) t))
  16891. ;; At first line: indent according to previous sibling, if any,
  16892. ;; ignoring footnote definitions and inline tasks, or parent's
  16893. ;; contents.
  16894. ((and ( = (line-beginning-position) start)
  16895. (eq org-adapt-indentation t))
  16896. (catch 'exit
  16897. (while t
  16898. (if (= (point-min) start) (throw 'exit 0)
  16899. (goto-char (1- start))
  16900. (let* ((previous (org-element-at-point))
  16901. (parent previous))
  16902. (while (and parent (<= (org-element-property :end parent) start))
  16903. (setq previous parent
  16904. parent (org-element-property :parent parent)))
  16905. (cond
  16906. ((not previous) (throw 'exit 0))
  16907. ((> (org-element-property :end previous) start)
  16908. (throw 'exit (org--get-expected-indentation previous t)))
  16909. ((memq (org-element-type previous)
  16910. '(footnote-definition inlinetask))
  16911. (setq start (org-element-property :begin previous)))
  16912. (t (goto-char (org-element-property :begin previous))
  16913. (throw 'exit
  16914. (if (bolp) (current-indentation)
  16915. ;; At first paragraph in an item or
  16916. ;; a footnote definition.
  16917. (org--get-expected-indentation
  16918. (org-element-property :parent previous) t))))))))))
  16919. ;; Otherwise, move to the first non-blank line above.
  16920. (t
  16921. (beginning-of-line)
  16922. (let ((pos (point)))
  16923. (skip-chars-backward " \r\t\n")
  16924. (cond
  16925. ;; Two blank lines end a footnote definition or a plain
  16926. ;; list. When we indent an empty line after them, the
  16927. ;; containing list or footnote definition is over, so it
  16928. ;; qualifies as a previous sibling. Therefore, we indent
  16929. ;; like its first line.
  16930. ((and (memq type '(footnote-definition plain-list))
  16931. (> (count-lines (point) pos) 2))
  16932. (goto-char start)
  16933. (current-indentation))
  16934. ;; Line above is the first one of a paragraph at the
  16935. ;; beginning of an item or a footnote definition. Indent
  16936. ;; like parent.
  16937. ((< (line-beginning-position) start)
  16938. (org--get-expected-indentation
  16939. (org-element-property :parent element) t))
  16940. ;; Line above is the beginning of an element, i.e., point
  16941. ;; was originally on the blank lines between element's start
  16942. ;; and contents.
  16943. ((= (line-beginning-position) post-affiliated)
  16944. (org--get-expected-indentation element t))
  16945. ;; POS is after contents in a greater element. Indent like
  16946. ;; the beginning of the element.
  16947. ((and (memq type org-element-greater-elements)
  16948. (let ((cend (org-element-property :contents-end element)))
  16949. (and cend (<= cend pos))))
  16950. ;; As a special case, if point is at the end of a footnote
  16951. ;; definition or an item, indent like the very last element
  16952. ;; within. If that last element is an item, indent like
  16953. ;; its contents.
  16954. (if (memq type '(footnote-definition item plain-list))
  16955. (let ((last (org-element-at-point)))
  16956. (goto-char pos)
  16957. (org--get-expected-indentation
  16958. last (eq (org-element-type last) 'item)))
  16959. (goto-char start)
  16960. (current-indentation)))
  16961. ;; In any other case, indent like the current line.
  16962. (t (current-indentation)))))
  16963. ;; Finally, no indentation is needed, fall back to 0.
  16964. (t (current-indentation))))))
  16965. (defun org--align-node-property ()
  16966. "Align node property at point.
  16967. Alignment is done according to `org-property-format', which see."
  16968. (when (save-excursion
  16969. (beginning-of-line)
  16970. (looking-at org-property-re))
  16971. (combine-change-calls (match-beginning 0) (match-end 0)
  16972. (let ((newtext (concat (match-string 4)
  16973. (org-trim
  16974. (format org-property-format (match-string 1) (match-string 3))))))
  16975. ;; Do not use `replace-match' here as we want to inherit folding
  16976. ;; properties if inside fold.
  16977. (setf (buffer-substring (match-beginning 0) (match-end 0)) "")
  16978. (insert-and-inherit newtext)))))
  16979. (defun org-indent-line ()
  16980. "Indent line depending on context.
  16981. Indentation is done according to the following rules:
  16982. - Footnote definitions, diary sexps, headlines and inline tasks
  16983. have to start at column 0.
  16984. - On the very first line of an element, consider, in order, the
  16985. next rules until one matches:
  16986. 1. If there's a sibling element before, ignoring footnote
  16987. definitions and inline tasks, indent like its first line.
  16988. 2. If element has a parent, indent like its contents. More
  16989. precisely, if parent is an item, indent after the bullet.
  16990. Else, indent like parent's first line.
  16991. 3. Otherwise, indent relatively to current level, if
  16992. `org-adapt-indentation' is t, or to left margin.
  16993. - On a blank line at the end of an element, indent according to
  16994. the type of the element. More precisely
  16995. 1. If element is a plain list, an item, or a footnote
  16996. definition, indent like the very last element within.
  16997. 2. If element is a paragraph, indent like its last non blank
  16998. line.
  16999. 3. Otherwise, indent like its very first line.
  17000. - In the code part of a source block, use language major mode
  17001. to indent current line if `org-src-tab-acts-natively' is
  17002. non-nil. If it is nil, do nothing.
  17003. - Otherwise, indent like the first non-blank line above.
  17004. The function doesn't indent an item as it could break the whole
  17005. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  17006. `\\[org-shiftmetaright]'.
  17007. Also align node properties according to `org-property-format'."
  17008. (interactive)
  17009. (unless (or (org-at-heading-p)
  17010. (and (eq org-adapt-indentation 'headline-data)
  17011. (not (or (org-at-clock-log-p)
  17012. (org-at-planning-p)))
  17013. (save-excursion
  17014. (beginning-of-line 1)
  17015. (skip-chars-backward "\n")
  17016. (or (org-at-heading-p)
  17017. (looking-back ":END:.*" (point-at-bol))))))
  17018. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point-no-context)))
  17019. (type (org-element-type element)))
  17020. (cond ((and (memq type '(plain-list item))
  17021. (= (line-beginning-position)
  17022. (org-element-property :post-affiliated element)))
  17023. nil)
  17024. ((and (eq type 'latex-environment)
  17025. (>= (point) (org-element-property :post-affiliated element))
  17026. (< (point)
  17027. (org-with-point-at (org-element-property :end element)
  17028. (skip-chars-backward " \t\n")
  17029. (line-beginning-position 2))))
  17030. nil)
  17031. ((and (eq type 'src-block)
  17032. org-src-tab-acts-natively
  17033. (> (line-beginning-position)
  17034. (org-element-property :post-affiliated element))
  17035. (< (line-beginning-position)
  17036. (org-with-point-at (org-element-property :end element)
  17037. (skip-chars-backward " \t\n")
  17038. (line-beginning-position))))
  17039. ;; At the beginning of a blank line, do some preindentation. This
  17040. ;; signals org-src--edit-element to preserve the indentation on exit
  17041. (when (and (looking-at-p "^[[:space:]]*$")
  17042. (not org-src-preserve-indentation))
  17043. (let ((element (org-element-at-point))
  17044. block-content-ind some-ind)
  17045. (org-with-point-at (org-element-property :begin element)
  17046. (setq block-content-ind (+ (current-indentation)
  17047. org-edit-src-content-indentation))
  17048. (forward-line)
  17049. (save-match-data (re-search-forward "^[ \t]*\\S-" nil t))
  17050. (backward-char)
  17051. (setq some-ind (if (looking-at-p "#\\+end_src")
  17052. block-content-ind (current-indentation))))
  17053. (indent-line-to (min block-content-ind some-ind))))
  17054. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  17055. (t
  17056. (let ((column (org--get-expected-indentation element nil)))
  17057. ;; Preserve current column.
  17058. (if (<= (current-column) (current-indentation))
  17059. (indent-line-to column)
  17060. (save-excursion (indent-line-to column))))
  17061. ;; Align node property. Also preserve current column.
  17062. (when (eq type 'node-property)
  17063. (let ((column (current-column)))
  17064. (org--align-node-property)
  17065. (org-move-to-column column))))))))
  17066. (defun org-indent-region (start end)
  17067. "Indent each non-blank line in the region.
  17068. Called from a program, START and END specify the region to
  17069. indent. The function will not indent contents of example blocks,
  17070. verse blocks and export blocks as leading white spaces are
  17071. assumed to be significant there."
  17072. (interactive "r")
  17073. (save-excursion
  17074. (goto-char start)
  17075. (skip-chars-forward " \r\t\n")
  17076. (unless (eobp) (beginning-of-line))
  17077. (let ((indent-to
  17078. (lambda (ind pos)
  17079. ;; Set IND as indentation for all lines between point and
  17080. ;; POS. Blank lines are ignored. Leave point after POS
  17081. ;; once done.
  17082. (let ((limit (copy-marker pos)))
  17083. (while (< (point) limit)
  17084. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  17085. (forward-line))
  17086. (set-marker limit nil))))
  17087. (end (copy-marker end)))
  17088. (while (< (point) end)
  17089. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  17090. (let* ((element (org-element-at-point-no-context))
  17091. (type (org-element-type element))
  17092. (element-end (copy-marker (org-element-property :end element)))
  17093. (ind (org--get-expected-indentation element nil)))
  17094. (cond
  17095. ;; Element indented as a single block. Example blocks
  17096. ;; preserving indentation are a special case since the
  17097. ;; "contents" must not be indented whereas the block
  17098. ;; boundaries can.
  17099. ((or (memq type '(export-block latex-environment))
  17100. (and (eq type 'example-block)
  17101. (not
  17102. (or org-src-preserve-indentation
  17103. (org-element-property :preserve-indent element)))))
  17104. (let ((offset (- ind (current-indentation))))
  17105. (unless (zerop offset)
  17106. (indent-rigidly (org-element-property :begin element)
  17107. (org-element-property :end element)
  17108. offset)))
  17109. (goto-char element-end))
  17110. ;; Elements indented line wise. Be sure to exclude
  17111. ;; example blocks (preserving indentation) and source
  17112. ;; blocks from this category as they are treated
  17113. ;; specially later.
  17114. ((or (memq type '(paragraph table table-row))
  17115. (not (or (org-element-property :contents-begin element)
  17116. (memq type '(example-block src-block)))))
  17117. (when (eq type 'node-property)
  17118. (org--align-node-property)
  17119. (beginning-of-line))
  17120. (funcall indent-to ind (min element-end end)))
  17121. ;; Elements consisting of three parts: before the
  17122. ;; contents, the contents, and after the contents. The
  17123. ;; contents are treated specially, according to the
  17124. ;; element type, or not indented at all. Other parts are
  17125. ;; indented as a single block.
  17126. (t
  17127. (let* ((post (copy-marker
  17128. (org-element-property :post-affiliated element)))
  17129. (cbeg
  17130. (copy-marker
  17131. (cond
  17132. ((not (org-element-property :contents-begin element))
  17133. ;; Fake contents for source blocks.
  17134. (org-with-wide-buffer
  17135. (goto-char post)
  17136. (line-beginning-position 2)))
  17137. ((memq type '(footnote-definition item plain-list))
  17138. ;; Contents in these elements could start on
  17139. ;; the same line as the beginning of the
  17140. ;; element. Make sure we start indenting
  17141. ;; from the second line.
  17142. (org-with-wide-buffer
  17143. (goto-char post)
  17144. (end-of-line)
  17145. (skip-chars-forward " \r\t\n")
  17146. (if (eobp) (point) (line-beginning-position))))
  17147. (t (org-element-property :contents-begin element)))))
  17148. (cend (copy-marker
  17149. (or (org-element-property :contents-end element)
  17150. ;; Fake contents for source blocks.
  17151. (org-with-wide-buffer
  17152. (goto-char element-end)
  17153. (skip-chars-backward " \r\t\n")
  17154. (line-beginning-position)))
  17155. t)))
  17156. ;; Do not change items indentation individually as it
  17157. ;; might break the list as a whole. On the other
  17158. ;; hand, when at a plain list, indent it as a whole.
  17159. (cond ((eq type 'plain-list)
  17160. (let ((offset (- ind (current-indentation))))
  17161. (unless (zerop offset)
  17162. (indent-rigidly (org-element-property :begin element)
  17163. (org-element-property :end element)
  17164. offset))
  17165. (goto-char cbeg)))
  17166. ((eq type 'item) (goto-char cbeg))
  17167. (t (funcall indent-to ind (min cbeg end))))
  17168. (when (< (point) end)
  17169. (cl-case type
  17170. ((example-block verse-block))
  17171. (src-block
  17172. ;; In a source block, indent source code
  17173. ;; according to language major mode, but only if
  17174. ;; `org-src-tab-acts-natively' is non-nil.
  17175. (when (and (< (point) end) org-src-tab-acts-natively)
  17176. (ignore-errors
  17177. (org-babel-do-in-edit-buffer
  17178. (indent-region (point-min) (point-max))))))
  17179. (t (org-indent-region (point) (min cend end))))
  17180. (goto-char (min cend end))
  17181. (when (< (point) end)
  17182. (funcall indent-to ind (min element-end end))))
  17183. (set-marker post nil)
  17184. (set-marker cbeg nil)
  17185. (set-marker cend nil))))
  17186. (set-marker element-end nil))))
  17187. (set-marker end nil))))
  17188. (defun org-indent-drawer ()
  17189. "Indent the drawer at point."
  17190. (interactive)
  17191. (unless (save-excursion
  17192. (beginning-of-line)
  17193. (looking-at-p org-drawer-regexp))
  17194. (user-error "Not at a drawer"))
  17195. (let ((element (org-element-at-point-no-context)))
  17196. (unless (memq (org-element-type element) '(drawer property-drawer))
  17197. (user-error "Not at a drawer"))
  17198. (org-with-wide-buffer
  17199. (org-indent-region (org-element-property :begin element)
  17200. (org-element-property :end element))))
  17201. (message "Drawer at point indented"))
  17202. (defun org-indent-block ()
  17203. "Indent the block at point."
  17204. (interactive)
  17205. (unless (save-excursion
  17206. (beginning-of-line)
  17207. (let ((case-fold-search t))
  17208. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  17209. (user-error "Not at a block"))
  17210. (let ((element (org-element-at-point-no-context)))
  17211. (unless (memq (org-element-type element)
  17212. '(comment-block center-block dynamic-block example-block
  17213. export-block quote-block special-block
  17214. src-block verse-block))
  17215. (user-error "Not at a block"))
  17216. (org-with-wide-buffer
  17217. (org-indent-region (org-element-property :begin element)
  17218. (org-element-property :end element))))
  17219. (message "Block at point indented"))
  17220. ;;; Filling
  17221. ;; We use our own fill-paragraph and auto-fill functions.
  17222. ;; `org-fill-paragraph' relies on adaptive filling and context
  17223. ;; checking. Appropriate `fill-prefix' is computed with
  17224. ;; `org-adaptive-fill-function'.
  17225. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  17226. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  17227. ;; `org-adaptive-fill-function' value. Internally,
  17228. ;; `org-comment-line-break-function' breaks the line.
  17229. ;; `org-setup-filling' installs filling and auto-filling related
  17230. ;; variables during `org-mode' initialization.
  17231. (defvar org--single-lines-list-is-paragraph) ; defined later
  17232. (defun org-setup-filling ()
  17233. (require 'org-element)
  17234. ;; Prevent auto-fill from inserting unwanted new items.
  17235. (setq-local fill-nobreak-predicate
  17236. (org-uniquify
  17237. (append fill-nobreak-predicate
  17238. '(org-fill-line-break-nobreak-p
  17239. org-fill-n-macro-as-item-nobreak-p
  17240. org-fill-paragraph-with-timestamp-nobreak-p))))
  17241. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  17242. (setq-local paragraph-start paragraph-ending)
  17243. (setq-local paragraph-separate paragraph-ending))
  17244. (setq-local fill-paragraph-function 'org-fill-paragraph)
  17245. (setq-local fill-forward-paragraph-function
  17246. (lambda (&optional arg)
  17247. (let ((org--single-lines-list-is-paragraph nil))
  17248. (org-forward-paragraph arg))))
  17249. (setq-local auto-fill-inhibit-regexp nil)
  17250. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  17251. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  17252. (setq-local comment-line-break-function 'org-comment-line-break-function))
  17253. (defun org-fill-line-break-nobreak-p ()
  17254. "Non-nil when a new line at point would create an Org line break."
  17255. (save-excursion
  17256. (skip-chars-backward " \t")
  17257. (skip-chars-backward "\\\\")
  17258. (looking-at "\\\\\\\\\\($\\|[^\\]\\)")))
  17259. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  17260. "Non-nil when a new line at point would split a timestamp."
  17261. (and (org-at-timestamp-p 'lax)
  17262. (not (looking-at org-ts-regexp-both))))
  17263. (defun org-fill-n-macro-as-item-nobreak-p ()
  17264. "Non-nil when a new line at point would create a new list."
  17265. ;; During export, a "n" macro followed by a dot or a closing
  17266. ;; parenthesis can end up being parsed as a new list item.
  17267. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  17268. (defun org-adaptive-fill-function ()
  17269. "Compute a fill prefix for the current line.
  17270. Return fill prefix, as a string, or nil if current line isn't
  17271. meant to be filled. For convenience, if `adaptive-fill-regexp'
  17272. matches in paragraphs or comments, use it."
  17273. (org-with-wide-buffer
  17274. (unless (org-at-heading-p)
  17275. (let* ((p (line-beginning-position))
  17276. (element (save-excursion
  17277. (beginning-of-line)
  17278. (org-element-at-point)))
  17279. (type (org-element-type element))
  17280. (post-affiliated (org-element-property :post-affiliated element)))
  17281. (unless (< p post-affiliated)
  17282. (cl-case type
  17283. (comment
  17284. (save-excursion
  17285. (beginning-of-line)
  17286. (looking-at "[ \t]*")
  17287. (concat (match-string 0) "# ")))
  17288. (footnote-definition "")
  17289. ((item plain-list)
  17290. (make-string (org-list-item-body-column post-affiliated) ?\s))
  17291. (paragraph
  17292. ;; Fill prefix is usually the same as the current line,
  17293. ;; unless the paragraph is at the beginning of an item.
  17294. (let ((parent (org-element-property :parent element)))
  17295. (save-excursion
  17296. (beginning-of-line)
  17297. (cond ((eq (org-element-type parent) 'item)
  17298. (make-string (org-list-item-body-column
  17299. (org-element-property :begin parent))
  17300. ?\s))
  17301. ((and adaptive-fill-regexp
  17302. ;; Locally disable
  17303. ;; `adaptive-fill-function' to let
  17304. ;; `fill-context-prefix' handle
  17305. ;; `adaptive-fill-regexp' variable.
  17306. (let (adaptive-fill-function)
  17307. (fill-context-prefix
  17308. post-affiliated
  17309. (org-element-property :end element)))))
  17310. ((looking-at "[ \t]+") (match-string 0))
  17311. (t "")))))
  17312. (comment-block
  17313. ;; Only fill contents if P is within block boundaries.
  17314. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  17315. (forward-line)
  17316. (point)))
  17317. (cend (save-excursion
  17318. (goto-char (org-element-property :end element))
  17319. (skip-chars-backward " \r\t\n")
  17320. (line-beginning-position))))
  17321. (when (and (>= p cbeg) (< p cend))
  17322. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  17323. (match-string 0)
  17324. ""))))))))))
  17325. (defun org-fill-element (&optional justify)
  17326. "Fill element at point, when applicable.
  17327. This function only applies to comment blocks, comments, example
  17328. blocks and paragraphs. Also, as a special case, re-align table
  17329. when point is at one.
  17330. If JUSTIFY is non-nil (interactively, with prefix argument),
  17331. justify as well. If `sentence-end-double-space' is non-nil, then
  17332. period followed by one space does not end a sentence, so don't
  17333. break a line there. The variable `fill-column' controls the
  17334. width for filling.
  17335. For convenience, when point is at a plain list, an item or
  17336. a footnote definition, try to fill the first paragraph within."
  17337. (with-syntax-table org-mode-transpose-word-syntax-table
  17338. ;; Move to end of line in order to get the first paragraph within
  17339. ;; a plain list or a footnote definition.
  17340. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  17341. ;; First check if point is in a blank line at the beginning of
  17342. ;; the buffer. In that case, ignore filling.
  17343. (cl-case (org-element-type element)
  17344. ;; Use major mode filling function is source blocks.
  17345. (src-block (org-babel-do-in-edit-buffer
  17346. (push-mark (point-min))
  17347. (goto-char (point-max))
  17348. (setq mark-active t)
  17349. (funcall-interactively #'fill-paragraph justify 'region)))
  17350. ;; Align Org tables, leave table.el tables as-is.
  17351. (table-row (org-table-align) t)
  17352. (table
  17353. (when (eq (org-element-property :type element) 'org)
  17354. (save-excursion
  17355. (goto-char (org-element-property :post-affiliated element))
  17356. (org-table-align)))
  17357. t)
  17358. (paragraph
  17359. ;; Paragraphs may contain `line-break' type objects.
  17360. (let ((beg (max (point-min)
  17361. (org-element-property :contents-begin element)))
  17362. (end (min (point-max)
  17363. (org-element-property :contents-end element))))
  17364. ;; Do nothing if point is at an affiliated keyword.
  17365. (if (< (line-end-position) beg) t
  17366. ;; Fill paragraph, taking line breaks into account.
  17367. (save-excursion
  17368. (goto-char beg)
  17369. (let ((cuts (list beg)))
  17370. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  17371. (when (eq 'line-break
  17372. (org-element-type
  17373. (save-excursion (backward-char)
  17374. (org-element-context))))
  17375. (push (point) cuts)))
  17376. (dolist (c (delq end cuts))
  17377. (fill-region-as-paragraph c end justify)
  17378. (setq end c))))
  17379. t)))
  17380. ;; Contents of `comment-block' type elements should be
  17381. ;; filled as plain text, but only if point is within block
  17382. ;; markers.
  17383. (comment-block
  17384. (let* ((case-fold-search t)
  17385. (beg (save-excursion
  17386. (goto-char (org-element-property :begin element))
  17387. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  17388. (forward-line)
  17389. (point)))
  17390. (end (save-excursion
  17391. (goto-char (org-element-property :end element))
  17392. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  17393. (line-beginning-position))))
  17394. (if (or (< (point) beg) (> (point) end)) t
  17395. (fill-region-as-paragraph
  17396. (save-excursion (end-of-line)
  17397. (re-search-backward "^[ \t]*$" beg 'move)
  17398. (line-beginning-position))
  17399. (save-excursion (beginning-of-line)
  17400. (re-search-forward "^[ \t]*$" end 'move)
  17401. (line-beginning-position))
  17402. justify))))
  17403. ;; Fill comments.
  17404. (comment
  17405. (let ((begin (org-element-property :post-affiliated element))
  17406. (end (org-element-property :end element)))
  17407. (when (and (>= (point) begin) (<= (point) end))
  17408. (let ((begin (save-excursion
  17409. (end-of-line)
  17410. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  17411. (progn (forward-line) (point))
  17412. begin)))
  17413. (end (save-excursion
  17414. (end-of-line)
  17415. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  17416. (1- (line-beginning-position))
  17417. (skip-chars-backward " \r\t\n")
  17418. (line-end-position)))))
  17419. ;; Do not fill comments when at a blank line.
  17420. (when (> end begin)
  17421. (let ((fill-prefix
  17422. (save-excursion
  17423. (beginning-of-line)
  17424. (looking-at "[ \t]*#")
  17425. (let ((comment-prefix (match-string 0)))
  17426. (goto-char (match-end 0))
  17427. (if (looking-at adaptive-fill-regexp)
  17428. (concat comment-prefix (match-string 0))
  17429. (concat comment-prefix " "))))))
  17430. (save-excursion
  17431. (fill-region-as-paragraph begin end justify))))))
  17432. t))
  17433. ;; Ignore every other element.
  17434. (otherwise t)))))
  17435. (defun org-fill-paragraph (&optional justify region)
  17436. "Fill element at point, when applicable.
  17437. This function only applies to comment blocks, comments, example
  17438. blocks and paragraphs. Also, as a special case, re-align table
  17439. when point is at one.
  17440. For convenience, when point is at a plain list, an item or
  17441. a footnote definition, try to fill the first paragraph within.
  17442. If JUSTIFY is non-nil (interactively, with prefix argument),
  17443. justify as well. If `sentence-end-double-space' is non-nil, then
  17444. period followed by one space does not end a sentence, so don't
  17445. break a line there. The variable `fill-column' controls the
  17446. width for filling.
  17447. The REGION argument is non-nil if called interactively; in that
  17448. case, if Transient Mark mode is enabled and the mark is active,
  17449. fill each of the elements in the active region, instead of just
  17450. filling the current element."
  17451. (interactive (progn
  17452. (barf-if-buffer-read-only)
  17453. (list (when current-prefix-arg 'full) t)))
  17454. (let ((hash (and (not (buffer-modified-p))
  17455. (org-buffer-hash))))
  17456. (cond
  17457. ((and region transient-mark-mode mark-active
  17458. (not (eq (region-beginning) (region-end))))
  17459. (let ((origin (point-marker))
  17460. (start (region-beginning)))
  17461. (unwind-protect
  17462. (progn
  17463. (goto-char (region-end))
  17464. (skip-chars-backward " \t\n")
  17465. (let ((org--single-lines-list-is-paragraph nil))
  17466. (while (> (point) start)
  17467. (org-fill-element justify)
  17468. (org-backward-paragraph)
  17469. (skip-chars-backward " \t\n"))))
  17470. (goto-char origin)
  17471. (set-marker origin nil))))
  17472. (t
  17473. (save-excursion
  17474. (when (org-match-line "[ \t]*$")
  17475. (skip-chars-forward " \t\n"))
  17476. (org-fill-element justify))))
  17477. ;; If we didn't change anything in the buffer (and the buffer was
  17478. ;; previously unmodified), then flip the modification status back
  17479. ;; to "unchanged".
  17480. (when (and hash (equal hash (org-buffer-hash)))
  17481. (set-buffer-modified-p nil))
  17482. ;; Return non-nil.
  17483. t))
  17484. (defun org-auto-fill-function ()
  17485. "Auto-fill function."
  17486. ;; Check if auto-filling is meaningful.
  17487. (let ((fc (current-fill-column)))
  17488. (when (and fc (> (current-column) fc))
  17489. (let* ((fill-prefix (org-adaptive-fill-function))
  17490. ;; Enforce empty fill prefix, if required. Otherwise, it
  17491. ;; will be computed again.
  17492. (adaptive-fill-mode (not (equal fill-prefix ""))))
  17493. (when fill-prefix (do-auto-fill))))))
  17494. (defun org-comment-line-break-function (&optional soft)
  17495. "Break line at point and indent, continuing comment if within one.
  17496. The inserted newline is marked hard if variable
  17497. `use-hard-newlines' is true, unless optional argument SOFT is
  17498. non-nil."
  17499. (if soft (insert-and-inherit ?\n) (newline 1))
  17500. (save-excursion (forward-char -1) (delete-horizontal-space))
  17501. (delete-horizontal-space)
  17502. (indent-to-left-margin)
  17503. (insert-before-markers-and-inherit fill-prefix))
  17504. ;;; Fixed Width Areas
  17505. (defun org-toggle-fixed-width ()
  17506. "Toggle fixed-width markup.
  17507. Add or remove fixed-width markup on current line, whenever it
  17508. makes sense. Return an error otherwise.
  17509. If a region is active and if it contains only fixed-width areas
  17510. or blank lines, remove all fixed-width markup in it. If the
  17511. region contains anything else, convert all non-fixed-width lines
  17512. to fixed-width ones.
  17513. Blank lines at the end of the region are ignored unless the
  17514. region only contains such lines."
  17515. (interactive)
  17516. (if (not (org-region-active-p))
  17517. ;; No region:
  17518. ;;
  17519. ;; Remove fixed width marker only in a fixed-with element.
  17520. ;;
  17521. ;; Add fixed width maker in paragraphs, in blank lines after
  17522. ;; elements or at the beginning of a headline or an inlinetask,
  17523. ;; and before any one-line elements (e.g., a clock).
  17524. (progn
  17525. (beginning-of-line)
  17526. (let* ((element (org-element-at-point))
  17527. (type (org-element-type element)))
  17528. (cond
  17529. ((and (eq type 'fixed-width)
  17530. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  17531. (replace-match
  17532. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  17533. ((and (memq type '(babel-call clock comment diary-sexp headline
  17534. horizontal-rule keyword paragraph
  17535. planning))
  17536. (<= (org-element-property :post-affiliated element) (point)))
  17537. (skip-chars-forward " \t")
  17538. (insert ": "))
  17539. ((and (looking-at-p "[ \t]*$")
  17540. (or (eq type 'inlinetask)
  17541. (save-excursion
  17542. (skip-chars-forward " \r\t\n")
  17543. (<= (org-element-property :end element) (point)))))
  17544. (delete-region (point) (line-end-position))
  17545. (org-indent-line)
  17546. (insert ": "))
  17547. (t (user-error "Cannot insert a fixed-width line here")))))
  17548. ;; Region active.
  17549. (let* ((begin (save-excursion
  17550. (goto-char (region-beginning))
  17551. (line-beginning-position)))
  17552. (end (copy-marker
  17553. (save-excursion
  17554. (goto-char (region-end))
  17555. (unless (eolp) (beginning-of-line))
  17556. (if (save-excursion (re-search-backward "\\S-" begin t))
  17557. (progn (skip-chars-backward " \r\t\n") (point))
  17558. (point)))))
  17559. (all-fixed-width-p
  17560. (catch 'not-all-p
  17561. (save-excursion
  17562. (goto-char begin)
  17563. (skip-chars-forward " \r\t\n")
  17564. (when (eobp) (throw 'not-all-p nil))
  17565. (while (< (point) end)
  17566. (let ((element (org-element-at-point)))
  17567. (if (eq (org-element-type element) 'fixed-width)
  17568. (goto-char (org-element-property :end element))
  17569. (throw 'not-all-p nil))))
  17570. t))))
  17571. (if all-fixed-width-p
  17572. (save-excursion
  17573. (goto-char begin)
  17574. (while (< (point) end)
  17575. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  17576. (replace-match
  17577. "" nil nil nil
  17578. (if (= (line-end-position) (match-end 0)) 0 1)))
  17579. (forward-line)))
  17580. (let ((min-ind (point-max)))
  17581. ;; Find minimum indentation across all lines.
  17582. (save-excursion
  17583. (goto-char begin)
  17584. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  17585. (setq min-ind 0)
  17586. (catch 'zerop
  17587. (while (< (point) end)
  17588. (unless (looking-at-p "[ \t]*$")
  17589. (let ((ind (current-indentation)))
  17590. (setq min-ind (min min-ind ind))
  17591. (when (zerop ind) (throw 'zerop t))))
  17592. (forward-line)))))
  17593. ;; Loop over all lines and add fixed-width markup everywhere
  17594. ;; but in fixed-width lines.
  17595. (save-excursion
  17596. (goto-char begin)
  17597. (while (< (point) end)
  17598. (cond
  17599. ((org-at-heading-p)
  17600. (insert ": ")
  17601. (forward-line)
  17602. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  17603. (insert ":")
  17604. (forward-line)))
  17605. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  17606. (let* ((element (org-element-at-point))
  17607. (element-end (org-element-property :end element)))
  17608. (if (eq (org-element-type element) 'fixed-width)
  17609. (progn (goto-char element-end)
  17610. (skip-chars-backward " \r\t\n")
  17611. (forward-line))
  17612. (let ((limit (min end element-end)))
  17613. (while (< (point) limit)
  17614. (org-move-to-column min-ind t)
  17615. (insert ": ")
  17616. (forward-line))))))
  17617. (t
  17618. (org-move-to-column min-ind t)
  17619. (insert ": ")
  17620. (forward-line)))))))
  17621. (set-marker end nil))))
  17622. ;;; Blocks
  17623. (defun org-block-map (function &optional start end)
  17624. "Call FUNCTION at the head of all source blocks in the current buffer.
  17625. Optional arguments START and END can be used to limit the range."
  17626. (let ((start (or start (point-min)))
  17627. (end (or end (point-max))))
  17628. (save-excursion
  17629. (goto-char start)
  17630. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  17631. (save-excursion
  17632. (save-match-data
  17633. (goto-char (match-beginning 0))
  17634. (funcall function)))))))
  17635. (defun org-next-block (arg &optional backward block-regexp)
  17636. "Jump to the next block.
  17637. With a prefix argument ARG, jump forward ARG many blocks.
  17638. When BACKWARD is non-nil, jump to the previous block.
  17639. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  17640. Match data is set according to this regexp when the function
  17641. returns.
  17642. Return point at beginning of the opening line of found block.
  17643. Throw an error if no block is found."
  17644. (interactive "p")
  17645. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  17646. (case-fold-search t)
  17647. (search-fn (if backward #'re-search-backward #'re-search-forward))
  17648. (count (or arg 1))
  17649. (origin (point))
  17650. last-element)
  17651. (if backward (beginning-of-line) (end-of-line))
  17652. (while (and (> count 0) (funcall search-fn re nil t))
  17653. (let ((element (save-excursion
  17654. (goto-char (match-beginning 0))
  17655. (save-match-data (org-element-at-point)))))
  17656. (when (and (memq (org-element-type element)
  17657. '(center-block comment-block dynamic-block
  17658. example-block export-block quote-block
  17659. special-block src-block verse-block))
  17660. (<= (match-beginning 0)
  17661. (org-element-property :post-affiliated element)))
  17662. (setq last-element element)
  17663. (cl-decf count))))
  17664. (if (= count 0)
  17665. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  17666. (save-match-data (org-fold-show-context)))
  17667. (goto-char origin)
  17668. (user-error "No %s code blocks" (if backward "previous" "further")))))
  17669. (defun org-previous-block (arg &optional block-regexp)
  17670. "Jump to the previous block.
  17671. With a prefix argument ARG, jump backward ARG many source blocks.
  17672. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  17673. (interactive "p")
  17674. (org-next-block arg t block-regexp))
  17675. ;;; Comments
  17676. ;; Org comments syntax is quite complex. It requires the entire line
  17677. ;; to be just a comment. Also, even with the right syntax at the
  17678. ;; beginning of line, some elements (e.g., verse-block or
  17679. ;; example-block) don't accept comments. Usual Emacs comment commands
  17680. ;; cannot cope with those requirements. Therefore, Org replaces them.
  17681. ;; Org still relies on 'comment-dwim', but cannot trust
  17682. ;; 'comment-only-p'. So, 'comment-region-function' and
  17683. ;; 'uncomment-region-function' both point
  17684. ;; to 'org-comment-or-uncomment-region'. Eventually,
  17685. ;; 'org-insert-comment' takes care of insertion of comments at the
  17686. ;; beginning of line.
  17687. ;; 'org-setup-comments-handling' install comments related variables
  17688. ;; during 'org-mode' initialization.
  17689. (defun org-setup-comments-handling ()
  17690. (interactive)
  17691. (setq-local comment-use-syntax nil)
  17692. (setq-local comment-start "# ")
  17693. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  17694. (setq-local comment-insert-comment-function 'org-insert-comment)
  17695. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  17696. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  17697. (defun org-insert-comment ()
  17698. "Insert an empty comment above current line.
  17699. If the line is empty, insert comment at its beginning. When
  17700. point is within a source block, comment according to the related
  17701. major mode."
  17702. (if (let ((element (org-element-at-point)))
  17703. (and (eq (org-element-type element) 'src-block)
  17704. (< (save-excursion
  17705. (goto-char (org-element-property :post-affiliated element))
  17706. (line-end-position))
  17707. (point))
  17708. (> (save-excursion
  17709. (goto-char (org-element-property :end element))
  17710. (skip-chars-backward " \r\t\n")
  17711. (line-beginning-position))
  17712. (point))))
  17713. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  17714. (beginning-of-line)
  17715. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  17716. (open-line 1))
  17717. (org-indent-line)
  17718. (insert "# ")))
  17719. (defvar comment-empty-lines) ; From newcomment.el.
  17720. (defun org-comment-or-uncomment-region (beg end &rest _)
  17721. "Comment or uncomment each non-blank line in the region.
  17722. Uncomment each non-blank line between BEG and END if it only
  17723. contains commented lines. Otherwise, comment them. If region is
  17724. strictly within a source block, use appropriate comment syntax."
  17725. (if (let ((element (org-element-at-point)))
  17726. (and (eq (org-element-type element) 'src-block)
  17727. (< (save-excursion
  17728. (goto-char (org-element-property :post-affiliated element))
  17729. (line-end-position))
  17730. beg)
  17731. (>= (save-excursion
  17732. (goto-char (org-element-property :end element))
  17733. (skip-chars-backward " \r\t\n")
  17734. (line-beginning-position))
  17735. end)))
  17736. ;; Translate region boundaries for the Org buffer to the source
  17737. ;; buffer.
  17738. (let ((offset (- end beg)))
  17739. (save-excursion
  17740. (goto-char beg)
  17741. (org-babel-do-in-edit-buffer
  17742. (comment-or-uncomment-region (point) (+ offset (point))))))
  17743. (save-restriction
  17744. ;; Restrict region
  17745. (narrow-to-region (save-excursion (goto-char beg)
  17746. (skip-chars-forward " \r\t\n" end)
  17747. (line-beginning-position))
  17748. (save-excursion (goto-char end)
  17749. (skip-chars-backward " \r\t\n" beg)
  17750. (line-end-position)))
  17751. (let ((uncommentp
  17752. ;; UNCOMMENTP is non-nil when every non blank line between
  17753. ;; BEG and END is a comment.
  17754. (save-excursion
  17755. (goto-char (point-min))
  17756. (while (and (not (eobp))
  17757. (let ((element (org-element-at-point)))
  17758. (and (eq (org-element-type element) 'comment)
  17759. (goto-char (min (point-max)
  17760. (org-element-property
  17761. :end element)))))))
  17762. (eobp))))
  17763. (if uncommentp
  17764. ;; Only blank lines and comments in region: uncomment it.
  17765. (save-excursion
  17766. (goto-char (point-min))
  17767. (while (not (eobp))
  17768. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  17769. (replace-match "" nil nil nil 1))
  17770. (forward-line)))
  17771. ;; Comment each line in region.
  17772. (let ((min-indent (point-max)))
  17773. ;; First find the minimum indentation across all lines.
  17774. (save-excursion
  17775. (goto-char (point-min))
  17776. (while (and (not (eobp)) (not (zerop min-indent)))
  17777. (unless (looking-at "[ \t]*$")
  17778. (setq min-indent (min min-indent (current-indentation))))
  17779. (forward-line)))
  17780. ;; Then loop over all lines.
  17781. (save-excursion
  17782. (goto-char (point-min))
  17783. (while (not (eobp))
  17784. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  17785. ;; Don't get fooled by invisible text (e.g. link path)
  17786. ;; when moving to column MIN-INDENT.
  17787. (let ((buffer-invisibility-spec nil))
  17788. (org-move-to-column min-indent t))
  17789. (insert comment-start))
  17790. (forward-line)))))))))
  17791. (defun org-comment-dwim (_arg)
  17792. "Call the comment command you mean.
  17793. Call `org-toggle-comment' if on a heading, otherwise call
  17794. `comment-dwim', within a source edit buffer if needed."
  17795. (interactive "*P")
  17796. (cond ((org-at-heading-p)
  17797. (call-interactively #'org-toggle-comment))
  17798. ((org-in-src-block-p)
  17799. (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
  17800. (t (call-interactively #'comment-dwim))))
  17801. ;;; Timestamps API
  17802. ;; This section contains tools to operate on, or create, timestamp
  17803. ;; objects, as returned by, e.g. `org-element-context'.
  17804. (defun org-timestamp-from-string (s)
  17805. "Convert Org timestamp S, as a string, into a timestamp object.
  17806. Return nil if S is not a valid timestamp string."
  17807. (when (org-string-nw-p s)
  17808. (with-temp-buffer
  17809. (save-excursion (insert s))
  17810. (org-element-timestamp-parser))))
  17811. (defun org-timestamp-from-time (time &optional with-time inactive)
  17812. "Convert a time value into a timestamp object.
  17813. TIME is an Emacs internal time representation, as returned, e.g.,
  17814. by `current-time'.
  17815. When optional argument WITH-TIME is non-nil, return a timestamp
  17816. object with a time part, i.e., with hours and minutes.
  17817. Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
  17818. return an active timestamp."
  17819. (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
  17820. (org-element-create 'timestamp
  17821. (list :type (if inactive 'inactive 'active)
  17822. :year-start year
  17823. :month-start month
  17824. :day-start day
  17825. :hour-start (and with-time hour)
  17826. :minute-start (and with-time minute)))))
  17827. (defun org-timestamp-to-time (timestamp &optional end)
  17828. "Convert TIMESTAMP object into an Emacs internal time value.
  17829. Use end of date range or time range when END is non-nil.
  17830. Otherwise, use its start."
  17831. (org-encode-time
  17832. (append '(0)
  17833. (mapcar
  17834. (lambda (prop) (or (org-element-property prop timestamp) 0))
  17835. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  17836. '(:minute-start :hour-start :day-start :month-start
  17837. :year-start)))
  17838. '(nil -1 nil))))
  17839. (defun org-timestamp-has-time-p (timestamp)
  17840. "Non-nil when TIMESTAMP has a time specified."
  17841. (org-element-property :hour-start timestamp))
  17842. (defun org-timestamp-format (timestamp format &optional end utc)
  17843. "Format a TIMESTAMP object into a string.
  17844. FORMAT is a format specifier to be passed to
  17845. `format-time-string'.
  17846. When optional argument END is non-nil, use end of date-range or
  17847. time-range, if possible.
  17848. When optional argument UTC is non-nil, time is be expressed as
  17849. Universal Time."
  17850. (format-time-string format (org-timestamp-to-time timestamp end)
  17851. (and utc t)))
  17852. (defun org-timestamp-split-range (timestamp &optional end)
  17853. "Extract a TIMESTAMP object from a date or time range.
  17854. END, when non-nil, means extract the end of the range.
  17855. Otherwise, extract its start.
  17856. Return a new timestamp object."
  17857. (let ((type (org-element-property :type timestamp)))
  17858. (if (memq type '(active inactive diary)) timestamp
  17859. (let ((split-ts (org-element-copy timestamp)))
  17860. ;; Set new type.
  17861. (org-element-put-property
  17862. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  17863. ;; Copy start properties over end properties if END is
  17864. ;; non-nil. Otherwise, copy end properties over `start' ones.
  17865. (let ((p-alist '((:minute-start . :minute-end)
  17866. (:hour-start . :hour-end)
  17867. (:day-start . :day-end)
  17868. (:month-start . :month-end)
  17869. (:year-start . :year-end))))
  17870. (dolist (p-cell p-alist)
  17871. (org-element-put-property
  17872. split-ts
  17873. (funcall (if end #'car #'cdr) p-cell)
  17874. (org-element-property
  17875. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  17876. ;; Eventually refresh `:raw-value'.
  17877. (org-element-put-property split-ts :raw-value nil)
  17878. (org-element-put-property
  17879. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  17880. (defun org-timestamp-translate (timestamp &optional boundary)
  17881. "Translate TIMESTAMP object to custom format.
  17882. Format string is defined in `org-time-stamp-custom-formats',
  17883. which see.
  17884. When optional argument BOUNDARY is non-nil, it is either the
  17885. symbol `start' or `end'. In this case, only translate the
  17886. starting or ending part of TIMESTAMP if it is a date or time
  17887. range. Otherwise, translate both parts.
  17888. Return timestamp as-is if `org-display-custom-times' is nil or if
  17889. it has a `diary' type."
  17890. (let ((type (org-element-property :type timestamp)))
  17891. (if (or (not org-display-custom-times) (eq type 'diary))
  17892. (org-element-interpret-data timestamp)
  17893. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  17894. org-time-stamp-custom-formats)))
  17895. (if (and (not boundary) (memq type '(active-range inactive-range)))
  17896. (concat (org-timestamp-format timestamp fmt)
  17897. "--"
  17898. (org-timestamp-format timestamp fmt t))
  17899. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  17900. ;;; Other stuff
  17901. (defvar reftex-docstruct-symbol)
  17902. (defvar org--rds)
  17903. (defun org-reftex-citation ()
  17904. "Use `reftex-citation' to insert a citation into the buffer.
  17905. This looks for a line like
  17906. #+BIBLIOGRAPHY: foo plain option:-d
  17907. and derives from it that foo.bib is the bibliography file relevant
  17908. for this document. It then installs the necessary environment for RefTeX
  17909. to work in this buffer and calls `reftex-citation' to insert a citation
  17910. into the buffer.
  17911. Export of such citations to both LaTeX and HTML is handled by the contributed
  17912. package ox-bibtex by Taru Karttunen."
  17913. (interactive)
  17914. (let ((reftex-docstruct-symbol 'org--rds)
  17915. org--rds bib)
  17916. (org-with-wide-buffer
  17917. (let ((case-fold-search t)
  17918. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  17919. (if (not (save-excursion
  17920. (or (re-search-forward re nil t)
  17921. (re-search-backward re nil t))))
  17922. (user-error "No bibliography defined in file")
  17923. (setq bib (concat (match-string 1) ".bib")
  17924. org--rds (list (list 'bib bib))))))
  17925. (call-interactively 'reftex-citation)))
  17926. ;;;; Functions extending outline functionality
  17927. (defun org-beginning-of-line (&optional n)
  17928. "Go to the beginning of the current visible line.
  17929. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  17930. symbol `reversed', on the first attempt move to where the
  17931. headline text starts, and only move to beginning of line when the
  17932. cursor is already before the start of the text of the headline.
  17933. If `org-special-ctrl-a/e' is symbol `reversed' then go to the
  17934. start of the text on the second attempt.
  17935. With argument N not nil or 1, move forward N - 1 lines first."
  17936. (interactive "^p")
  17937. (let ((origin (point))
  17938. (special (pcase org-special-ctrl-a/e
  17939. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  17940. deactivate-mark)
  17941. ;; First move to a visible line.
  17942. (if (bound-and-true-p visual-line-mode)
  17943. (beginning-of-visual-line n)
  17944. (move-beginning-of-line n)
  17945. ;; `move-beginning-of-line' may leave point after invisible
  17946. ;; characters if line starts with such of these (e.g., with
  17947. ;; a link at column 0). Really move to the beginning of the
  17948. ;; current visible line.
  17949. (beginning-of-line))
  17950. (cond
  17951. ;; No special behavior. Point is already at the beginning of
  17952. ;; a line, logical or visual.
  17953. ((not special))
  17954. ;; `beginning-of-visual-line' left point before logical beginning
  17955. ;; of line: point is at the beginning of a visual line. Bail
  17956. ;; out.
  17957. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  17958. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  17959. ;; At a headline, special position is before the title, but
  17960. ;; after any TODO keyword or priority cookie.
  17961. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  17962. (line-end-position)))
  17963. (bol (point)))
  17964. (if (eq special 'reversed)
  17965. (when (and (= origin bol) (eq last-command this-command))
  17966. (goto-char refpos))
  17967. (when (or (> origin refpos) (= origin bol))
  17968. (goto-char refpos)))))
  17969. ((and (looking-at org-list-full-item-re)
  17970. (memq (org-element-type (save-match-data (org-element-at-point)))
  17971. '(item plain-list)))
  17972. ;; Set special position at first white space character after
  17973. ;; bullet, and check-box, if any.
  17974. (let ((after-bullet
  17975. (let ((box (match-end 3)))
  17976. (cond ((not box) (match-end 1))
  17977. ((eq (char-after box) ?\s) (1+ box))
  17978. (t box)))))
  17979. (if (eq special 'reversed)
  17980. (when (and (= (point) origin) (eq last-command this-command))
  17981. (goto-char after-bullet))
  17982. (when (or (> origin after-bullet) (= (point) origin))
  17983. (goto-char after-bullet)))))
  17984. ;; No special context. Point is already at beginning of line.
  17985. (t nil))))
  17986. (defun org-end-of-line (&optional n)
  17987. "Go to the end of the line, but before ellipsis, if any.
  17988. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  17989. symbol `reversed', ignore tags on the first attempt, and only
  17990. move to after the tags when the cursor is already beyond the end
  17991. of the headline.
  17992. If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
  17993. on the second attempt.
  17994. With argument N not nil or 1, move forward N - 1 lines first."
  17995. (interactive "^p")
  17996. (let ((origin (point))
  17997. (special (pcase org-special-ctrl-a/e
  17998. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  17999. deactivate-mark)
  18000. ;; First move to a visible line.
  18001. (if (bound-and-true-p visual-line-mode)
  18002. (beginning-of-visual-line n)
  18003. (move-beginning-of-line n))
  18004. (cond
  18005. ;; At a headline, with tags.
  18006. ((and special
  18007. (save-excursion
  18008. (beginning-of-line)
  18009. (let ((case-fold-search nil))
  18010. (looking-at org-complex-heading-regexp)))
  18011. (match-end 5))
  18012. (let ((tags (save-excursion
  18013. (goto-char (match-beginning 5))
  18014. (skip-chars-backward " \t")
  18015. (point)))
  18016. (visual-end (and (bound-and-true-p visual-line-mode)
  18017. (save-excursion
  18018. (end-of-visual-line)
  18019. (point)))))
  18020. ;; If `end-of-visual-line' brings us before end of line or
  18021. ;; even tags, i.e., the headline spans over multiple visual
  18022. ;; lines, move there.
  18023. (cond ((and visual-end
  18024. (< visual-end tags)
  18025. (<= origin visual-end))
  18026. (goto-char visual-end))
  18027. ((eq special 'reversed)
  18028. (if (and (= origin (line-end-position))
  18029. (eq this-command last-command))
  18030. (goto-char tags)
  18031. (end-of-line)))
  18032. (t
  18033. (if (or (< origin tags) (= origin (line-end-position)))
  18034. (goto-char tags)
  18035. (end-of-line))))))
  18036. ((bound-and-true-p visual-line-mode)
  18037. (let ((bol (line-beginning-position)))
  18038. (end-of-visual-line)
  18039. ;; If `end-of-visual-line' gets us past the ellipsis at the
  18040. ;; end of a line, backtrack and use `end-of-line' instead.
  18041. (when (/= bol (line-beginning-position))
  18042. (goto-char bol)
  18043. (end-of-line))))
  18044. (t (end-of-line)))))
  18045. (defun org-backward-sentence (&optional _arg)
  18046. "Go to beginning of sentence, or beginning of table field.
  18047. This will call `backward-sentence' or `org-table-beginning-of-field',
  18048. depending on context."
  18049. (interactive)
  18050. (let* ((element (org-element-at-point))
  18051. (contents-begin (org-element-property :contents-begin element))
  18052. (table (org-element-lineage element '(table) t)))
  18053. (if (and table
  18054. (> (point) contents-begin)
  18055. (<= (point) (org-element-property :contents-end table)))
  18056. (call-interactively #'org-table-beginning-of-field)
  18057. (save-restriction
  18058. (when (and contents-begin
  18059. (< (point-min) contents-begin)
  18060. (> (point) contents-begin))
  18061. (narrow-to-region contents-begin
  18062. (org-element-property :contents-end element)))
  18063. (call-interactively #'backward-sentence)))))
  18064. (defun org-forward-sentence (&optional _arg)
  18065. "Go to end of sentence, or end of table field.
  18066. This will call `forward-sentence' or `org-table-end-of-field',
  18067. depending on context."
  18068. (interactive)
  18069. (if (and (org-at-heading-p)
  18070. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  18071. (save-restriction
  18072. (narrow-to-region (line-beginning-position) (line-end-position))
  18073. (call-interactively #'forward-sentence))
  18074. (let* ((element (org-element-at-point))
  18075. (contents-end (org-element-property :contents-end element))
  18076. (table (org-element-lineage element '(table) t)))
  18077. (if (and table
  18078. (>= (point) (org-element-property :contents-begin table))
  18079. (< (point) contents-end))
  18080. (call-interactively #'org-table-end-of-field)
  18081. (save-restriction
  18082. (when (and contents-end
  18083. (> (point-max) contents-end)
  18084. ;; Skip blank lines between elements.
  18085. (< (org-element-property :end element)
  18086. (save-excursion (goto-char contents-end)
  18087. (skip-chars-forward " \r\t\n"))))
  18088. (narrow-to-region (org-element-property :contents-begin element)
  18089. contents-end))
  18090. ;; End of heading is considered as the end of a sentence.
  18091. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  18092. (call-interactively #'forward-sentence)))))))
  18093. (defun org-kill-line (&optional _arg)
  18094. "Kill line, to tags or end of line."
  18095. (interactive)
  18096. (cond
  18097. ((or (not org-special-ctrl-k)
  18098. (bolp)
  18099. (not (org-at-heading-p)))
  18100. (when (and (org-invisible-p (line-end-position))
  18101. org-ctrl-k-protect-subtree
  18102. (or (eq org-ctrl-k-protect-subtree 'error)
  18103. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  18104. (user-error
  18105. (substitute-command-keys
  18106. "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
  18107. (call-interactively
  18108. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  18109. ((org-match-line org-tag-line-re)
  18110. (let ((end (save-excursion
  18111. (goto-char (match-beginning 1))
  18112. (skip-chars-backward " \t")
  18113. (point))))
  18114. (if (<= end (point)) ;on tags part
  18115. (kill-region (point) (line-end-position))
  18116. (kill-region (point) end)))
  18117. ;; Only align tags when we are still on a heading:
  18118. (if (org-at-heading-p) (org-align-tags)))
  18119. (t (kill-region (point) (line-end-position)))))
  18120. (defun org-yank (&optional arg)
  18121. "Yank. If the kill is a subtree, treat it specially.
  18122. This command will look at the current kill and check if is a single
  18123. subtree, or a series of subtrees[1]. If it passes the test, and if the
  18124. cursor is at the beginning of a line or after the stars of a currently
  18125. empty headline, then the yank is handled specially. How exactly depends
  18126. on the value of the following variables.
  18127. `org-yank-folded-subtrees'
  18128. By default, this variable is non-nil, which results in
  18129. subtree(s) being folded after insertion, except if doing so
  18130. would swallow text after the yanked text.
  18131. `org-yank-adjusted-subtrees'
  18132. When non-nil (the default value is nil), the subtree will be
  18133. promoted or demoted in order to fit into the local outline tree
  18134. structure, which means that the level will be adjusted so that it
  18135. becomes the smaller one of the two *visible* surrounding headings.
  18136. Any prefix to this command will cause `yank' to be called directly with
  18137. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  18138. will just
  18139. plainly yank the text as it is.
  18140. \[1] The test checks if the first non-white line is a heading
  18141. and if there are no other headings with fewer stars."
  18142. (interactive "P")
  18143. (org-yank-generic 'yank arg))
  18144. (defun org-yank-generic (command arg)
  18145. "Perform some yank-like command.
  18146. This function implements the behavior described in the `org-yank'
  18147. documentation. However, it has been generalized to work for any
  18148. interactive command with similar behavior."
  18149. ;; pretend to be command COMMAND
  18150. (setq this-command command)
  18151. (if arg
  18152. (call-interactively command)
  18153. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  18154. (and (org-kill-is-subtree-p)
  18155. (or (bolp)
  18156. (and (looking-at "[ \t]*$")
  18157. (string-match
  18158. "\\`\\*+\\'"
  18159. (buffer-substring (point-at-bol) (point)))))))
  18160. swallowp)
  18161. (cond
  18162. ((and subtreep org-yank-folded-subtrees)
  18163. (let ((beg (point))
  18164. end)
  18165. (if (and subtreep org-yank-adjusted-subtrees)
  18166. (org-paste-subtree nil nil 'for-yank)
  18167. (call-interactively command))
  18168. (setq end (point))
  18169. (goto-char beg)
  18170. (when (and (bolp) subtreep
  18171. (not (setq swallowp
  18172. (org-yank-folding-would-swallow-text beg end))))
  18173. (org-with-limited-levels
  18174. (or (looking-at org-outline-regexp)
  18175. (re-search-forward org-outline-regexp-bol end t))
  18176. (while (and (< (point) end) (looking-at org-outline-regexp))
  18177. (org-fold-subtree t)
  18178. (org-cycle-show-empty-lines 'folded)
  18179. (condition-case nil
  18180. (outline-forward-same-level 1)
  18181. (error (goto-char end))))))
  18182. (when swallowp
  18183. (message
  18184. "Inserted text not folded because that would swallow text"))
  18185. (goto-char end)
  18186. (skip-chars-forward " \t\n\r")
  18187. (beginning-of-line 1)
  18188. (push-mark beg 'nomsg)))
  18189. ((and subtreep org-yank-adjusted-subtrees)
  18190. (let ((beg (point-at-bol)))
  18191. (org-paste-subtree nil nil 'for-yank)
  18192. (push-mark beg 'nomsg)))
  18193. (t
  18194. (call-interactively command))))))
  18195. (defun org-yank-folding-would-swallow-text (beg end)
  18196. "Would `hide-subtree' at BEG swallow any text after END?"
  18197. (let (level)
  18198. (org-with-limited-levels
  18199. (save-excursion
  18200. (goto-char beg)
  18201. (when (or (looking-at org-outline-regexp)
  18202. (re-search-forward org-outline-regexp-bol end t))
  18203. (setq level (org-outline-level)))
  18204. (goto-char end)
  18205. (skip-chars-forward " \t\r\n\v\f")
  18206. (not (or (eobp)
  18207. (and (bolp) (looking-at-p org-outline-regexp)
  18208. (<= (org-outline-level) level))))))))
  18209. (defun org-back-to-heading (&optional invisible-ok)
  18210. "Go back to beginning of heading."
  18211. (beginning-of-line)
  18212. (or (org-at-heading-p (not invisible-ok))
  18213. (let (found)
  18214. (save-excursion
  18215. ;; At inlinetask end. Move to bol, so that the following
  18216. ;; search goes to the beginning of the inlinetask.
  18217. (when (and (featurep 'org-inlinetask)
  18218. (fboundp 'org-inlinetask-end-p)
  18219. (org-inlinetask-end-p))
  18220. (goto-char (line-beginning-position)))
  18221. (while (not found)
  18222. (or (re-search-backward (concat "^\\(?:" outline-regexp "\\)")
  18223. nil t)
  18224. (user-error "Before first headline at position %d in buffer %s"
  18225. (point) (current-buffer)))
  18226. ;; Skip inlinetask end.
  18227. (if (and (featurep 'org-inlinetask)
  18228. (fboundp 'org-inlinetask-end-p)
  18229. (org-inlinetask-end-p))
  18230. (org-inlinetask-goto-beginning)
  18231. (setq found (and (or invisible-ok (not (org-fold-folded-p)))
  18232. (point))))))
  18233. (goto-char found)
  18234. found)))
  18235. (defun org-back-to-heading-or-point-min (&optional invisible-ok)
  18236. "Go back to heading or first point in buffer.
  18237. If point is before first heading go to first point in buffer
  18238. instead of back to heading."
  18239. (if (org-before-first-heading-p)
  18240. (goto-char (point-min))
  18241. (org-back-to-heading invisible-ok)))
  18242. (defun org-before-first-heading-p ()
  18243. "Before first heading?
  18244. Respect narrowing."
  18245. (let ((cached (org-element-at-point nil 'cached)))
  18246. (if cached
  18247. (let ((cached-headline (org-element-lineage cached '(headline) t)))
  18248. (or (not cached-headline)
  18249. (< (org-element-property :begin cached-headline) (point-min))))
  18250. (org-with-limited-levels
  18251. (save-excursion
  18252. (end-of-line)
  18253. (null (re-search-backward org-outline-regexp-bol nil t)))))))
  18254. (defun org-at-heading-p (&optional invisible-not-ok)
  18255. "Return t if point is on a (possibly invisible) heading line.
  18256. If INVISIBLE-NOT-OK is non-nil, an invisible heading line is not ok."
  18257. (save-excursion
  18258. (beginning-of-line)
  18259. (and (bolp) (or (not invisible-not-ok) (not (org-fold-folded-p)))
  18260. (looking-at outline-regexp))))
  18261. (defun org-in-commented-heading-p (&optional no-inheritance element)
  18262. "Non-nil if point is under a commented heading.
  18263. This function also checks ancestors of the current headline,
  18264. unless optional argument NO-INHERITANCE is non-nil.
  18265. Optional argument ELEMENT contains element at point."
  18266. (save-match-data
  18267. (let ((el (or element
  18268. (org-element-at-point nil 'cached)
  18269. (org-with-wide-buffer
  18270. (org-back-to-heading-or-point-min t)
  18271. (org-element-at-point)))))
  18272. (catch :found
  18273. (setq el (org-element-lineage el '(headline inlinetask) 'include-self))
  18274. (if no-inheritance
  18275. (org-element-property :commentedp el)
  18276. (while el
  18277. (when (org-element-property :commentedp el)
  18278. (throw :found t))
  18279. (setq el (org-element-property :parent el))))))))
  18280. (defun org-in-archived-heading-p (&optional no-inheritance element)
  18281. "Non-nil if point is under an archived heading.
  18282. This function also checks ancestors of the current headline,
  18283. unless optional argument NO-INHERITANCE is non-nil.
  18284. Optional argument ELEMENT contains element at point."
  18285. (cond
  18286. ((and (not element) (org-before-first-heading-p)) nil)
  18287. ((if element
  18288. (org-element-property :archivedp element)
  18289. (let ((tags (org-get-tags element 'local)))
  18290. (and tags
  18291. (cl-some (apply-partially #'string= org-archive-tag) tags)))))
  18292. (no-inheritance nil)
  18293. (t
  18294. (if (org-element--cache-active-p)
  18295. (cl-some (lambda (el) (org-element-property :archivedp el))
  18296. (org-element-lineage (or element (org-element-at-point)) nil t))
  18297. (save-excursion (and (org-up-heading-safe) (org-in-archived-heading-p)))))))
  18298. (defun org-at-comment-p nil
  18299. "Return t if cursor is in a commented line."
  18300. (save-excursion
  18301. (save-match-data
  18302. (beginning-of-line)
  18303. (looking-at org-comment-regexp))))
  18304. (defun org-at-keyword-p nil
  18305. "Return t if cursor is at a keyword-line."
  18306. (save-excursion
  18307. (move-beginning-of-line 1)
  18308. (looking-at org-keyword-regexp)))
  18309. (defun org-at-drawer-p nil
  18310. "Return t if cursor is at a drawer keyword."
  18311. (save-excursion
  18312. (move-beginning-of-line 1)
  18313. (looking-at org-drawer-regexp)))
  18314. (defun org-at-block-p nil
  18315. "Return t if cursor is at a block keyword."
  18316. (save-excursion
  18317. (move-beginning-of-line 1)
  18318. (looking-at org-block-regexp)))
  18319. (defun org-point-at-end-of-empty-headline ()
  18320. "If point is at the end of an empty headline, return t, else nil.
  18321. If the heading only contains a TODO keyword, it is still considered
  18322. empty."
  18323. (let ((case-fold-search nil))
  18324. (and (looking-at "[ \t]*$")
  18325. org-todo-line-regexp
  18326. (save-excursion
  18327. (beginning-of-line)
  18328. (looking-at org-todo-line-regexp)
  18329. (string= (match-string 3) "")))))
  18330. (defun org-at-heading-or-item-p ()
  18331. (or (org-at-heading-p) (org-at-item-p)))
  18332. (defun org-up-heading-all (arg)
  18333. "Move to the heading line of which the present line is a subheading.
  18334. This function considers both visible and invisible heading lines.
  18335. With argument, move up ARG levels."
  18336. (outline-up-heading arg t))
  18337. (defvar-local org--up-heading-cache nil
  18338. "Buffer-local `org-up-heading-safe' cache.")
  18339. (defvar-local org--up-heading-cache-tick nil
  18340. "Buffer `buffer-chars-modified-tick' in `org--up-heading-cache'.")
  18341. (defun org-up-heading-safe ()
  18342. "Move to the heading line of which the present line is a subheading.
  18343. This version will not throw an error. It will return the level of the
  18344. headline found, or nil if no higher level is found.
  18345. Also, this function will be a lot faster than `outline-up-heading',
  18346. because it relies on stars being the outline starters. This can really
  18347. make a significant difference in outlines with very many siblings."
  18348. (let ((element (and (org-element--cache-active-p)
  18349. (org-element-at-point nil t))))
  18350. (if element
  18351. (let* ((current-heading (org-element-lineage element '(headline) 'with-self))
  18352. (parent (org-element-lineage current-heading '(headline))))
  18353. (if (and parent
  18354. (<= (point-min) (org-element-property :begin parent)))
  18355. (progn
  18356. (goto-char (org-element-property :begin parent))
  18357. (org-element-property :level parent))
  18358. (when (and current-heading
  18359. (<= (point-min) (org-element-property :begin current-heading)))
  18360. (goto-char (org-element-property :begin current-heading))
  18361. nil)))
  18362. (when (ignore-errors (org-back-to-heading t))
  18363. (let (level-cache)
  18364. (unless org--up-heading-cache
  18365. (setq org--up-heading-cache (make-hash-table)))
  18366. (if (and (eq (buffer-chars-modified-tick) org--up-heading-cache-tick)
  18367. (setq level-cache (gethash (point) org--up-heading-cache)))
  18368. (when (<= (point-min) (car level-cache) (point-max))
  18369. ;; Parent is inside accessible part of the buffer.
  18370. (progn (goto-char (car level-cache))
  18371. (cdr level-cache)))
  18372. ;; Buffer modified. Invalidate cache.
  18373. (unless (eq (buffer-chars-modified-tick) org--up-heading-cache-tick)
  18374. (setq-local org--up-heading-cache-tick
  18375. (buffer-chars-modified-tick))
  18376. (clrhash org--up-heading-cache))
  18377. (let* ((level-up (1- (funcall outline-level)))
  18378. (pos (point))
  18379. (result (and (> level-up 0)
  18380. (re-search-backward
  18381. (format "^\\*\\{1,%d\\} " level-up) nil t)
  18382. (funcall outline-level))))
  18383. (when result (puthash pos (cons (point) result) org--up-heading-cache))
  18384. result)))))))
  18385. (defun org-up-heading-or-point-min ()
  18386. "Move to the heading line of which the present is a subheading, or point-min.
  18387. This version is needed to make point-min behave like a virtual
  18388. heading of level 0 for property-inheritance. It will return the
  18389. level of the headline found (down to 0) or nil if already at a
  18390. point before the first headline or at point-min."
  18391. (when (ignore-errors (org-back-to-heading t))
  18392. (if (< 1 (funcall outline-level))
  18393. (or (org-up-heading-safe)
  18394. ;; The first heading may not be level 1 heading.
  18395. (goto-char (point-min)))
  18396. (unless (= (point) (point-min)) (goto-char (point-min))))))
  18397. (defun org-first-sibling-p ()
  18398. "Is this heading the first child of its parents?"
  18399. (interactive)
  18400. (let ((re org-outline-regexp-bol)
  18401. level l)
  18402. (unless (org-at-heading-p t)
  18403. (user-error "Not at a heading"))
  18404. (setq level (funcall outline-level))
  18405. (save-excursion
  18406. (if (not (re-search-backward re nil t))
  18407. t
  18408. (setq l (funcall outline-level))
  18409. (< l level)))))
  18410. (defun org-goto-sibling (&optional previous)
  18411. "Goto the next sibling, even if it is invisible.
  18412. When PREVIOUS is set, go to the previous sibling instead. Returns t
  18413. when a sibling was found. When none is found, return nil and don't
  18414. move point."
  18415. (let ((fun (if previous 're-search-backward 're-search-forward))
  18416. (pos (point))
  18417. (re org-outline-regexp-bol)
  18418. level l)
  18419. (when (ignore-errors (org-back-to-heading t))
  18420. (setq level (funcall outline-level))
  18421. (catch 'exit
  18422. (or previous (forward-char 1))
  18423. (while (funcall fun re nil t)
  18424. (setq l (funcall outline-level))
  18425. (when (< l level) (goto-char pos) (throw 'exit nil))
  18426. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  18427. (goto-char pos)
  18428. nil))))
  18429. (defun org-goto-first-child (&optional element)
  18430. "Goto the first child, even if it is invisible.
  18431. Return t when a child was found. Otherwise don't move point and
  18432. return nil."
  18433. (if (org-element--cache-active-p)
  18434. (let ((heading (org-element-lineage
  18435. (or element (org-element-at-point))
  18436. '(headline inlinetask org-data)
  18437. t)))
  18438. (when heading
  18439. (unless (or (eq 'inlinetask (org-element-type heading))
  18440. (not (org-element-property :contents-begin heading)))
  18441. (let ((pos (point)))
  18442. (goto-char (org-element-property :contents-begin heading))
  18443. (if (re-search-forward
  18444. org-outline-regexp-bol
  18445. (org-element-property :end heading)
  18446. t)
  18447. (progn (goto-char (match-beginning 0)) t)
  18448. (goto-char pos) nil)))))
  18449. (let (level (pos (point)) (re org-outline-regexp-bol))
  18450. (when (org-back-to-heading-or-point-min t)
  18451. (setq level (org-outline-level))
  18452. (forward-char 1)
  18453. (if (and (re-search-forward re nil t) (> (org-outline-level) level))
  18454. (progn (goto-char (match-beginning 0)) t)
  18455. (goto-char pos) nil)))))
  18456. (defun org-get-next-sibling ()
  18457. "Move to next heading of the same level, and return point.
  18458. If there is no such heading, return nil.
  18459. This is like outline-next-sibling, but invisible headings are ok."
  18460. (let ((level (funcall outline-level)))
  18461. (outline-next-heading)
  18462. (while (and (not (eobp)) (> (funcall outline-level) level))
  18463. (outline-next-heading))
  18464. (unless (or (eobp) (< (funcall outline-level) level))
  18465. (point))))
  18466. (defun org-get-previous-sibling ()
  18467. "Move to previous heading of the same level, and return point.
  18468. If there is no such heading, return nil."
  18469. (let ((opoint (point))
  18470. (level (funcall outline-level)))
  18471. (outline-previous-heading)
  18472. (when (and (/= (point) opoint) (outline-on-heading-p t))
  18473. (while (and (> (funcall outline-level) level)
  18474. (not (bobp)))
  18475. (outline-previous-heading))
  18476. (unless (< (funcall outline-level) level)
  18477. (point)))))
  18478. (defun org-end-of-subtree (&optional invisible-ok to-heading element)
  18479. "Goto to the end of a subtree at point or for ELEMENT heading."
  18480. ;; This contains an exact copy of the original function, but it uses
  18481. ;; `org-back-to-heading-or-point-min', to make it work also in invisible
  18482. ;; trees and before first headline. And is uses an invisible-ok argument.
  18483. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  18484. ;; Furthermore, when used inside Org, finding the end of a large subtree
  18485. ;; with many children and grandchildren etc, this can be much faster
  18486. ;; than the outline version.
  18487. (org-back-to-heading-or-point-min invisible-ok)
  18488. (unless (and (org-element--cache-active-p)
  18489. (let ((cached (or element (org-element-at-point nil t))))
  18490. (and cached
  18491. (eq 'headline (org-element-type cached))
  18492. (goto-char (org-element-property
  18493. :end cached)))))
  18494. (let ((first t)
  18495. (level (funcall outline-level)))
  18496. (cond ((= level 0)
  18497. (goto-char (point-max)))
  18498. ((and (derived-mode-p 'org-mode) (< level 1000))
  18499. ;; A true heading (not a plain list item), in Org
  18500. ;; This means we can easily find the end by looking
  18501. ;; only for the right number of stars. Using a regexp to do
  18502. ;; this is so much faster than using a Lisp loop.
  18503. (let ((re (concat "^\\*\\{1," (number-to-string level) "\\} ")))
  18504. (forward-char 1)
  18505. (and (re-search-forward re nil 'move) (beginning-of-line 1))))
  18506. (t
  18507. ;; something else, do it the slow way
  18508. (while (and (not (eobp))
  18509. (or first (> (funcall outline-level) level)))
  18510. (setq first nil)
  18511. (outline-next-heading))))))
  18512. (unless to-heading
  18513. (when (memq (preceding-char) '(?\n ?\^M))
  18514. ;; Go to end of line before heading
  18515. (forward-char -1)
  18516. (when (memq (preceding-char) '(?\n ?\^M))
  18517. ;; leave blank line before heading
  18518. (forward-char -1))))
  18519. (point))
  18520. (defun org-end-of-meta-data (&optional full)
  18521. "Skip planning line and properties drawer in current entry.
  18522. When optional argument FULL is t, also skip planning information,
  18523. clocking lines and any kind of drawer.
  18524. When FULL is non-nil but not t, skip planning information,
  18525. properties, clocking lines and logbook drawers."
  18526. (org-back-to-heading t)
  18527. (forward-line)
  18528. ;; Skip planning information.
  18529. (when (looking-at-p org-planning-line-re) (forward-line))
  18530. ;; Skip property drawer.
  18531. (when (looking-at org-property-drawer-re)
  18532. (goto-char (match-end 0))
  18533. (forward-line))
  18534. ;; When FULL is not nil, skip more.
  18535. (when (and full (not (org-at-heading-p)))
  18536. (catch 'exit
  18537. (let ((end (save-excursion (outline-next-heading) (point)))
  18538. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  18539. (while (not (eobp))
  18540. (cond ;; Skip clock lines.
  18541. ((looking-at-p re) (forward-line))
  18542. ;; Skip logbook drawer.
  18543. ((looking-at-p org-logbook-drawer-re)
  18544. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  18545. (forward-line)
  18546. (throw 'exit t)))
  18547. ;; When FULL is t, skip regular drawer too.
  18548. ((and (eq full t) (looking-at-p org-drawer-regexp))
  18549. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  18550. (forward-line)
  18551. (throw 'exit t)))
  18552. (t (throw 'exit t))))))))
  18553. (defun org--line-fully-invisible-p ()
  18554. "Return non-nil if the current line is fully invisible."
  18555. (let ((line-beg (line-beginning-position))
  18556. (line-pos (1- (line-end-position)))
  18557. (is-invisible t))
  18558. (while (and (< line-beg line-pos) is-invisible)
  18559. (setq is-invisible (org-invisible-p line-pos))
  18560. (setq line-pos (1- line-pos)))
  18561. is-invisible))
  18562. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  18563. "Move forward to the ARG'th subheading at same level as this one.
  18564. Stop at the first and last subheadings of a superior heading.
  18565. Normally this only looks at visible headings, but when INVISIBLE-OK is
  18566. non-nil it will also look at invisible ones."
  18567. (interactive "p")
  18568. (let ((backward? (and arg (< arg 0))))
  18569. (if (org-before-first-heading-p)
  18570. (if backward? (goto-char (point-min)) (outline-next-heading))
  18571. (org-back-to-heading invisible-ok)
  18572. (unless backward? (end-of-line)) ;do not match current headline
  18573. (let ((level (- (match-end 0) (match-beginning 0) 1))
  18574. (f (if backward? #'re-search-backward #'re-search-forward))
  18575. (count (if arg (abs arg) 1))
  18576. (result (point)))
  18577. (while (and (> count 0)
  18578. (funcall f org-outline-regexp-bol nil 'move))
  18579. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  18580. (cond ((< l level) (setq count 0))
  18581. ((and (= l level)
  18582. (or invisible-ok
  18583. ;; FIXME: See commit a700fadd72 and the
  18584. ;; related discussion on why using
  18585. ;; `org--line-fully-invisible-p' is needed
  18586. ;; here, which is to serve the needs of an
  18587. ;; external package. If the change is
  18588. ;; wrong regarding Org itself, it should
  18589. ;; be removed.
  18590. (not (org--line-fully-invisible-p))))
  18591. (cl-decf count)
  18592. (when (= l level) (setq result (point)))))))
  18593. (goto-char result))
  18594. (beginning-of-line))))
  18595. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  18596. "Move backward to the ARG'th subheading at same level as this one.
  18597. Stop at the first and last subheadings of a superior heading."
  18598. (interactive "p")
  18599. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  18600. (defun org-next-visible-heading--overlays (arg)
  18601. "Move to the next visible heading line.
  18602. With ARG, repeats or can move backward if negative."
  18603. (interactive "p")
  18604. (let ((regexp (concat "^" (org-get-limited-outline-regexp))))
  18605. (if (< arg 0)
  18606. (beginning-of-line)
  18607. (end-of-line))
  18608. (while (and (< arg 0) (re-search-backward regexp nil :move))
  18609. (unless (bobp)
  18610. (while (pcase (get-char-property-and-overlay (point) 'invisible)
  18611. (`(outline . ,o)
  18612. (goto-char (overlay-start o))
  18613. (re-search-backward regexp nil :move))
  18614. (_ nil))))
  18615. (cl-incf arg))
  18616. (while (and (> arg 0) (re-search-forward regexp nil t))
  18617. (while (pcase (get-char-property-and-overlay (point) 'invisible)
  18618. (`(outline . ,o)
  18619. (goto-char (overlay-end o))
  18620. (re-search-forward regexp nil :move))
  18621. (_
  18622. (end-of-line)
  18623. nil))) ;leave the loop
  18624. (cl-decf arg))
  18625. (if (> arg 0) (goto-char (point-max)) (beginning-of-line))))
  18626. (defun org-next-visible-heading--text-properties (arg)
  18627. "Move to the next visible heading line.
  18628. With ARG, repeats or can move backward if negative."
  18629. (interactive "p")
  18630. (let ((regexp (concat "^" (org-get-limited-outline-regexp))))
  18631. (if (< arg 0)
  18632. (beginning-of-line)
  18633. (end-of-line))
  18634. (while (and (< arg 0) (re-search-backward regexp nil :move))
  18635. (unless (bobp)
  18636. (when (org-fold-folded-p)
  18637. (goto-char (org-fold-previous-visibility-change))
  18638. (unless (looking-at-p regexp)
  18639. (re-search-backward regexp nil :mode))))
  18640. (cl-incf arg))
  18641. (while (and (> arg 0) (re-search-forward regexp nil :move))
  18642. (when (org-fold-folded-p)
  18643. (goto-char (org-fold-next-visibility-change))
  18644. (skip-chars-forward " \t\n")
  18645. (end-of-line))
  18646. (cl-decf arg))
  18647. (if (> arg 0) (goto-char (point-max)) (beginning-of-line))))
  18648. (defun org-next-visible-heading (arg)
  18649. "Move to the next visible heading line.
  18650. With ARG, repeats or can move backward if negative."
  18651. (interactive "p")
  18652. (if (eq org-fold-core-style 'text-properties)
  18653. (org-next-visible-heading--text-properties arg)
  18654. (org-next-visible-heading--overlays arg)))
  18655. (defun org-previous-visible-heading (arg)
  18656. "Move to the previous visible heading.
  18657. With ARG, repeats or can move forward if negative."
  18658. (interactive "p")
  18659. (org-next-visible-heading (- arg)))
  18660. (defun org-forward-paragraph (&optional arg)
  18661. "Move forward by a paragraph, or equivalent, unit.
  18662. With argument ARG, do it ARG times;
  18663. a negative argument ARG = -N means move backward N paragraphs.
  18664. The function moves point between two structural
  18665. elements (paragraphs, tables, lists, etc.).
  18666. It also provides the following special moves for convenience:
  18667. - on a table or a property drawer, move to its beginning;
  18668. - on comment, example, export, source and verse blocks, stop
  18669. at blank lines;
  18670. - skip consecutive clocks, diary S-exps, and keywords."
  18671. (interactive "^p")
  18672. (unless arg (setq arg 1))
  18673. (if (< arg 0) (org-backward-paragraph (- arg))
  18674. (while (and (> arg 0) (not (eobp)))
  18675. (org--forward-paragraph-once)
  18676. (cl-decf arg))
  18677. ;; Return moves left.
  18678. arg))
  18679. (defun org-backward-paragraph (&optional arg)
  18680. "Move backward by a paragraph, or equivalent, unit.
  18681. With argument ARG, do it ARG times;
  18682. a negative argument ARG = -N means move forward N paragraphs.
  18683. The function moves point between two structural
  18684. elements (paragraphs, tables, lists, etc.).
  18685. It also provides the following special moves for convenience:
  18686. - on a table or a property drawer, move to its beginning;
  18687. - on comment, example, export, source and verse blocks, stop
  18688. at blank lines;
  18689. - skip consecutive clocks, diary S-exps, and keywords."
  18690. (interactive "^p")
  18691. (unless arg (setq arg 1))
  18692. (if (< arg 0) (org-forward-paragraph (- arg))
  18693. (while (and (> arg 0) (not (bobp)))
  18694. (org--backward-paragraph-once)
  18695. (cl-decf arg))
  18696. ;; Return moves left.
  18697. arg))
  18698. (defvar org--single-lines-list-is-paragraph t
  18699. "Treat plain lists with single line items as a whole paragraph")
  18700. (defun org--paragraph-at-point ()
  18701. "Return paragraph, or equivalent, element at point.
  18702. Paragraph element at point is the element at point, with the
  18703. following special cases:
  18704. - treat table rows (resp. node properties) as the table
  18705. \(resp. property drawer) containing them.
  18706. - treat plain lists with an item every line as a whole.
  18707. - treat consecutive keywords, clocks, and diary-sexps as a single
  18708. block.
  18709. Function may return a real element, or a pseudo-element with type
  18710. `pseudo-paragraph'."
  18711. (let* ((e (org-element-at-point))
  18712. (type (org-element-type e))
  18713. ;; If we need to fake a new pseudo-element, triplet is
  18714. ;;
  18715. ;; (BEG END PARENT)
  18716. ;;
  18717. ;; where BEG and END are element boundaries, and PARENT the
  18718. ;; element containing it, or nil.
  18719. (triplet
  18720. (cond
  18721. ((memq type '(table property-drawer))
  18722. (list (org-element-property :begin e)
  18723. (org-element-property :end e)
  18724. (org-element-property :parent e)))
  18725. ((memq type '(node-property table-row))
  18726. (let ((e (org-element-property :parent e)))
  18727. (list (org-element-property :begin e)
  18728. (org-element-property :end e)
  18729. (org-element-property :parent e))))
  18730. ((memq type '(clock diary-sexp keyword))
  18731. (let* ((regexp (pcase type
  18732. (`clock org-clock-line-re)
  18733. (`diary-sexp "%%(")
  18734. (_ org-keyword-regexp)))
  18735. (end (if (< 0 (org-element-property :post-blank e))
  18736. (org-element-property :end e)
  18737. (org-with-wide-buffer
  18738. (forward-line)
  18739. (while (looking-at regexp) (forward-line))
  18740. (skip-chars-forward " \t\n")
  18741. (line-beginning-position))))
  18742. (begin (org-with-point-at (org-element-property :begin e)
  18743. (while (and (not (bobp)) (looking-at regexp))
  18744. (forward-line -1))
  18745. ;; We may have gotten one line too far.
  18746. (if (looking-at regexp)
  18747. (point)
  18748. (line-beginning-position 2)))))
  18749. (list begin end (org-element-property :parent e))))
  18750. ;; Find the full plain list containing point, the check it
  18751. ;; contains exactly one line per item.
  18752. ((let ((l (org-element-lineage e '(plain-list) t)))
  18753. (while (memq (org-element-type (org-element-property :parent l))
  18754. '(item plain-list))
  18755. (setq l (org-element-property :parent l)))
  18756. (and l org--single-lines-list-is-paragraph
  18757. (org-with-point-at (org-element-property :post-affiliated l)
  18758. (forward-line (length (org-element-property :structure l)))
  18759. (= (point) (org-element-property :contents-end l)))
  18760. ;; Return value.
  18761. (list (org-element-property :begin l)
  18762. (org-element-property :end l)
  18763. (org-element-property :parent l)))))
  18764. (t nil)))) ;no triplet: return element
  18765. (pcase triplet
  18766. (`(,b ,e ,p)
  18767. (org-element-create
  18768. 'pseudo-paragraph
  18769. (list :begin b :end e :parent p :post-blank 0 :post-affiliated b)))
  18770. (_ e))))
  18771. (defun org--forward-paragraph-once--overlays ()
  18772. "Move forward to end of paragraph or equivalent, once.
  18773. See `org-forward-paragraph'."
  18774. (interactive)
  18775. (save-restriction
  18776. (widen)
  18777. (skip-chars-forward " \t\n")
  18778. (cond
  18779. ((eobp) nil)
  18780. ;; When inside a folded part, move out of it.
  18781. ((pcase (get-char-property-and-overlay (point) 'invisible)
  18782. (`(,(or `outline `org-hide-block) . ,o)
  18783. (goto-char (overlay-end o))
  18784. (forward-line)
  18785. t)
  18786. (_ nil)))
  18787. (t
  18788. (let* ((element (org--paragraph-at-point))
  18789. (type (org-element-type element))
  18790. (contents-begin (org-element-property :contents-begin element))
  18791. (end (org-element-property :end element))
  18792. (post-affiliated (org-element-property :post-affiliated element)))
  18793. (cond
  18794. ((eq type 'plain-list)
  18795. (forward-char)
  18796. (org--forward-paragraph-once))
  18797. ;; If the element is folded, skip it altogether.
  18798. ((pcase (org-with-point-at post-affiliated
  18799. (get-char-property-and-overlay (line-end-position)
  18800. 'invisible))
  18801. (`(,(or `outline `org-hide-block) . ,o)
  18802. (goto-char (overlay-end o))
  18803. (forward-line)
  18804. t)
  18805. (_ nil)))
  18806. ;; At a greater element, move inside.
  18807. ((and contents-begin
  18808. (> contents-begin (point))
  18809. (not (eq type 'paragraph)))
  18810. (goto-char contents-begin)
  18811. ;; Items and footnote definitions contents may not start at
  18812. ;; the beginning of the line. In this case, skip until the
  18813. ;; next paragraph.
  18814. (cond
  18815. ((not (bolp)) (org--forward-paragraph-once))
  18816. ((org-previous-line-empty-p) (forward-line -1))
  18817. (t nil)))
  18818. ;; Move between empty lines in some blocks.
  18819. ((memq type '(comment-block example-block export-block src-block
  18820. verse-block))
  18821. (let ((contents-start
  18822. (org-with-point-at post-affiliated
  18823. (line-beginning-position 2))))
  18824. (if (< (point) contents-start)
  18825. (goto-char contents-start)
  18826. (let ((contents-end
  18827. (org-with-point-at end
  18828. (skip-chars-backward " \t\n")
  18829. (line-beginning-position))))
  18830. (cond
  18831. ((>= (point) contents-end)
  18832. (goto-char end)
  18833. (skip-chars-backward " \t\n")
  18834. (forward-line))
  18835. ((re-search-forward "^[ \t]*\n" contents-end :move)
  18836. (forward-line -1))
  18837. (t nil))))))
  18838. (t
  18839. ;; Move to element's end.
  18840. (goto-char end)
  18841. (skip-chars-backward " \t\n")
  18842. (forward-line))))))))
  18843. (defun org--forward-paragraph-once--text-properties ()
  18844. "Move forward to end of paragraph or equivalent, once.
  18845. See `org-forward-paragraph'."
  18846. (interactive)
  18847. (save-restriction
  18848. (widen)
  18849. (skip-chars-forward " \t\n")
  18850. (cond
  18851. ((eobp) nil)
  18852. ;; When inside a folded part, move out of it.
  18853. ((when (org-invisible-p nil t)
  18854. (goto-char (cdr (org-fold-get-region-at-point)))
  18855. (forward-line)
  18856. t))
  18857. (t
  18858. (let* ((element (org--paragraph-at-point))
  18859. (type (org-element-type element))
  18860. (contents-begin (org-element-property :contents-begin element))
  18861. (end (org-element-property :end element))
  18862. (post-affiliated (org-element-property :post-affiliated element)))
  18863. (cond
  18864. ((eq type 'plain-list)
  18865. (forward-char)
  18866. (org--forward-paragraph-once))
  18867. ;; If the element is folded, skip it altogether.
  18868. ((when (org-with-point-at post-affiliated (org-invisible-p (line-end-position) t))
  18869. (goto-char (cdr (org-fold-get-region-at-point
  18870. nil
  18871. (org-with-point-at post-affiliated
  18872. (line-end-position)))))
  18873. (forward-line)
  18874. t))
  18875. ;; At a greater element, move inside.
  18876. ((and contents-begin
  18877. (> contents-begin (point))
  18878. (not (eq type 'paragraph)))
  18879. (goto-char contents-begin)
  18880. ;; Items and footnote definitions contents may not start at
  18881. ;; the beginning of the line. In this case, skip until the
  18882. ;; next paragraph.
  18883. (cond
  18884. ((not (bolp)) (org--forward-paragraph-once))
  18885. ((org-previous-line-empty-p) (forward-line -1))
  18886. (t nil)))
  18887. ;; Move between empty lines in some blocks.
  18888. ((memq type '(comment-block example-block export-block src-block
  18889. verse-block))
  18890. (let ((contents-start
  18891. (org-with-point-at post-affiliated
  18892. (line-beginning-position 2))))
  18893. (if (< (point) contents-start)
  18894. (goto-char contents-start)
  18895. (let ((contents-end
  18896. (org-with-point-at end
  18897. (skip-chars-backward " \t\n")
  18898. (line-beginning-position))))
  18899. (cond
  18900. ((>= (point) contents-end)
  18901. (goto-char end)
  18902. (skip-chars-backward " \t\n")
  18903. (forward-line))
  18904. ((re-search-forward "^[ \t]*\n" contents-end :move)
  18905. (forward-line -1))
  18906. (t nil))))))
  18907. (t
  18908. ;; Move to element's end.
  18909. (goto-char end)
  18910. (skip-chars-backward " \t\n")
  18911. (forward-line))))))))
  18912. (defun org--forward-paragraph-once ()
  18913. "Move forward to end of paragraph or equivalent, once.
  18914. See `org-forward-paragraph'."
  18915. (interactive)
  18916. (if (eq org-fold-core-style 'text-properties)
  18917. (org--forward-paragraph-once--text-properties)
  18918. (org--forward-paragraph-once--overlays)))
  18919. (defun org--backward-paragraph-once--overlays ()
  18920. "Move backward to start of paragraph or equivalent, once.
  18921. See `org-backward-paragraph'."
  18922. (interactive)
  18923. (save-restriction
  18924. (widen)
  18925. (cond
  18926. ((bobp) nil)
  18927. ;; Blank lines at the beginning of the buffer.
  18928. ((and (org-match-line "^[ \t]*$")
  18929. (save-excursion (skip-chars-backward " \t\n") (bobp)))
  18930. (goto-char (point-min)))
  18931. ;; When inside a folded part, move out of it.
  18932. ((pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  18933. (`(,(or `outline `org-hide-block) . ,o)
  18934. (goto-char (1- (overlay-start o)))
  18935. (org--backward-paragraph-once)
  18936. t)
  18937. (_ nil)))
  18938. (t
  18939. (let* ((element (org--paragraph-at-point))
  18940. (type (org-element-type element))
  18941. (begin (org-element-property :begin element))
  18942. (post-affiliated (org-element-property :post-affiliated element))
  18943. (contents-end (org-element-property :contents-end element))
  18944. (end (org-element-property :end element))
  18945. (parent (org-element-property :parent element))
  18946. (reach
  18947. ;; Move to the visible empty line above position P, or
  18948. ;; to position P. Return t.
  18949. (lambda (p)
  18950. (goto-char p)
  18951. (when (and (org-previous-line-empty-p)
  18952. (let ((end (line-end-position 0)))
  18953. (or (= end (point-min))
  18954. (not (org-invisible-p (1- end))))))
  18955. (forward-line -1))
  18956. t)))
  18957. (cond
  18958. ;; Already at the beginning of an element.
  18959. ((= begin (point))
  18960. (cond
  18961. ;; There is a blank line above. Move there.
  18962. ((and (org-previous-line-empty-p)
  18963. (let ((lep (line-end-position 0)))
  18964. ;; When the first headline start at point 2, don't choke while
  18965. ;; checking with `org-invisible-p'.
  18966. (or (= lep 1)
  18967. (not (org-invisible-p (1- (line-end-position 0)))))))
  18968. (forward-line -1))
  18969. ;; At the beginning of the first element within a greater
  18970. ;; element. Move to the beginning of the greater element.
  18971. ((and parent
  18972. (not (eq 'section (org-element-type parent)))
  18973. (= begin (org-element-property :contents-begin parent)))
  18974. (funcall reach (org-element-property :begin parent)))
  18975. ;; Since we have to move anyway, find the beginning
  18976. ;; position of the element above.
  18977. (t
  18978. (forward-char -1)
  18979. (org--backward-paragraph-once))))
  18980. ;; Skip paragraphs at the very beginning of footnote
  18981. ;; definitions or items.
  18982. ((and (eq type 'paragraph)
  18983. (org-with-point-at begin (not (bolp))))
  18984. (funcall reach (progn (goto-char begin) (line-beginning-position))))
  18985. ;; If the element is folded, skip it altogether.
  18986. ((org-with-point-at post-affiliated
  18987. (org-invisible-p (line-end-position) t))
  18988. (funcall reach begin))
  18989. ;; At the end of a greater element, move inside.
  18990. ((and contents-end
  18991. (<= contents-end (point))
  18992. (not (eq type 'paragraph)))
  18993. (cond
  18994. ((memq type '(footnote-definition plain-list))
  18995. (skip-chars-backward " \t\n")
  18996. (org--backward-paragraph-once))
  18997. ((= contents-end (point))
  18998. (forward-char -1)
  18999. (org--backward-paragraph-once))
  19000. (t
  19001. (goto-char contents-end))))
  19002. ;; Move between empty lines in some blocks.
  19003. ((and (memq type '(comment-block example-block export-block src-block
  19004. verse-block))
  19005. (let ((contents-start
  19006. (org-with-point-at post-affiliated
  19007. (line-beginning-position 2))))
  19008. (when (> (point) contents-start)
  19009. (let ((contents-end
  19010. (org-with-point-at end
  19011. (skip-chars-backward " \t\n")
  19012. (line-beginning-position))))
  19013. (if (> (point) contents-end)
  19014. (progn (goto-char contents-end) t)
  19015. (skip-chars-backward " \t\n" begin)
  19016. (re-search-backward "^[ \t]*\n" contents-start :move)
  19017. t))))))
  19018. ;; Move to element's start.
  19019. (t
  19020. (funcall reach begin))))))))
  19021. (defun org--backward-paragraph-once--text-properties ()
  19022. "Move backward to start of paragraph or equivalent, once.
  19023. See `org-backward-paragraph'."
  19024. (interactive)
  19025. (save-restriction
  19026. (widen)
  19027. (cond
  19028. ((bobp) nil)
  19029. ;; Blank lines at the beginning of the buffer.
  19030. ((and (org-match-line "^[ \t]*$")
  19031. (save-excursion (skip-chars-backward " \t\n") (bobp)))
  19032. (goto-char (point-min)))
  19033. ;; When inside a folded part, move out of it.
  19034. ((when (org-invisible-p (1- (point)) t)
  19035. (goto-char (1- (car (org-fold-get-region-at-point nil (1- (point))))))
  19036. (org--backward-paragraph-once)
  19037. t))
  19038. (t
  19039. (let* ((element (org--paragraph-at-point))
  19040. (type (org-element-type element))
  19041. (begin (org-element-property :begin element))
  19042. (post-affiliated (org-element-property :post-affiliated element))
  19043. (contents-end (org-element-property :contents-end element))
  19044. (end (org-element-property :end element))
  19045. (parent (org-element-property :parent element))
  19046. (reach
  19047. ;; Move to the visible empty line above position P, or
  19048. ;; to position P. Return t.
  19049. (lambda (p)
  19050. (goto-char p)
  19051. (when (and (org-previous-line-empty-p)
  19052. (let ((end (line-end-position 0)))
  19053. (or (= end (point-min))
  19054. (not (org-invisible-p (1- end))))))
  19055. (forward-line -1))
  19056. t)))
  19057. (cond
  19058. ;; Already at the beginning of an element.
  19059. ((= begin (point))
  19060. (cond
  19061. ;; There is a blank line above. Move there.
  19062. ((and (org-previous-line-empty-p)
  19063. (not (org-invisible-p (1- (line-end-position 0)))))
  19064. (forward-line -1))
  19065. ;; At the beginning of the first element within a greater
  19066. ;; element. Move to the beginning of the greater element.
  19067. ((and parent
  19068. (not (eq 'section (org-element-type parent)))
  19069. (= begin (org-element-property :contents-begin parent)))
  19070. (funcall reach (org-element-property :begin parent)))
  19071. ;; Since we have to move anyway, find the beginning
  19072. ;; position of the element above.
  19073. (t
  19074. (forward-char -1)
  19075. (org--backward-paragraph-once))))
  19076. ;; Skip paragraphs at the very beginning of footnote
  19077. ;; definitions or items.
  19078. ((and (eq type 'paragraph)
  19079. (org-with-point-at begin (not (bolp))))
  19080. (funcall reach (progn (goto-char begin) (line-beginning-position))))
  19081. ;; If the element is folded, skip it altogether.
  19082. ((org-with-point-at post-affiliated (org-invisible-p (line-end-position) t))
  19083. (funcall reach begin))
  19084. ;; At the end of a greater element, move inside.
  19085. ((and contents-end
  19086. (<= contents-end (point))
  19087. (not (eq type 'paragraph)))
  19088. (cond
  19089. ((memq type '(footnote-definition plain-list))
  19090. (skip-chars-backward " \t\n")
  19091. (org--backward-paragraph-once))
  19092. ((= contents-end (point))
  19093. (forward-char -1)
  19094. (org--backward-paragraph-once))
  19095. (t
  19096. (goto-char contents-end))))
  19097. ;; Move between empty lines in some blocks.
  19098. ((and (memq type '(comment-block example-block export-block src-block
  19099. verse-block))
  19100. (let ((contents-start
  19101. (org-with-point-at post-affiliated
  19102. (line-beginning-position 2))))
  19103. (when (> (point) contents-start)
  19104. (let ((contents-end
  19105. (org-with-point-at end
  19106. (skip-chars-backward " \t\n")
  19107. (line-beginning-position))))
  19108. (if (> (point) contents-end)
  19109. (progn (goto-char contents-end) t)
  19110. (skip-chars-backward " \t\n" begin)
  19111. (re-search-backward "^[ \t]*\n" contents-start :move)
  19112. t))))))
  19113. ;; Move to element's start.
  19114. (t
  19115. (funcall reach begin))))))))
  19116. (defun org--backward-paragraph-once ()
  19117. "Move backward to start of paragraph or equivalent, once.
  19118. See `org-backward-paragraph'."
  19119. (interactive)
  19120. (if (eq org-fold-core-style 'text-properties)
  19121. (org--backward-paragraph-once--text-properties)
  19122. (org--backward-paragraph-once--overlays)))
  19123. (defun org-forward-element ()
  19124. "Move forward by one element.
  19125. Move to the next element at the same level, when possible."
  19126. (interactive)
  19127. (cond ((eobp) (user-error "Cannot move further down"))
  19128. ((org-with-limited-levels (org-at-heading-p))
  19129. (let ((origin (point)))
  19130. (goto-char (org-end-of-subtree nil t))
  19131. (unless (org-with-limited-levels (org-at-heading-p))
  19132. (goto-char origin)
  19133. (user-error "Cannot move further down"))))
  19134. (t
  19135. (let* ((elem (org-element-at-point))
  19136. (end (org-element-property :end elem))
  19137. (parent (org-element-property :parent elem)))
  19138. (cond ((and parent (= (org-element-property :contents-end parent) end))
  19139. (goto-char (org-element-property :end parent)))
  19140. ((integer-or-marker-p end) (goto-char end))
  19141. (t (message "No element at point")))))))
  19142. (defun org-backward-element ()
  19143. "Move backward by one element.
  19144. Move to the previous element at the same level, when possible."
  19145. (interactive)
  19146. (cond ((bobp) (user-error "Cannot move further up"))
  19147. ((org-with-limited-levels (org-at-heading-p))
  19148. ;; At a headline, move to the previous one, if any, or stay
  19149. ;; here.
  19150. (let ((origin (point)))
  19151. (org-with-limited-levels (org-backward-heading-same-level 1))
  19152. ;; When current headline has no sibling above, move to its
  19153. ;; parent.
  19154. (when (= (point) origin)
  19155. (or (org-with-limited-levels (org-up-heading-safe))
  19156. (progn (goto-char origin)
  19157. (user-error "Cannot move further up"))))))
  19158. (t
  19159. (let* ((elem (org-element-at-point))
  19160. (beg (org-element-property :begin elem)))
  19161. (cond
  19162. ;; Move to beginning of current element if point isn't
  19163. ;; there already.
  19164. ((null beg) (message "No element at point"))
  19165. ((/= (point) beg) (goto-char beg))
  19166. (t (goto-char beg)
  19167. (skip-chars-backward " \r\t\n")
  19168. (unless (bobp)
  19169. (let ((prev (org-element-at-point)))
  19170. (goto-char (org-element-property :begin prev))
  19171. (while (and (setq prev (org-element-property :parent prev))
  19172. (<= (org-element-property :end prev) beg))
  19173. (goto-char (org-element-property :begin prev)))))))))))
  19174. (defun org-up-element ()
  19175. "Move to upper element."
  19176. (interactive)
  19177. (if (org-with-limited-levels (org-at-heading-p))
  19178. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  19179. (let* ((elem (org-element-at-point))
  19180. (parent (org-element-property :parent elem)))
  19181. (if (and parent
  19182. (not (memq (org-element-type parent) '(section org-data))))
  19183. (goto-char (org-element-property :begin parent))
  19184. (if (org-with-limited-levels (org-before-first-heading-p))
  19185. (user-error "No surrounding element")
  19186. (org-with-limited-levels (org-back-to-heading)))))))
  19187. (defun org-down-element ()
  19188. "Move to inner element."
  19189. (interactive)
  19190. (let ((element (org-element-at-point)))
  19191. (cond
  19192. ((memq (org-element-type element) '(plain-list table))
  19193. (goto-char (org-element-property :contents-begin element))
  19194. (forward-char))
  19195. ((memq (org-element-type element) org-element-greater-elements)
  19196. ;; If contents are hidden, first disclose them.
  19197. (when (org-invisible-p (line-end-position)) (org-cycle))
  19198. (goto-char (or (org-element-property :contents-begin element)
  19199. (user-error "No content for this element"))))
  19200. (t (user-error "No inner element")))))
  19201. (defun org-drag-element-backward ()
  19202. "Move backward element at point."
  19203. (interactive)
  19204. (let ((elem (or (org-element-at-point)
  19205. (user-error "No element at point"))))
  19206. (if (eq (org-element-type elem) 'headline)
  19207. ;; Preserve point when moving a whole tree, even if point was
  19208. ;; on blank lines below the headline.
  19209. (let ((offset (skip-chars-backward " \t\n")))
  19210. (unwind-protect (org-move-subtree-up)
  19211. (forward-char (- offset))))
  19212. (let ((prev-elem
  19213. (save-excursion
  19214. (goto-char (org-element-property :begin elem))
  19215. (skip-chars-backward " \r\t\n")
  19216. (unless (bobp)
  19217. (let* ((beg (org-element-property :begin elem))
  19218. (prev (org-element-at-point))
  19219. (up prev))
  19220. (while (and (setq up (org-element-property :parent up))
  19221. (<= (org-element-property :end up) beg))
  19222. (setq prev up))
  19223. prev)))))
  19224. ;; Error out if no previous element or previous element is
  19225. ;; a parent of the current one.
  19226. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  19227. (user-error "Cannot drag element backward")
  19228. (let ((pos (point)))
  19229. (org-element-swap-A-B prev-elem elem)
  19230. (goto-char (+ (org-element-property :begin prev-elem)
  19231. (- pos (org-element-property :begin elem))))))))))
  19232. (defun org-drag-element-forward ()
  19233. "Move forward element at point."
  19234. (interactive)
  19235. (let* ((pos (point))
  19236. (elem (or (org-element-at-point)
  19237. (user-error "No element at point"))))
  19238. (when (= (point-max) (org-element-property :end elem))
  19239. (user-error "Cannot drag element forward"))
  19240. (goto-char (org-element-property :end elem))
  19241. (let ((next-elem (org-element-at-point)))
  19242. (when (or (org-element-nested-p elem next-elem)
  19243. (and (eq (org-element-type next-elem) 'headline)
  19244. (not (eq (org-element-type elem) 'headline))))
  19245. (goto-char pos)
  19246. (user-error "Cannot drag element forward"))
  19247. ;; Compute new position of point: it's shifted by NEXT-ELEM
  19248. ;; body's length (without final blanks) and by the length of
  19249. ;; blanks between ELEM and NEXT-ELEM.
  19250. (let ((size-next (- (save-excursion
  19251. (goto-char (org-element-property :end next-elem))
  19252. (skip-chars-backward " \r\t\n")
  19253. (forward-line)
  19254. ;; Small correction if buffer doesn't end
  19255. ;; with a newline character.
  19256. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  19257. (org-element-property :begin next-elem)))
  19258. (size-blank (- (org-element-property :end elem)
  19259. (save-excursion
  19260. (goto-char (org-element-property :end elem))
  19261. (skip-chars-backward " \r\t\n")
  19262. (forward-line)
  19263. (point)))))
  19264. (org-element-swap-A-B elem next-elem)
  19265. (goto-char (+ pos size-next size-blank))))))
  19266. (defun org-drag-line-forward (arg)
  19267. "Drag the line at point ARG lines forward."
  19268. (interactive "p")
  19269. (dotimes (_ (abs arg))
  19270. (let ((c (current-column)))
  19271. (if (< 0 arg)
  19272. (progn
  19273. (beginning-of-line 2)
  19274. (transpose-lines 1)
  19275. (beginning-of-line 0))
  19276. (transpose-lines 1)
  19277. (beginning-of-line -1))
  19278. (org-move-to-column c))))
  19279. (defun org-drag-line-backward (arg)
  19280. "Drag the line at point ARG lines backward."
  19281. (interactive "p")
  19282. (org-drag-line-forward (- arg)))
  19283. (defun org-mark-element ()
  19284. "Put point at beginning of this element, mark at end.
  19285. Interactively, if this command is repeated or (in Transient Mark
  19286. mode) if the mark is active, it marks the next element after the
  19287. ones already marked."
  19288. (interactive)
  19289. (let (deactivate-mark)
  19290. (if (and (called-interactively-p 'any)
  19291. (or (and (eq last-command this-command) (mark t))
  19292. (and transient-mark-mode mark-active)))
  19293. (set-mark
  19294. (save-excursion
  19295. (goto-char (mark))
  19296. (goto-char (org-element-property :end (org-element-at-point)))
  19297. (point)))
  19298. (let ((element (org-element-at-point)))
  19299. (end-of-line)
  19300. (push-mark (min (point-max) (org-element-property :end element)) t t)
  19301. (goto-char (org-element-property :begin element))))))
  19302. (defun org-narrow-to-element ()
  19303. "Narrow buffer to current element."
  19304. (interactive)
  19305. (let ((elem (org-element-at-point)))
  19306. (cond
  19307. ((eq (car elem) 'headline)
  19308. (narrow-to-region
  19309. (org-element-property :begin elem)
  19310. (org-element-property :end elem)))
  19311. ((memq (car elem) org-element-greater-elements)
  19312. (narrow-to-region
  19313. (org-element-property :contents-begin elem)
  19314. (org-element-property :contents-end elem)))
  19315. (t
  19316. (narrow-to-region
  19317. (org-element-property :begin elem)
  19318. (org-element-property :end elem))))))
  19319. (defun org-transpose-element ()
  19320. "Transpose current and previous elements, keeping blank lines between.
  19321. Point is moved after both elements."
  19322. (interactive)
  19323. (org-skip-whitespace)
  19324. (let ((end (org-element-property :end (org-element-at-point))))
  19325. (org-drag-element-backward)
  19326. (goto-char end)))
  19327. (defun org-unindent-buffer ()
  19328. "Un-indent the visible part of the buffer.
  19329. Relative indentation (between items, inside blocks, etc.) isn't
  19330. modified."
  19331. (interactive)
  19332. (unless (eq major-mode 'org-mode)
  19333. (user-error "Cannot un-indent a buffer not in Org mode"))
  19334. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  19335. (unindent-tree
  19336. (lambda (contents)
  19337. (dolist (element (reverse contents))
  19338. (if (memq (org-element-type element) '(headline section))
  19339. (funcall unindent-tree (org-element-contents element))
  19340. (save-excursion
  19341. (save-restriction
  19342. (narrow-to-region
  19343. (org-element-property :begin element)
  19344. (org-element-property :end element))
  19345. (org-do-remove-indentation))))))))
  19346. (funcall unindent-tree (org-element-contents parse-tree))))
  19347. (defun org-make-options-regexp (kwds &optional extra)
  19348. "Make a regular expression for keyword lines.
  19349. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  19350. when non-nil, is a regexp matching keywords names."
  19351. (concat "^[ \t]*#\\+\\("
  19352. (regexp-opt kwds)
  19353. (and extra (concat (and kwds "\\|") extra))
  19354. "\\):[ \t]*\\(.*\\)"))
  19355. ;;; Conveniently switch to Info nodes
  19356. (defun org-info-find-node (&optional nodename)
  19357. "Find Info documentation NODENAME or Org documentation according context.
  19358. Started from `gnus-info-find-node'."
  19359. (interactive)
  19360. (Info-goto-node
  19361. (or nodename
  19362. (let ((default-org-info-node "(org) Top"))
  19363. (cond
  19364. ((eq 'org-agenda-mode major-mode) "(org) Agenda Views")
  19365. ((eq 'org-mode major-mode)
  19366. (let* ((context (org-element-at-point))
  19367. (element-info-nodes ; compare to `org-element-all-elements'.
  19368. `((babel-call . "(org) Evaluating Code Blocks")
  19369. (center-block . "(org) Paragraphs")
  19370. (clock . ,default-org-info-node)
  19371. (comment . "(org) Comment Lines")
  19372. (comment-block . "(org) Comment Lines")
  19373. (diary-sexp . ,default-org-info-node)
  19374. (drawer . "(org) Drawers")
  19375. (dynamic-block . "(org) Dynamic Blocks")
  19376. (example-block . "(org) Literal Examples")
  19377. (export-block . "(org) ASCII/Latin-1/UTF-8 export")
  19378. (fixed-width . ,default-org-info-node)
  19379. (footnote-definition . "(org) Creating Footnotes")
  19380. (headline . "(org) Document Structure")
  19381. (horizontal-rule . "(org) Built-in Table Editor")
  19382. (inlinetask . ,default-org-info-node)
  19383. (item . "(org) Plain Lists")
  19384. (keyword . "(org) Per-file keywords")
  19385. (latex-environment . "(org) LaTeX Export")
  19386. (node-property . "(org) Properties and Columns")
  19387. (paragraph . "(org) Paragraphs")
  19388. (plain-list . "(org) Plain Lists")
  19389. (planning . "(org) Deadlines and Scheduling")
  19390. (property-drawer . "(org) Properties and Columns")
  19391. (quote-block . "(org) Paragraphs")
  19392. (section . ,default-org-info-node)
  19393. (special-block . ,default-org-info-node)
  19394. (src-block . "(org) Working with Source Code")
  19395. (table . "(org) Tables")
  19396. (table-row . "(org) Tables")
  19397. (verse-block . "(org) Paragraphs"))))
  19398. (or (cdr (assoc (car context) element-info-nodes))
  19399. default-org-info-node)))
  19400. (t default-org-info-node))))))
  19401. ;;; Finish up
  19402. (add-hook 'org-mode-hook ;remove folds when changing major mode
  19403. (lambda () (add-hook 'change-major-mode-hook
  19404. 'org-fold-show-all 'append 'local)))
  19405. (provide 'org)
  19406. (run-hooks 'org-load-hook)
  19407. ;;; org.el ends here