org.el 819 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201
  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-pre
  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 'org-compat)
  67. (org-assert-version)
  68. (require 'cl-lib)
  69. (eval-when-compile (require 'gnus-sum))
  70. (require 'calendar)
  71. (require 'find-func)
  72. (require 'format-spec)
  73. (condition-case nil
  74. (load (concat (file-name-directory load-file-name)
  75. "org-loaddefs")
  76. nil t nil t)
  77. (error
  78. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  79. (sit-for 3)
  80. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  81. (sit-for 3)))
  82. (eval-and-compile (require 'org-macs))
  83. (require 'org-compat)
  84. (require 'org-keys)
  85. (require 'ol)
  86. (require 'oc)
  87. (require 'org-table)
  88. (require 'org-fold)
  89. (require 'org-cycle)
  90. (defvaralias 'org-hide-block-startup 'org-cycle-hide-block-startup)
  91. (defvaralias 'org-pre-cycle-hook 'org-cycle-pre-hook)
  92. (defvaralias 'org-tab-first-hook 'org-cycle-tab-first-hook)
  93. (defalias 'org-global-cycle #'org-cycle-global)
  94. (defalias 'org-overview #'org-cycle-overview)
  95. (defalias 'org-content #'org-cycle-content)
  96. (defalias 'org-reveal #'org-fold-reveal)
  97. (defalias 'org-force-cycle-archived #'org-cycle-force-archived)
  98. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  99. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  100. (defvar org-outline-regexp "\\*+ "
  101. "Regexp to match Org headlines.")
  102. (defvar org-outline-regexp-bol "^\\*+ "
  103. "Regexp to match Org headlines.
  104. This is similar to `org-outline-regexp' but additionally makes
  105. sure that we are at the beginning of the line.")
  106. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  107. "Matches a headline, putting stars and text into groups.
  108. Stars are put in group 1 and the trimmed body in group 2.")
  109. (declare-function calendar-check-holidays "holidays" (date))
  110. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  111. (declare-function cdlatex-math-symbol "ext:cdlatex")
  112. (declare-function Info-goto-node "info" (nodename &optional fork strict-case))
  113. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  114. (declare-function org-add-archive-files "org-archive" (files))
  115. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  116. (declare-function org-agenda-todo-yesterday "org-agenda" (&optional arg))
  117. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
  118. (declare-function org-agenda-redo "org-agenda" (&optional all))
  119. (declare-function org-agenda-remove-restriction-lock "org-agenda" (&optional noupdate))
  120. (declare-function org-archive-subtree "org-archive" (&optional find-done))
  121. (declare-function org-archive-subtree-default "org-archive" ())
  122. (declare-function org-archive-to-archive-sibling "org-archive" ())
  123. (declare-function org-attach "org-attach" ())
  124. (declare-function org-attach-dir "org-attach"
  125. (&optional create-if-not-exists-p no-fs-check))
  126. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  127. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  128. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  129. (declare-function org-clock-auto-clockout "org-clock" ())
  130. (declare-function org-clock-cancel "org-clock" ())
  131. (declare-function org-clock-display "org-clock" (&optional arg))
  132. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  133. (declare-function org-clock-goto "org-clock" (&optional select))
  134. (declare-function org-clock-in "org-clock" (&optional select start-time))
  135. (declare-function org-clock-in-last "org-clock" (&optional arg))
  136. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  137. (declare-function org-clock-out-if-current "org-clock" ())
  138. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  139. (declare-function org-clock-report "org-clock" (&optional arg))
  140. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  141. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  142. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  143. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  144. (declare-function org-clock-update-time-maybe "org-clock" ())
  145. (declare-function org-clocktable-shift "org-clock" (dir n))
  146. (declare-function org-columns-quit "org-colview" ())
  147. (declare-function org-columns-insert-dblock "org-colview" ())
  148. (declare-function org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  149. (declare-function org-duration-to-minutes "org-duration" (duration &optional canonical))
  150. (declare-function org-element-at-point "org-element" (&optional pom cached-only))
  151. (declare-function org-element-at-point-no-context "org-element" (&optional pom))
  152. (declare-function org-element-cache-refresh "org-element" (pos))
  153. (declare-function org-element-cache-reset "org-element" (&optional all no-persistence))
  154. (declare-function org-element-cache-map "org-element" (func &rest keys))
  155. (declare-function org-element-contents "org-element" (element))
  156. (declare-function org-element-context "org-element" (&optional element))
  157. (declare-function org-element-copy "org-element" (datum))
  158. (declare-function org-element-create "org-element" (type &optional props &rest children))
  159. (declare-function org-element-extract-element "org-element" (element))
  160. (declare-function org-element-insert-before "org-element" (element location))
  161. (declare-function org-element-interpret-data "org-element" (data))
  162. (declare-function org-element-keyword-parser "org-element" (limit affiliated))
  163. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  164. (declare-function org-element-link-parser "org-element" ())
  165. (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion with-affiliated))
  166. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  167. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  168. (declare-function org-element-parse-secondary-string "org-element" (string restriction &optional parent))
  169. (declare-function org-element-property "org-element" (property element))
  170. (declare-function org-element-put-property "org-element" (element property value))
  171. (declare-function org-element-restriction "org-element" (element))
  172. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  173. (declare-function org-element-timestamp-parser "org-element" ())
  174. (declare-function org-element-type "org-element" (element))
  175. (declare-function org-element--cache-active-p "org-element" ())
  176. (declare-function org-export-dispatch "ox" (&optional arg))
  177. (declare-function org-export-get-backend "ox" (name))
  178. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  179. (declare-function org-feed-goto-inbox "org-feed" (feed))
  180. (declare-function org-feed-update-all "org-feed" ())
  181. (declare-function org-goto "org-goto" (&optional alternative-interface))
  182. (declare-function org-id-find-id-file "org-id" (id))
  183. (declare-function org-id-get-create "org-id" (&optional force))
  184. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  185. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  186. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  187. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  188. (declare-function org-num-mode "org-num" (&optional arg))
  189. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  190. (declare-function org-persist-load "org-persist" (container &optional associated hash-must-match))
  191. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  192. (declare-function org-timer "org-timer" (&optional restart no-insert))
  193. (declare-function org-timer-item "org-timer" (&optional arg))
  194. (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
  195. (declare-function org-timer-set-timer "org-timer" (&optional opt))
  196. (declare-function org-timer-start "org-timer" (&optional offset))
  197. (declare-function org-timer-stop "org-timer" ())
  198. (declare-function org-toggle-archive-tag "org-archive" (&optional find-done))
  199. (declare-function org-update-radio-target-regexp "ol" ())
  200. (defvar org-agenda-buffer-name)
  201. (defvar org-element-paragraph-separate)
  202. (defvar org-element-cache-map-continue-from)
  203. (defvar org-element--timestamp-regexp)
  204. (defvar org-indent-indentation-per-level)
  205. (defvar org-radio-target-regexp)
  206. (defvar org-target-link-regexp)
  207. (defvar org-target-regexp)
  208. (defvar org-id-overriding-file-name)
  209. ;; load languages based on value of `org-babel-load-languages'
  210. (defvar org-babel-load-languages)
  211. (defvar crm-separator) ; dynamically scoped param
  212. ;;;###autoload
  213. (defun org-babel-do-load-languages (sym value)
  214. "Load the languages defined in `org-babel-load-languages'."
  215. (set-default-toplevel-value sym value)
  216. (dolist (pair org-babel-load-languages)
  217. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  218. (if active
  219. (require (intern (concat "ob-" lang)))
  220. (fmakunbound
  221. (intern (concat "org-babel-execute:" lang)))
  222. (fmakunbound
  223. (intern (concat "org-babel-expand-body:" lang)))))))
  224. ;;;###autoload
  225. (defun org-babel-load-file (file &optional compile)
  226. "Load Emacs Lisp source code blocks in the Org FILE.
  227. This function exports the source code using `org-babel-tangle'
  228. and then loads the resulting file using `load-file'. With
  229. optional prefix argument COMPILE, the tangled Emacs Lisp file is
  230. byte-compiled before it is loaded."
  231. (interactive "fFile to load: \nP")
  232. (let ((tangled-file (concat (file-name-sans-extension file) ".el")))
  233. ;; Tangle only if the Org file is newer than the Elisp file.
  234. (unless (org-file-newer-than-p
  235. tangled-file
  236. (file-attribute-modification-time
  237. (file-attributes (file-truename file))))
  238. ;; Make sure that tangled file modification time is
  239. ;; updated even when `org-babel-tangle-file' does not make changes.
  240. ;; This avoids re-tangling changed FILE where the changes did
  241. ;; not affect the tangled code.
  242. (when (file-exists-p tangled-file)
  243. (set-file-times tangled-file))
  244. (org-babel-tangle-file file
  245. tangled-file
  246. (rx string-start
  247. (or "emacs-lisp" "elisp")
  248. string-end)))
  249. (if compile
  250. (progn
  251. (byte-compile-file tangled-file)
  252. (load-file (byte-compile-dest-file tangled-file))
  253. (message "Compiled and loaded %s" tangled-file))
  254. (load-file tangled-file)
  255. (message "Loaded %s" tangled-file))))
  256. (defcustom org-babel-load-languages '((emacs-lisp . t))
  257. "Languages which can be evaluated in Org buffers.
  258. \\<org-mode-map>
  259. This list can be used to load support for any of the available
  260. languages with babel support (see info node `(org) Languages'). Each
  261. language will depend on a different set of system executables and/or
  262. Emacs modes.
  263. When a language is \"loaded\", code blocks in that language can
  264. be evaluated with `org-babel-execute-src-block', which is bound
  265. by default to \\[org-ctrl-c-ctrl-c].
  266. The `org-babel-no-eval-on-ctrl-c-ctrl-c' option can be set to
  267. remove code block evaluation from \\[org-ctrl-c-ctrl-c]. By
  268. default, only Emacs Lisp is loaded, since it has no specific
  269. requirement."
  270. :group 'org-babel
  271. :set 'org-babel-do-load-languages
  272. :version "24.1"
  273. :type '(alist :tag "Babel Languages"
  274. :key-type
  275. (choice
  276. (const :tag "Awk" awk)
  277. (const :tag "C" C)
  278. (const :tag "R" R)
  279. (const :tag "Calc" calc)
  280. (const :tag "Clojure" clojure)
  281. (const :tag "CSS" css)
  282. (const :tag "Ditaa" ditaa)
  283. (const :tag "Dot" dot)
  284. (const :tag "Emacs Lisp" emacs-lisp)
  285. (const :tag "Forth" forth)
  286. (const :tag "Fortran" fortran)
  287. (const :tag "Gnuplot" gnuplot)
  288. (const :tag "Haskell" haskell)
  289. (const :tag "Java" java)
  290. (const :tag "Javascript" js)
  291. (const :tag "LaTeX" latex)
  292. (const :tag "Lilypond" lilypond)
  293. (const :tag "Lisp" lisp)
  294. (const :tag "Makefile" makefile)
  295. (const :tag "Maxima" maxima)
  296. (const :tag "Matlab" matlab)
  297. (const :tag "Ocaml" ocaml)
  298. (const :tag "Octave" octave)
  299. (const :tag "Org" org)
  300. (const :tag "Perl" perl)
  301. (const :tag "Pico Lisp" picolisp)
  302. (const :tag "PlantUML" plantuml)
  303. (const :tag "Python" python)
  304. (const :tag "Ruby" ruby)
  305. (const :tag "Sass" sass)
  306. (const :tag "Scala" scala)
  307. (const :tag "Scheme" scheme)
  308. (const :tag "Screen" screen)
  309. (const :tag "Shell Script" shell)
  310. (const :tag "Sql" sql)
  311. (const :tag "Sqlite" sqlite)
  312. (const :tag "Stan" stan))
  313. :value-type (boolean :tag "Activate" :value t)))
  314. ;;;; Customization variables
  315. (defcustom org-clone-delete-id nil
  316. "Remove ID property of clones of a subtree.
  317. When non-nil, clones of a subtree don't inherit the ID property.
  318. Otherwise they inherit the ID property with a new unique
  319. identifier."
  320. :type 'boolean
  321. :version "24.1"
  322. :group 'org-id)
  323. ;;; Version
  324. (org-check-version)
  325. ;;;###autoload
  326. (defun org-version (&optional here full message)
  327. "Show the Org version.
  328. Interactively, or when MESSAGE is non-nil, show it in echo area.
  329. With prefix argument, or when HERE is non-nil, insert it at point.
  330. In non-interactive uses, a reduced version string is output unless
  331. FULL is given."
  332. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  333. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  334. (save-load-suffixes load-suffixes)
  335. (load-suffixes (list ".el"))
  336. (org-install-dir
  337. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  338. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  339. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  340. (let* ((load-suffixes save-load-suffixes)
  341. (release (org-release))
  342. (git-version (org-git-version))
  343. (version (format "Org mode version %s (%s @ %s)"
  344. release
  345. git-version
  346. (if org-install-dir
  347. (if (string= org-dir org-install-dir)
  348. org-install-dir
  349. (concat "mixed installation! "
  350. org-install-dir
  351. " and "
  352. org-dir))
  353. "org-loaddefs.el can not be found!")))
  354. (version1 (if full version release)))
  355. (when here (insert version1))
  356. (when message (message "%s" version1))
  357. version1)))
  358. (defconst org-version (org-version))
  359. ;;; Syntax Constants
  360. ;;;; Comments
  361. (defconst org-comment-regexp
  362. (rx (seq bol (zero-or-more (any "\t ")) "#" (or " " eol)))
  363. "Regular expression for comment lines.")
  364. ;;;; Keyword
  365. (defconst org-keyword-regexp "^[ \t]*#\\+\\(\\S-+?\\):[ \t]*\\(.*\\)$"
  366. "Regular expression for keyword-lines.")
  367. ;;;; Block
  368. (defconst org-block-regexp
  369. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  370. "Regular expression for hiding blocks.")
  371. (defconst org-dblock-start-re
  372. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  373. "Matches the start line of a dynamic block, with parameters.")
  374. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  375. "Matches the end of a dynamic block.")
  376. ;;;; Timestamp
  377. (defconst org-ts--internal-regexp
  378. (rx (seq
  379. (= 4 digit) "-" (= 2 digit) "-" (= 2 digit)
  380. (optional " " (*? nonl))))
  381. "Regular expression matching the innards of a time stamp.")
  382. (defconst org-ts-regexp (format "<\\(%s\\)>" org-ts--internal-regexp)
  383. "Regular expression for fast time stamp matching.")
  384. (defconst org-ts-regexp-inactive
  385. (format "\\[\\(%s\\)\\]" org-ts--internal-regexp)
  386. "Regular expression for fast inactive time stamp matching.")
  387. (defconst org-ts-regexp-both (format "[[<]\\(%s\\)[]>]" org-ts--internal-regexp)
  388. "Regular expression for fast time stamp matching.")
  389. (defconst org-ts-regexp0
  390. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  391. "Regular expression matching time strings for analysis.
  392. This one does not require the space after the date, so it can be used
  393. on a string that terminates immediately after the date.")
  394. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\(?: *\\([^]+0-9>\r\n -]+\\)\\)?\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  395. "Regular expression matching time strings for analysis.")
  396. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  397. "Regular expression matching time stamps, with groups.")
  398. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  399. "Regular expression matching time stamps (also [..]), with groups.")
  400. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  401. "Regular expression matching a time stamp range.")
  402. (defconst org-tr-regexp-both
  403. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  404. "Regular expression matching a time stamp range.")
  405. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  406. org-ts-regexp "\\)?")
  407. "Regular expression matching a time stamp or time stamp range.")
  408. (defconst org-tsr-regexp-both
  409. (concat org-ts-regexp-both "\\(--?-?"
  410. org-ts-regexp-both "\\)?")
  411. "Regular expression matching a time stamp or time stamp range.
  412. The time stamps may be either active or inactive.")
  413. (defconst org-repeat-re
  414. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\
  415. \\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  416. "Regular expression for specifying repeated events.
  417. After a match, group 1 contains the repeat expression.")
  418. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  419. "Formats for `format-time-string' which are used for time stamps.")
  420. ;;;; Clock and Planning
  421. (defconst org-clock-string "CLOCK:"
  422. "String used as prefix for timestamps clocking work hours on an item.")
  423. (defvar org-closed-string "CLOSED:"
  424. "String used as the prefix for timestamps logging closing a TODO entry.")
  425. (defvar org-deadline-string "DEADLINE:"
  426. "String to mark deadline entries.
  427. \\<org-mode-map>
  428. A deadline is this string, followed by a time stamp. It must be
  429. a word, terminated by a colon. You can insert a schedule keyword
  430. and a timestamp with `\\[org-deadline]'.")
  431. (defvar org-scheduled-string "SCHEDULED:"
  432. "String to mark scheduled TODO entries.
  433. \\<org-mode-map>
  434. A schedule is this string, followed by a time stamp. It must be
  435. a word, terminated by a colon. You can insert a schedule keyword
  436. and a timestamp with `\\[org-schedule]'.")
  437. (defconst org-ds-keyword-length
  438. (+ 2
  439. (apply #'max
  440. (mapcar #'length
  441. (list org-deadline-string org-scheduled-string
  442. org-clock-string org-closed-string))))
  443. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  444. (defconst org-planning-line-re
  445. (concat "^[ \t]*"
  446. (regexp-opt
  447. (list org-closed-string org-deadline-string org-scheduled-string)
  448. t))
  449. "Matches a line with planning info.
  450. Matched keyword is in group 1.")
  451. (defconst org-clock-line-re
  452. (concat "^[ \t]*" org-clock-string)
  453. "Matches a line with clock info.")
  454. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  455. "Matches the DEADLINE keyword.")
  456. (defconst org-deadline-time-regexp
  457. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  458. "Matches the DEADLINE keyword together with a time stamp.")
  459. (defconst org-deadline-time-hour-regexp
  460. (concat "\\<" org-deadline-string
  461. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
  462. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  463. (defconst org-deadline-line-regexp
  464. (concat "\\<\\(" org-deadline-string "\\).*")
  465. "Matches the DEADLINE keyword and the rest of the line.")
  466. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  467. "Matches the SCHEDULED keyword.")
  468. (defconst org-scheduled-time-regexp
  469. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  470. "Matches the SCHEDULED keyword together with a time stamp.")
  471. (defconst org-scheduled-time-hour-regexp
  472. (concat "\\<" org-scheduled-string
  473. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
  474. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  475. (defconst org-closed-time-regexp
  476. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  477. "Matches the CLOSED keyword together with a time stamp.")
  478. (defconst org-keyword-time-regexp
  479. (concat "\\<"
  480. (regexp-opt
  481. (list org-scheduled-string org-deadline-string org-closed-string
  482. org-clock-string)
  483. t)
  484. " *[[<]\\([^]>]+\\)[]>]")
  485. "Matches any of the 4 keywords, together with the time stamp.")
  486. (defconst org-keyword-time-not-clock-regexp
  487. (concat
  488. "\\<"
  489. (regexp-opt
  490. (list org-scheduled-string org-deadline-string org-closed-string) t)
  491. " *[[<]\\([^]>]+\\)[]>]")
  492. "Matches any of the 3 keywords, together with the time stamp.")
  493. (defconst org-all-time-keywords
  494. (mapcar (lambda (w) (substring w 0 -1))
  495. (list org-scheduled-string org-deadline-string
  496. org-clock-string org-closed-string))
  497. "List of time keywords.")
  498. ;;;; Drawer
  499. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  500. "Matches first or last line of a hidden block.
  501. Group 1 contains drawer's name or \"END\".")
  502. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  503. "Regular expression matching the first line of a property drawer.")
  504. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  505. "Regular expression matching the last line of a property drawer.")
  506. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  507. "Regular expression matching the first line of a clock drawer.")
  508. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  509. "Regular expression matching the last line of a clock drawer.")
  510. (defconst org-logbook-drawer-re
  511. (rx (seq bol (0+ (any "\t ")) ":LOGBOOK:" (0+ (any "\t ")) "\n"
  512. (*? (0+ nonl) "\n")
  513. (0+ (any "\t ")) ":END:" (0+ (any "\t ")) eol))
  514. "Matches an entire LOGBOOK drawer.")
  515. (defconst org-property-drawer-re
  516. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  517. "\\(?:[ \t]*:\\S-+:\\(?:[ \t].*\\)?[ \t]*\n\\)*?"
  518. "[ \t]*:END:[ \t]*$")
  519. "Matches an entire property drawer.")
  520. (defconst org-clock-drawer-re
  521. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  522. org-clock-drawer-end-re "\\)\n?")
  523. "Matches an entire clock drawer.")
  524. ;;;; Headline
  525. (defconst org-heading-keyword-regexp-format
  526. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  527. "Printf format for a regexp matching a headline with some keyword.
  528. This regexp will match the headline of any node which has the
  529. exact keyword that is put into the format. The keyword isn't in
  530. any group by default, but the stars and the body are.")
  531. (defconst org-heading-keyword-maybe-regexp-format
  532. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  533. "Printf format for a regexp matching a headline, possibly with some keyword.
  534. This regexp can match any headline with the specified keyword, or
  535. without a keyword. The keyword isn't in any group by default,
  536. but the stars and the body are.")
  537. (defconst org-archive-tag "ARCHIVE"
  538. "The tag that marks a subtree as archived.
  539. An archived subtree does not open during visibility cycling, and does
  540. not contribute to the agenda listings.")
  541. (defconst org-tag-re "[[:alnum:]_@#%]+"
  542. "Regexp matching a single tag.")
  543. (defconst org-tag-group-re "[ \t]+\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  544. "Regexp matching the tag group at the end of a line, with leading spaces.
  545. Tags are stored in match group 1. Match group 2 stores the tags
  546. without the enclosing colons.")
  547. (defconst org-tag-line-re
  548. "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  549. "Regexp matching tags in a headline.
  550. Tags are stored in match group 1. Match group 2 stores the tags
  551. without the enclosing colons.")
  552. (eval-and-compile
  553. (defconst org-comment-string "COMMENT"
  554. "Entries starting with this keyword will never be exported.
  555. \\<org-mode-map>
  556. An entry can be toggled between COMMENT and normal with
  557. `\\[org-toggle-comment]'."))
  558. ;;;; LaTeX Environments and Fragments
  559. (defconst org-latex-regexps
  560. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  561. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  562. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  563. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  564. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  565. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  566. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  567. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  568. "Regular expressions for matching embedded LaTeX.")
  569. ;;;; Node Property
  570. (defconst org-effort-property "Effort"
  571. "The property that is being used to keep track of effort estimates.
  572. Effort estimates given in this property need to be in the format
  573. defined in org-duration.el.")
  574. ;;; The custom variables
  575. (defgroup org nil
  576. "Outline-based notes management and organizer."
  577. :tag "Org"
  578. :group 'outlines
  579. :group 'calendar)
  580. (defcustom org-mode-hook nil
  581. "Mode hook for Org mode, run after the mode was turned on."
  582. :group 'org
  583. :type 'hook)
  584. (defcustom org-load-hook nil
  585. "Hook that is run after org.el has been loaded."
  586. :group 'org
  587. :type 'hook)
  588. (make-obsolete-variable
  589. 'org-load-hook
  590. "use `with-eval-after-load' instead." "9.5")
  591. (defcustom org-log-buffer-setup-hook nil
  592. "Hook that is run after an Org log buffer is created."
  593. :group 'org
  594. :version "24.1"
  595. :type 'hook)
  596. (defvar org-modules) ; defined below
  597. (defvar org-modules-loaded nil
  598. "Have the modules been loaded already?")
  599. ;;;###autoload
  600. (defun org-load-modules-maybe (&optional force)
  601. "Load all extensions listed in `org-modules'."
  602. (when (or force (not org-modules-loaded))
  603. (dolist (ext org-modules)
  604. (condition-case nil (require ext)
  605. (error (message "Problems while trying to load feature `%s'" ext))))
  606. (setq org-modules-loaded t)))
  607. (defun org-set-modules (var value)
  608. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  609. (set-default-toplevel-value var value)
  610. (when (featurep 'org)
  611. (org-load-modules-maybe 'force)
  612. (org-element-cache-reset 'all)))
  613. (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)
  614. "Modules that should always be loaded together with org.el.
  615. If a description starts with <C>, the file is not part of Emacs and Org mode,
  616. so loading it will require that you have properly installed org-contrib
  617. package from NonGNU Emacs Lisp Package Archive
  618. https://elpa.nongnu.org/nongnu/org-contrib.html
  619. You can also use this system to load external packages (i.e. neither Org
  620. core modules, nor org-contrib modules). Just add symbols
  621. to the end of the list. If the package is called org-xyz.el, then you need
  622. to add the symbol `xyz', and the package must have a call to:
  623. (provide \\='org-xyz)
  624. For export specific modules, see also `org-export-backends'."
  625. :group 'org
  626. :set 'org-set-modules
  627. :package-version '(Org . "9.5")
  628. :type
  629. '(set :greedy t
  630. (const :tag " bbdb: Links to BBDB entries" ol-bbdb)
  631. (const :tag " bibtex: Links to BibTeX entries" ol-bibtex)
  632. (const :tag " crypt: Encryption of subtrees" org-crypt)
  633. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  634. (const :tag " docview: Links to Docview buffers" ol-docview)
  635. (const :tag " doi: Links to DOI references" ol-doi)
  636. (const :tag " eww: Store link to URL of Eww" ol-eww)
  637. (const :tag " gnus: Links to GNUS folders/messages" ol-gnus)
  638. (const :tag " habit: Track your consistency with habits" org-habit)
  639. (const :tag " id: Global IDs for identifying entries" org-id)
  640. (const :tag " info: Links to Info nodes" ol-info)
  641. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  642. (const :tag " irc: Links to IRC/ERC chat sessions" ol-irc)
  643. (const :tag " mhe: Links to MHE folders/messages" ol-mhe)
  644. (const :tag " mouse: Additional mouse support" org-mouse)
  645. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  646. (const :tag " rmail: Links to RMAIL folders/messages" ol-rmail)
  647. (const :tag " tempo: Fast completion for structures" org-tempo)
  648. (const :tag " w3m: Special cut/paste from w3m to Org mode." ol-w3m)
  649. (const :tag " eshell: Links to working directories in Eshell" ol-eshell)
  650. (const :tag "C annotate-file: Annotate a file with Org syntax" org-annotate-file)
  651. (const :tag "C bookmark: Links to bookmarks" ol-bookmark)
  652. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  653. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  654. (const :tag "C collector: Collect properties into tables" org-collector)
  655. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  656. (const :tag "C elisp-symbol: Links to emacs-lisp symbols" ol-elisp-symbol)
  657. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  658. (const :tag "C eval: Include command output as text" org-eval)
  659. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  660. (const :tag "C git-link: Links to specific file version" ol-git-link)
  661. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  662. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  663. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  664. (const :tag "C mac-iCal: Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  665. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  666. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  667. (const :tag "C man: Links to man pages in Org mode" ol-man)
  668. (const :tag "C mew: Links to Mew folders/messages" ol-mew)
  669. (const :tag "C notify: Notifications for Org mode" org-notify)
  670. (const :tag "C notmuch: Provide Org links to notmuch searches or messages" ol-notmuch)
  671. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  672. (const :tag "C registry: A registry for Org links" org-registry)
  673. (const :tag "C screen: Visit screen sessions through links" org-screen)
  674. (const :tag "C screenshot: Take and manage screenshots in Org files" org-screenshot)
  675. (const :tag "C secretary: Team management with Org" org-secretary)
  676. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  677. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  678. (const :tag "C track: Keep up with Org mode development" org-track)
  679. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  680. (const :tag "C vm: Links to VM folders/messages" ol-vm)
  681. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  682. (const :tag "C wl: Links to Wanderlust folders/messages" ol-wl)
  683. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  684. (defvar org-export-registered-backends) ; From ox.el.
  685. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  686. (declare-function org-export-backend-name "ox" (backend) t)
  687. (defcustom org-export-backends '(ascii html icalendar latex odt)
  688. "List of export back-ends that should be always available.
  689. If a description starts with <C>, the file is not part of Emacs and Org mode,
  690. so loading it will require that you have properly installed org-contrib
  691. package from NonGNU Emacs Lisp Package Archive
  692. https://elpa.nongnu.org/nongnu/org-contrib.html
  693. Unlike to `org-modules', libraries in this list will not be
  694. loaded along with Org, but only once the export framework is
  695. needed.
  696. This variable needs to be set before org.el is loaded. If you
  697. need to make a change while Emacs is running, use the customize
  698. interface or run the following code, where VAL stands for the new
  699. value of the variable, after updating it:
  700. (progn
  701. (setq org-export-registered-backends
  702. (cl-remove-if-not
  703. (lambda (backend)
  704. (let ((name (org-export-backend-name backend)))
  705. (or (memq name val)
  706. (catch \\='parentp
  707. (dolist (b val)
  708. (and (org-export-derived-backend-p b name)
  709. (throw \\='parentp t)))))))
  710. org-export-registered-backends))
  711. (let ((new-list (mapcar #\\='org-export-backend-name
  712. org-export-registered-backends)))
  713. (dolist (backend val)
  714. (cond
  715. ((not (load (format \"ox-%s\" backend) t t))
  716. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  717. backend))
  718. ((not (memq backend new-list)) (push backend new-list))))
  719. (set-default \\='org-export-backends new-list)))
  720. Adding a back-end to this list will also pull the back-end it
  721. depends on, if any."
  722. :group 'org
  723. :group 'org-export
  724. :version "26.1"
  725. :package-version '(Org . "9.0")
  726. :initialize 'custom-initialize-set
  727. :set (lambda (var val)
  728. (if (not (featurep 'ox)) (set-default-toplevel-value var val)
  729. ;; Any back-end not required anymore (not present in VAL and not
  730. ;; a parent of any back-end in the new value) is removed from the
  731. ;; list of registered back-ends.
  732. (setq org-export-registered-backends
  733. (cl-remove-if-not
  734. (lambda (backend)
  735. (let ((name (org-export-backend-name backend)))
  736. (or (memq name val)
  737. (catch 'parentp
  738. (dolist (b val)
  739. (and (org-export-derived-backend-p b name)
  740. (throw 'parentp t)))))))
  741. org-export-registered-backends))
  742. ;; Now build NEW-LIST of both new back-ends and required
  743. ;; parents.
  744. (let ((new-list (mapcar #'org-export-backend-name
  745. org-export-registered-backends)))
  746. (dolist (backend val)
  747. (cond
  748. ((not (load (format "ox-%s" backend) t t))
  749. (message "Problems while trying to load export back-end `%s'"
  750. backend))
  751. ((not (memq backend new-list)) (push backend new-list))))
  752. ;; Set VAR to that list with fixed dependencies.
  753. (set-default-toplevel-value var new-list))))
  754. :type '(set :greedy t
  755. (const :tag " ascii Export buffer to ASCII format" ascii)
  756. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  757. (const :tag " html Export buffer to HTML format" html)
  758. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  759. (const :tag " latex Export buffer to LaTeX format" latex)
  760. (const :tag " man Export buffer to MAN format" man)
  761. (const :tag " md Export buffer to Markdown format" md)
  762. (const :tag " odt Export buffer to ODT format" odt)
  763. (const :tag " org Export buffer to Org format" org)
  764. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  765. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  766. (const :tag "C deck Export buffer to deck.js presentations" deck)
  767. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  768. (const :tag "C groff Export buffer to Groff format" groff)
  769. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  770. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  771. (const :tag "C s5 Export buffer to s5 presentations" s5)
  772. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  773. (eval-after-load 'ox
  774. '(dolist (backend org-export-backends)
  775. (condition-case nil (require (intern (format "ox-%s" backend)))
  776. (error (message "Problems while trying to load export back-end `%s'"
  777. backend)))))
  778. (defcustom org-support-shift-select nil
  779. "Non-nil means make shift-cursor commands select text when possible.
  780. \\<org-mode-map>
  781. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  782. start selecting a region, or enlarge regions started in this way.
  783. In Org mode, in special contexts, these same keys are used for
  784. other purposes, important enough to compete with shift selection.
  785. Org tries to balance these needs by supporting `shift-select-mode'
  786. outside these special contexts, under control of this variable.
  787. The default of this variable is nil, to avoid confusing behavior. Shifted
  788. cursor keys will then execute Org commands in the following contexts:
  789. - on a headline, changing TODO state (left/right) and priority (up/down)
  790. - on a time stamp, changing the time
  791. - in a plain list item, changing the bullet type
  792. - in a property definition line, switching between allowed values
  793. - in the BEGIN line of a clock table (changing the time block).
  794. - in a table, moving the cell in the specified direction.
  795. Outside these contexts, the commands will throw an error.
  796. When this variable is t and the cursor is not in a special
  797. context, Org mode will support shift-selection for making and
  798. enlarging regions. To make this more effective, the bullet
  799. cycling will no longer happen anywhere in an item line, but only
  800. if the cursor is exactly on the bullet.
  801. If you set this variable to the symbol `always', then the keys
  802. will not be special in headlines, property lines, item lines, and
  803. table cells, to make shift selection work there as well. If this is
  804. what you want, you can use the following alternative commands:
  805. `\\[org-todo]' and `\\[org-priority]' \
  806. to change TODO state and priority,
  807. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  808. can be used to switch TODO sets,
  809. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  810. and properties can be edited by hand or in column view.
  811. However, when the cursor is on a timestamp, shift-cursor commands
  812. will still edit the time stamp - this is just too good to give up."
  813. :group 'org
  814. :type '(choice
  815. (const :tag "Never" nil)
  816. (const :tag "When outside special context" t)
  817. (const :tag "Everywhere except timestamps" always)))
  818. (defcustom org-loop-over-headlines-in-active-region t
  819. "Shall some commands act upon headlines in the active region?
  820. When set to t, some commands will be performed in all headlines
  821. within the active region.
  822. When set to `start-level', some commands will be performed in all
  823. headlines within the active region, provided that these headlines
  824. are of the same level than the first one.
  825. When set to a string, those commands will be performed on the
  826. matching headlines within the active region. Such string must be
  827. a tags/property/todo match as it is used in the agenda tags view.
  828. The list of commands is: `org-schedule', `org-deadline',
  829. `org-todo', `org-set-tags-command', `org-archive-subtree',
  830. `org-archive-set-tag', `org-toggle-archive-tag' and
  831. `org-archive-to-archive-sibling'. The archiving commands skip
  832. already archived entries.
  833. See `org-agenda-loop-over-headlines-in-active-region' for the
  834. equivalent option for agenda views."
  835. :type '(choice (const :tag "Don't loop" nil)
  836. (const :tag "All headlines in active region" t)
  837. (const :tag "In active region, headlines at the same level than the first one" start-level)
  838. (string :tag "Tags/Property/Todo matcher"))
  839. :package-version '(Org . "9.4")
  840. :group 'org-todo
  841. :group 'org-archive)
  842. (defcustom org-startup-folded 'showeverything
  843. "Non-nil means entering Org mode will switch to OVERVIEW.
  844. This can also be configured on a per-file basis by adding one of
  845. the following lines anywhere in the buffer:
  846. #+STARTUP: fold (or `overview', this is equivalent)
  847. #+STARTUP: nofold (or `showall', this is equivalent)
  848. #+STARTUP: content
  849. #+STARTUP: show<n>levels (<n> = 2..5)
  850. #+STARTUP: showeverything
  851. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  852. to ignore this option when Org opens agenda files for the first
  853. time."
  854. :group 'org-startup
  855. :package-version '(Org . "9.4")
  856. :type '(choice
  857. (const :tag "nofold: show all" nil)
  858. (const :tag "fold: overview" t)
  859. (const :tag "fold: show two levels" show2levels)
  860. (const :tag "fold: show three levels" show3levels)
  861. (const :tag "fold: show four levels" show4evels)
  862. (const :tag "fold: show five levels" show5levels)
  863. (const :tag "content: all headlines" content)
  864. (const :tag "show everything, even drawers" showeverything)))
  865. (defcustom org-startup-truncated t
  866. "Non-nil means entering Org mode will set `truncate-lines'.
  867. This is useful since some lines containing links can be very long and
  868. uninteresting. Also tables look terrible when wrapped.
  869. The variable `org-startup-truncated' allows to configure
  870. truncation for Org mode different to the other modes that use the
  871. variable `truncate-lines' and as a shortcut instead of putting
  872. the variable `truncate-lines' into the `org-mode-hook'. If one
  873. wants to configure truncation for Org mode not statically but
  874. dynamically e.g. in a hook like `ediff-prepare-buffer-hook' then
  875. the variable `truncate-lines' has to be used because in such a
  876. case it is too late to set the variable `org-startup-truncated'."
  877. :group 'org-startup
  878. :type 'boolean)
  879. (defcustom org-startup-indented nil
  880. "Non-nil means turn on `org-indent-mode' on startup.
  881. This can also be configured on a per-file basis by adding one of
  882. the following lines anywhere in the buffer:
  883. #+STARTUP: indent
  884. #+STARTUP: noindent"
  885. :group 'org-structure
  886. :type '(choice
  887. (const :tag "Not" nil)
  888. (const :tag "Globally (slow on startup in large files)" t)))
  889. (defcustom org-startup-numerated nil
  890. "Non-nil means turn on `org-num-mode' on startup.
  891. This can also be configured on a per-file basis by adding one of
  892. the following lines anywhere in the buffer:
  893. #+STARTUP: num
  894. #+STARTUP: nonum"
  895. :group 'org-structure
  896. :package-version '(Org . "9.4")
  897. :type '(choice
  898. (const :tag "Not" nil)
  899. (const :tag "Globally" t)))
  900. (defcustom org-use-sub-superscripts t
  901. "Non-nil means interpret \"_\" and \"^\" for display.
  902. If you want to control how Org exports those characters, see
  903. `org-export-with-sub-superscripts'.
  904. When this option is turned on, you can use TeX-like syntax for
  905. sub- and superscripts within the buffer. Several characters after
  906. \"_\" or \"^\" will be considered as a single item - so grouping
  907. with {} is normally not needed. For example, the following things
  908. will be parsed as single sub- or superscripts:
  909. 10^24 or 10^tau several digits will be considered 1 item.
  910. 10^-12 or 10^-tau a leading sign with digits or a word
  911. x^2-y^3 will be read as x^2 - y^3, because items are
  912. terminated by almost any nonword/nondigit char.
  913. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  914. Still, ambiguity is possible. So when in doubt, use {} to enclose
  915. the sub/superscript. If you set this variable to the symbol `{}',
  916. the braces are *required* in order to trigger interpretations as
  917. sub/superscript. This can be helpful in documents that need \"_\"
  918. frequently in plain text."
  919. :group 'org-startup
  920. :version "24.4"
  921. :package-version '(Org . "8.0")
  922. :type '(choice
  923. (const :tag "Always interpret" t)
  924. (const :tag "Only with braces" {})
  925. (const :tag "Never interpret" nil)))
  926. (defcustom org-startup-with-beamer-mode nil
  927. "Non-nil means turn on `org-beamer-mode' on startup.
  928. This can also be configured on a per-file basis by adding one of
  929. the following lines anywhere in the buffer:
  930. #+STARTUP: beamer"
  931. :group 'org-startup
  932. :version "24.1"
  933. :type 'boolean)
  934. (defcustom org-startup-align-all-tables nil
  935. "Non-nil means align all tables when visiting a file.
  936. This can also be configured on a per-file basis by adding one of
  937. the following lines anywhere in the buffer:
  938. #+STARTUP: align
  939. #+STARTUP: noalign"
  940. :group 'org-startup
  941. :type 'boolean)
  942. (defcustom org-startup-shrink-all-tables nil
  943. "Non-nil means shrink all table columns with a width cookie.
  944. This can also be configured on a per-file basis by adding one of
  945. the following lines anywhere in the buffer:
  946. #+STARTUP: shrink"
  947. :group 'org-startup
  948. :type 'boolean
  949. :version "27.1"
  950. :package-version '(Org . "9.2")
  951. :safe #'booleanp)
  952. (defcustom org-startup-with-inline-images nil
  953. "Non-nil means show inline images when loading a new Org file.
  954. This can also be configured on a per-file basis by adding one of
  955. the following lines anywhere in the buffer:
  956. #+STARTUP: inlineimages
  957. #+STARTUP: noinlineimages"
  958. :group 'org-startup
  959. :version "24.1"
  960. :type 'boolean)
  961. (defcustom org-startup-with-latex-preview nil
  962. "Non-nil means preview LaTeX fragments when loading a new Org file.
  963. This can also be configured on a per-file basis by adding one of
  964. the following lines anywhere in the buffer:
  965. #+STARTUP: latexpreview
  966. #+STARTUP: nolatexpreview"
  967. :group 'org-startup
  968. :version "24.4"
  969. :package-version '(Org . "8.0")
  970. :type 'boolean)
  971. (defcustom org-insert-mode-line-in-empty-file nil
  972. "Non-nil means insert the first line setting Org mode in empty files.
  973. When the function `org-mode' is called interactively in an empty file, this
  974. normally means that the file name does not automatically trigger Org mode.
  975. To ensure that the file will always be in Org mode in the future, a
  976. line enforcing Org mode will be inserted into the buffer, if this option
  977. has been set."
  978. :group 'org-startup
  979. :type 'boolean)
  980. (defcustom org-ellipsis nil
  981. "The ellipsis to use in the Org mode outline.
  982. When nil, just use the standard three dots. When a non-empty string,
  983. use that string instead.
  984. The change affects only Org mode (which will then use its own display table).
  985. Changing this requires executing `\\[org-mode]' in a buffer to become
  986. effective. It cannot be set as a local variable."
  987. :group 'org-startup
  988. :type '(choice (const :tag "Default" nil)
  989. (string :tag "String" :value "...#")))
  990. (defvar org-display-table nil
  991. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  992. (defcustom org-directory "~/org"
  993. "Directory with Org files.
  994. This is just a default location to look for Org files. There is no need
  995. at all to put your files into this directory. It is used in the
  996. following situations:
  997. 1. When a capture template specifies a target file that is not an
  998. absolute path. The path will then be interpreted relative to
  999. `org-directory'
  1000. 2. When the value of variable `org-agenda-files' is a single file, any
  1001. relative paths in this file will be taken as relative to
  1002. `org-directory'."
  1003. :group 'org-refile
  1004. :group 'org-capture
  1005. :type 'directory)
  1006. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  1007. "Default target for storing notes.
  1008. Used as a fall back file for org-capture.el, for templates that
  1009. do not specify a target file."
  1010. :group 'org-refile
  1011. :group 'org-capture
  1012. :type 'file)
  1013. (defcustom org-reverse-note-order nil
  1014. "Non-nil means store new notes at the beginning of a file or entry.
  1015. When nil, new notes will be filed to the end of a file or entry.
  1016. This can also be a list with cons cells of regular expressions that
  1017. are matched against file names, and values."
  1018. :group 'org-capture
  1019. :group 'org-refile
  1020. :type '(choice
  1021. (const :tag "Reverse always" t)
  1022. (const :tag "Reverse never" nil)
  1023. (repeat :tag "By file name regexp"
  1024. (cons regexp boolean))))
  1025. (defgroup org-keywords nil
  1026. "Keywords in Org mode."
  1027. :tag "Org Keywords"
  1028. :group 'org)
  1029. (defcustom org-closed-keep-when-no-todo nil
  1030. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  1031. :group 'org-todo
  1032. :group 'org-keywords
  1033. :version "24.4"
  1034. :package-version '(Org . "8.0")
  1035. :type 'boolean)
  1036. (defgroup org-structure nil
  1037. "Options concerning the general structure of Org files."
  1038. :tag "Org Structure"
  1039. :group 'org)
  1040. (defcustom org-indirect-buffer-display 'other-window
  1041. "How should indirect tree buffers be displayed?
  1042. This applies to indirect buffers created with the commands
  1043. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1044. Valid values are:
  1045. current-window Display in the current window
  1046. other-window Just display in another window.
  1047. dedicated-frame Create one new frame, and re-use it each time.
  1048. new-frame Make a new frame each time. Note that in this case
  1049. previously-made indirect buffers are kept, and you need to
  1050. kill these buffers yourself."
  1051. :group 'org-structure
  1052. :group 'org-agenda-windows
  1053. :type '(choice
  1054. (const :tag "In current window" current-window)
  1055. (const :tag "In current frame, other window" other-window)
  1056. (const :tag "Each time a new frame" new-frame)
  1057. (const :tag "One dedicated frame" dedicated-frame)))
  1058. (defconst org-file-apps-gnu
  1059. '((remote . emacs)
  1060. (system . mailcap)
  1061. (t . mailcap))
  1062. "Default file applications on a UNIX or GNU/Linux system.
  1063. See `org-file-apps'.")
  1064. (defconst org-file-apps-macos
  1065. '((remote . emacs)
  1066. (system . "open %s")
  1067. ("ps.gz" . "gv %s")
  1068. ("eps.gz" . "gv %s")
  1069. ("dvi" . "xdvi %s")
  1070. ("fig" . "xfig %s")
  1071. (t . "open %s"))
  1072. "Default file applications on a macOS system.
  1073. The system \"open\" is known as a default, but we use X11 applications
  1074. for some files for which the OS does not have a good default.
  1075. See `org-file-apps'.")
  1076. (defconst org-file-apps-windowsnt
  1077. (list '(remote . emacs)
  1078. (cons 'system (lambda (file _path)
  1079. (with-no-warnings (w32-shell-execute "open" file))))
  1080. (cons t (lambda (file _path)
  1081. (with-no-warnings (w32-shell-execute "open" file)))))
  1082. "Default file applications on a Windows NT system.
  1083. The system \"open\" is used for most files.
  1084. See `org-file-apps'.")
  1085. (defcustom org-file-apps
  1086. '((auto-mode . emacs)
  1087. (directory . emacs)
  1088. ("\\.mm\\'" . default)
  1089. ("\\.x?html?\\'" . default)
  1090. ("\\.pdf\\'" . default))
  1091. "Applications for opening `file:path' items in a document.
  1092. \\<org-mode-map>
  1093. Org mode uses system defaults for different file types, but you
  1094. can use this variable to set the application for a given file
  1095. extension. The entries in this list are cons cells where the car
  1096. identifies files and the cdr the corresponding command.
  1097. Possible values for the file identifier are:
  1098. \"string\" A string as a file identifier can be interpreted in different
  1099. ways, depending on its contents:
  1100. - Alphanumeric characters only:
  1101. Match links with this file extension.
  1102. Example: (\"pdf\" . \"evince %s\")
  1103. to open PDFs with evince.
  1104. - Regular expression: Match links where the
  1105. filename matches the regexp. If you want to
  1106. use groups here, use shy groups.
  1107. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1108. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1109. to open *.html and *.xhtml with firefox.
  1110. - Regular expression which contains (non-shy) groups:
  1111. Match links where the whole link, including \"::\", and
  1112. anything after that, matches the regexp.
  1113. In a custom command string, %1, %2, etc. are replaced with
  1114. the parts of the link that were matched by the groups.
  1115. For backwards compatibility, if a command string is given
  1116. that does not use any of the group matches, this case is
  1117. handled identically to the second one (i.e. match against
  1118. file name only).
  1119. In a custom function, you can access the group matches with
  1120. (match-string n link).
  1121. Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
  1122. \"evince -p %1 %s\")
  1123. to open [[file:document.pdf::5]] with evince at page 5.
  1124. Likely, you will need more entries: without page
  1125. number; with search pattern; with cross-reference
  1126. anchor; some combination of options. Consider simple
  1127. pattern here and a Lisp function to determine command
  1128. line arguments instead. Passing argument list to
  1129. `call-process' or `make-process' directly allows to
  1130. avoid treating some character in peculiar file names
  1131. as shell specialls causing executing part of file
  1132. name as a subcommand.
  1133. `directory' Matches a directory
  1134. `remote' Matches a remote file, accessible through tramp.
  1135. Remote files most likely should be visited through Emacs
  1136. because external applications cannot handle such paths.
  1137. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1138. so all files Emacs knows how to handle. Using this with
  1139. command `emacs' will open most files in Emacs. Beware that this
  1140. will also open html files inside Emacs, unless you add
  1141. (\"html\" . default) to the list as well.
  1142. `system' The system command to open files, like `open' on Windows
  1143. and macOS, and mailcap under GNU/Linux. This is the command
  1144. that will be selected if you call `org-open-at-point' with a
  1145. double prefix argument (`\\[universal-argument] \
  1146. \\[universal-argument] \\[org-open-at-point]').
  1147. t Default for files not matched by any of the other options.
  1148. Possible values for the command are:
  1149. `emacs' The file will be visited by the current Emacs process.
  1150. `default' Use the default application for this file type, which is the
  1151. association for t in the list, most likely in the system-specific
  1152. part. This can be used to overrule an unwanted setting in the
  1153. system-specific variable.
  1154. `system' Use the system command for opening files, like \"open\".
  1155. This command is specified by the entry whose car is `system'.
  1156. Most likely, the system-specific version of this variable
  1157. does define this command, but you can overrule/replace it
  1158. here.
  1159. `mailcap' Use command specified in the mailcaps.
  1160. string A command to be executed by a shell; %s will be replaced
  1161. by the path to the file.
  1162. function A Lisp function, which will be called with two arguments:
  1163. the file path and the original link string, without the
  1164. \"file:\" prefix.
  1165. For more examples, see the system specific constants
  1166. `org-file-apps-macos'
  1167. `org-file-apps-windowsnt'
  1168. `org-file-apps-gnu'."
  1169. :group 'org
  1170. :package-version '(Org . "9.4")
  1171. :type '(repeat
  1172. (cons (choice :value ""
  1173. (string :tag "Extension")
  1174. (const :tag "System command to open files" system)
  1175. (const :tag "Default for unrecognized files" t)
  1176. (const :tag "Remote file" remote)
  1177. (const :tag "Links to a directory" directory)
  1178. (const :tag "Any files that have Emacs modes"
  1179. auto-mode))
  1180. (choice :value ""
  1181. (const :tag "Visit with Emacs" emacs)
  1182. (const :tag "Use default" default)
  1183. (const :tag "Use the system command" system)
  1184. (string :tag "Command")
  1185. (function :tag "Function")))))
  1186. (defcustom org-resource-download-policy 'prompt
  1187. "The policy applied to requests to obtain remote resources.
  1188. This affects keywords like #+setupfile and #+incude on export,
  1189. `org-persist-write:url',and `org-attach-url' in non-interactive
  1190. Emacs sessions.
  1191. This recognises four possible values:
  1192. - t, remote resources should always be downloaded.
  1193. - prompt, you will be prompted to download resources nt considered safe.
  1194. - safe, only resources considered safe will be downloaded.
  1195. - nil, never download remote resources.
  1196. A resource is considered safe if it matches one of the patterns
  1197. in `org-safe-remote-resources'."
  1198. :group 'org
  1199. :type '(choice (const :tag "Always download remote resources" t)
  1200. (const :tag "Prompt before downloading an unsafe resource" prompt)
  1201. (const :tag "Only download resources considered safe" safe)
  1202. (const :tag "Never download any resources" nil)))
  1203. (defcustom org-safe-remote-resources nil
  1204. "A list of regexp patterns matching safe URIs.
  1205. URI regexps are applied to both URLs and Org files requesting
  1206. remote resources."
  1207. :group 'org
  1208. :type '(list regexp))
  1209. (defcustom org-open-non-existing-files nil
  1210. "Non-nil means `org-open-file' opens non-existing files.
  1211. When nil, an error is thrown.
  1212. This variable applies only to external applications because they
  1213. might choke on non-existing files. If the link is to a file that
  1214. will be opened in Emacs, the variable is ignored."
  1215. :group 'org
  1216. :type 'boolean
  1217. :safe #'booleanp)
  1218. (defcustom org-open-directory-means-index-dot-org nil
  1219. "When non-nil a link to a directory really means to \"index.org\".
  1220. When nil, following a directory link runs Dired or opens
  1221. a finder/explorer window on that directory."
  1222. :group 'org
  1223. :type 'boolean
  1224. :safe #'booleanp)
  1225. (defcustom org-bookmark-names-plist
  1226. '(:last-capture "org-capture-last-stored"
  1227. :last-refile "org-refile-last-stored"
  1228. :last-capture-marker "org-capture-last-stored-marker")
  1229. "Names for bookmarks automatically set by some Org commands.
  1230. This can provide strings as names for a number of bookmarks Org sets
  1231. automatically. The following keys are currently implemented:
  1232. :last-capture
  1233. :last-capture-marker
  1234. :last-refile
  1235. When a key does not show up in the property list, the corresponding bookmark
  1236. is not set."
  1237. :group 'org-structure
  1238. :type 'plist)
  1239. (defgroup org-edit-structure nil
  1240. "Options concerning structure editing in Org mode."
  1241. :tag "Org Edit Structure"
  1242. :group 'org-structure)
  1243. (defcustom org-odd-levels-only nil
  1244. "Non-nil means skip even levels and only use odd levels for the outline.
  1245. This has the effect that two stars are being added/taken away in
  1246. promotion/demotion commands. It also influences how levels are
  1247. handled by the exporters.
  1248. Changing it requires restart of `font-lock-mode' to become effective
  1249. for fontification also in regions already fontified.
  1250. You may also set this on a per-file basis by adding one of the following
  1251. lines to the buffer:
  1252. #+STARTUP: odd
  1253. #+STARTUP: oddeven"
  1254. :group 'org-edit-structure
  1255. :group 'org-appearance
  1256. :type 'boolean)
  1257. (defcustom org-adapt-indentation nil
  1258. "Non-nil means adapt indentation to outline node level.
  1259. When set to t, Org assumes that you write outlines by indenting
  1260. text in each node to align with the headline, after the stars.
  1261. When this variable is set to `headline-data', Org only adapts the
  1262. indentation of the data lines right below the headline, such as
  1263. planning/clock lines and property/logbook drawers.
  1264. The following issues are influenced by this variable:
  1265. - The indentation is increased by one space in a demotion
  1266. command, and decreased by one in a promotion command. However,
  1267. in the latter case, if shifting some line in the entry body
  1268. would alter document structure (e.g., insert a new headline),
  1269. indentation is not changed at all.
  1270. - Property drawers and planning information is inserted indented
  1271. when this variable is set. When nil, they will not be indented.
  1272. - TAB indents a line relative to current level. The lines below
  1273. a headline will be indented when this variable is set to t.
  1274. Note that this is all about true indentation, by adding and
  1275. removing space characters. See also \"org-indent.el\" which does
  1276. level-dependent indentation in a virtual way, i.e. at display
  1277. time in Emacs."
  1278. :group 'org-edit-structure
  1279. :type '(choice
  1280. (const :tag "Adapt indentation for all lines" t)
  1281. (const :tag "Adapt indentation for headline data lines"
  1282. headline-data)
  1283. (const :tag "Do not adapt indentation at all" nil))
  1284. :safe (lambda (x) (memq x '(t nil headline-data))))
  1285. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1286. (defcustom org-special-ctrl-a/e nil
  1287. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1288. When t, `C-a' will bring back the cursor to the beginning of the
  1289. headline text, i.e. after the stars and after a possible TODO
  1290. keyword. In an item, this will be the position after bullet and
  1291. check-box, if any. When the cursor is already at that position,
  1292. another `C-a' will bring it to the beginning of the line.
  1293. `C-e' will jump to the end of the headline, ignoring the presence
  1294. of tags in the headline. A second `C-e' will then jump to the
  1295. true end of the line, after any tags. This also means that, when
  1296. this variable is non-nil, `C-e' also will never jump beyond the
  1297. end of the heading of a folded section, i.e. not after the
  1298. ellipses.
  1299. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1300. normally, going to the true line boundary first. Only a directly
  1301. following, identical keypress will bring the cursor to the
  1302. special positions.
  1303. This may also be a cons cell where the behavior for `C-a' and
  1304. `C-e' is set separately."
  1305. :group 'org-edit-structure
  1306. :type '(choice
  1307. (const :tag "off" nil)
  1308. (const :tag "on: after stars/bullet and before tags first" t)
  1309. (const :tag "reversed: true line boundary first" reversed)
  1310. (cons :tag "Set C-a and C-e separately"
  1311. (choice :tag "Special C-a"
  1312. (const :tag "off" nil)
  1313. (const :tag "on: after stars/bullet first" t)
  1314. (const :tag "reversed: before stars/bullet first" reversed))
  1315. (choice :tag "Special C-e"
  1316. (const :tag "off" nil)
  1317. (const :tag "on: before tags first" t)
  1318. (const :tag "reversed: after tags first" reversed)))))
  1319. (defcustom org-special-ctrl-k nil
  1320. "Non-nil means that \\<org-mode-map>\\[org-kill-line] \
  1321. will behave specially in headlines.
  1322. When nil, \\[org-kill-line] will call the default `kill-line' command.
  1323. Otherwise, the following will happen when point is in a headline:
  1324. - At the beginning of a headline, kill the entire line.
  1325. - In the middle of the headline text, kill the text up to the tags.
  1326. - After the headline text and before the tags, kill all the tags."
  1327. :group 'org-edit-structure
  1328. :type 'boolean)
  1329. (defcustom org-ctrl-k-protect-subtree nil
  1330. "Non-nil means, do not delete a hidden subtree with `C-k'.
  1331. When set to the symbol `error', simply throw an error when `C-k' is
  1332. used to kill (part-of) a headline that has hidden text behind it.
  1333. Any other non-nil value will result in a query to the user, if it is
  1334. OK to kill that hidden subtree. When nil, kill without remorse."
  1335. :group 'org-edit-structure
  1336. :version "24.1"
  1337. :type '(choice
  1338. (const :tag "Do not protect hidden subtrees" nil)
  1339. (const :tag "Protect hidden subtrees with a security query" t)
  1340. (const :tag "Never kill a hidden subtree with C-k" error)))
  1341. (defcustom org-special-ctrl-o t
  1342. "Non-nil means, make `open-line' (\\[open-line]) insert a row in tables."
  1343. :group 'org-edit-structure
  1344. :type 'boolean)
  1345. (defcustom org-yank-folded-subtrees t
  1346. "Non-nil means when yanking subtrees, fold them.
  1347. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1348. it starts with a heading and all other headings in it are either children
  1349. or siblings, then fold all the subtrees. However, do this only if no
  1350. text after the yank would be swallowed into a folded tree by this action."
  1351. :group 'org-edit-structure
  1352. :type 'boolean)
  1353. (defcustom org-yank-adjusted-subtrees nil
  1354. "Non-nil means when yanking subtrees, adjust the level.
  1355. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1356. this function for details."
  1357. :group 'org-edit-structure
  1358. :type 'boolean)
  1359. (defcustom org-M-RET-may-split-line '((default . t))
  1360. "Non-nil means M-RET will split the line at the cursor position.
  1361. When nil, it will go to the end of the line before making a
  1362. new line.
  1363. You may also set this option in a different way for different
  1364. contexts. Valid contexts are:
  1365. headline when creating a new headline
  1366. item when creating a new item
  1367. table in a table field
  1368. default the value to be used for all contexts not explicitly
  1369. customized"
  1370. :group 'org-structure
  1371. :group 'org-table
  1372. :type '(choice
  1373. (const :tag "Always" t)
  1374. (const :tag "Never" nil)
  1375. (repeat :greedy t :tag "Individual contexts"
  1376. (cons
  1377. (choice :tag "Context"
  1378. (const headline)
  1379. (const item)
  1380. (const table)
  1381. (const default))
  1382. (boolean)))))
  1383. (defcustom org-insert-heading-respect-content nil
  1384. "Non-nil means insert new headings after the current subtree.
  1385. \\<org-mode-map>
  1386. When nil, the new heading is created directly after the current line.
  1387. The commands `\\[org-insert-heading-respect-content]' and \
  1388. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1389. for the duration of the command."
  1390. :group 'org-structure
  1391. :type 'boolean)
  1392. (defcustom org-blank-before-new-entry '((heading . auto)
  1393. (plain-list-item . auto))
  1394. "Should `org-insert-heading' leave a blank line before new heading/item?
  1395. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1396. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1397. which case Org will look at the surrounding headings/items and try to
  1398. make an intelligent decision whether to insert a blank line or not."
  1399. :group 'org-edit-structure
  1400. :type '(list
  1401. (cons (const heading)
  1402. (choice (const :tag "Never" nil)
  1403. (const :tag "Always" t)
  1404. (const :tag "Auto" auto)))
  1405. (cons (const plain-list-item)
  1406. (choice (const :tag "Never" nil)
  1407. (const :tag "Always" t)
  1408. (const :tag "Auto" auto)))))
  1409. (defcustom org-insert-heading-hook nil
  1410. "Hook being run after inserting a new heading."
  1411. :group 'org-edit-structure
  1412. :type 'hook)
  1413. (defgroup org-sparse-trees nil
  1414. "Options concerning sparse trees in Org mode."
  1415. :tag "Org Sparse Trees"
  1416. :group 'org-structure)
  1417. (defcustom org-highlight-sparse-tree-matches t
  1418. "Non-nil means highlight all matches that define a sparse tree.
  1419. The highlights will automatically disappear the next time the buffer is
  1420. changed by an edit command."
  1421. :group 'org-sparse-trees
  1422. :type 'boolean)
  1423. (defcustom org-remove-highlights-with-change t
  1424. "Non-nil means any change to the buffer will remove temporary highlights.
  1425. \\<org-mode-map>\
  1426. Such highlights are created by `org-occur' and `org-clock-display'.
  1427. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1428. to get rid of the highlights.
  1429. The highlights created by `org-latex-preview' always need
  1430. `\\[org-latex-preview]' to be removed."
  1431. :group 'org-sparse-trees
  1432. :group 'org-time
  1433. :type 'boolean)
  1434. (defcustom org-occur-case-fold-search t
  1435. "Non-nil means `org-occur' should be case-insensitive.
  1436. If set to `smart' the search will be case-insensitive only if it
  1437. doesn't specify any upper case character."
  1438. :group 'org-sparse-trees
  1439. :version "26.1"
  1440. :type '(choice
  1441. (const :tag "Case-sensitive" nil)
  1442. (const :tag "Case-insensitive" t)
  1443. (const :tag "Case-insensitive for lower case searches only" smart)))
  1444. (defcustom org-occur-hook '(org-first-headline-recenter)
  1445. "Hook that is run after `org-occur' has constructed a sparse tree.
  1446. This can be used to recenter the window to show as much of the structure
  1447. as possible."
  1448. :group 'org-sparse-trees
  1449. :type 'hook)
  1450. (defcustom org-self-insert-cluster-for-undo nil
  1451. "Non-nil means cluster self-insert commands for undo when possible.
  1452. If this is set, then, like in the Emacs command loop, 20 consecutive
  1453. characters will be undone together.
  1454. This is configurable, because there is some impact on typing performance."
  1455. :group 'org-table
  1456. :type 'boolean)
  1457. (defvaralias 'org-activate-links 'org-highlight-links)
  1458. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1459. "Types of links that should be highlighted in Org files.
  1460. This is a list of symbols, each one of them leading to the
  1461. highlighting of a certain link type.
  1462. You can still open links that are not highlighted.
  1463. In principle, it does not hurt to turn on highlighting for all
  1464. link types. There may be a small gain when turning off unused
  1465. link types. The types are:
  1466. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1467. angle Links in angular brackets that may contain whitespace like
  1468. <bbdb:Carsten Dominik>.
  1469. plain Plain links in normal text, no whitespace, like https://gnu.org.
  1470. radio Text that is matched by a radio target, see manual for details.
  1471. tag Tag settings in a headline (link to tag search).
  1472. date Time stamps (link to calendar).
  1473. footnote Footnote labels.
  1474. If you set this variable during an Emacs session, use `org-mode-restart'
  1475. in the Org buffer so that the change takes effect."
  1476. :group 'org-appearance
  1477. :type '(set :greedy t
  1478. (const :tag "Double bracket links" bracket)
  1479. (const :tag "Angular bracket links" angle)
  1480. (const :tag "Plain text links" plain)
  1481. (const :tag "Radio target matches" radio)
  1482. (const :tag "Tags" tag)
  1483. (const :tag "Timestamps" date)
  1484. (const :tag "Footnotes" footnote)))
  1485. (defcustom org-mark-ring-length 4
  1486. "Number of different positions to be recorded in the ring.
  1487. Changing this requires a restart of Emacs to work correctly."
  1488. :group 'org-link-follow
  1489. :type 'integer)
  1490. (defgroup org-todo nil
  1491. "Options concerning TODO items in Org mode."
  1492. :tag "Org TODO"
  1493. :group 'org)
  1494. (defgroup org-progress nil
  1495. "Options concerning Progress logging in Org mode."
  1496. :tag "Org Progress"
  1497. :group 'org-time)
  1498. (defvar org-todo-interpretation-widgets
  1499. '((:tag "Sequence (cycling hits every state)" sequence)
  1500. (:tag "Type (cycling directly to DONE)" type))
  1501. "The available interpretation symbols for customizing `org-todo-keywords'.
  1502. Interested libraries should add to this list.")
  1503. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  1504. "List of TODO entry keyword sequences and their interpretation.
  1505. \\<org-mode-map>This is a list of sequences.
  1506. Each sequence starts with a symbol, either `sequence' or `type',
  1507. indicating if the keywords should be interpreted as a sequence of
  1508. action steps, or as different types of TODO items. The first
  1509. keywords are states requiring action - these states will select a headline
  1510. for inclusion into the global TODO list Org produces. If one of the
  1511. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  1512. signify that no further action is necessary. If \"|\" is not found,
  1513. the last keyword is treated as the only DONE state of the sequence.
  1514. The command `\\[org-todo]' cycles an entry through these states, and one
  1515. additional state where no keyword is present. For details about this
  1516. cycling, see the manual.
  1517. TODO keywords and interpretation can also be set on a per-file basis with
  1518. the special #+SEQ_TODO and #+TYP_TODO lines.
  1519. Each keyword can optionally specify a character for fast state selection
  1520. \(in combination with the variable `org-use-fast-todo-selection')
  1521. and specifiers for state change logging, using the same syntax that
  1522. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  1523. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  1524. indicates to record a time stamp each time this state is selected.
  1525. Each keyword may also specify if a timestamp or a note should be
  1526. recorded when entering or leaving the state, by adding additional
  1527. characters in the parenthesis after the keyword. This looks like this:
  1528. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  1529. record only the time of the state change. With X and Y being either
  1530. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  1531. Y when leaving the state if and only if the *target* state does not
  1532. define X. You may omit any of the fast-selection key or X or /Y,
  1533. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  1534. For backward compatibility, this variable may also be just a list
  1535. of keywords. In this case the interpretation (sequence or type) will be
  1536. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  1537. :group 'org-todo
  1538. :group 'org-keywords
  1539. :type '(choice
  1540. (repeat :tag "Old syntax, just keywords"
  1541. (string :tag "Keyword"))
  1542. (repeat :tag "New syntax"
  1543. (cons
  1544. (choice
  1545. :tag "Interpretation"
  1546. ;;Quick and dirty way to see
  1547. ;;`org-todo-interpretation'. This takes the
  1548. ;;place of item arguments
  1549. :convert-widget
  1550. (lambda (widget)
  1551. (widget-put widget
  1552. :args (mapcar
  1553. (lambda (x)
  1554. (widget-convert
  1555. (cons 'const x)))
  1556. org-todo-interpretation-widgets))
  1557. widget))
  1558. (repeat
  1559. (string :tag "Keyword"))))))
  1560. (defvar-local org-todo-keywords-1 nil
  1561. "All TODO and DONE keywords active in a buffer.")
  1562. (defvar org-todo-keywords-for-agenda nil)
  1563. (defvar org-done-keywords-for-agenda nil)
  1564. (defvar org-todo-keyword-alist-for-agenda nil)
  1565. (defvar org-tag-alist-for-agenda nil
  1566. "Alist of all tags from all agenda files.")
  1567. (defvar org-tag-groups-alist-for-agenda nil
  1568. "Alist of all groups tags from all current agenda files.")
  1569. (defvar-local org-tag-groups-alist nil)
  1570. (defvar org-agenda-contributing-files nil)
  1571. (defvar-local org-current-tag-alist nil
  1572. "Alist of all tag groups in current buffer.
  1573. This variable takes into consideration `org-tag-alist',
  1574. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  1575. (defvar-local org-not-done-keywords nil)
  1576. (defvar-local org-done-keywords nil)
  1577. (defvar-local org-todo-heads nil)
  1578. (defvar-local org-todo-sets nil)
  1579. (defvar-local org-todo-log-states nil)
  1580. (defvar-local org-todo-kwd-alist nil)
  1581. (defvar-local org-todo-key-alist nil)
  1582. (defvar-local org-todo-key-trigger nil)
  1583. (defcustom org-todo-interpretation 'sequence
  1584. "Controls how TODO keywords are interpreted.
  1585. This variable is in principle obsolete and is only used for
  1586. backward compatibility, if the interpretation of todo keywords is
  1587. not given already in `org-todo-keywords'. See that variable for
  1588. more information."
  1589. :group 'org-todo
  1590. :group 'org-keywords
  1591. :type '(choice (const sequence)
  1592. (const type)))
  1593. (defcustom org-use-fast-todo-selection 'auto
  1594. "\\<org-mode-map>\
  1595. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  1596. This variable describes if and under what circumstances the cycling
  1597. mechanism for TODO keywords will be replaced by a single-key, direct
  1598. selection scheme, where the choices are displayed in a little window.
  1599. When nil, fast selection is never used. This means that the command
  1600. will always switch to the next state.
  1601. When it is the symbol `auto', fast selection is whenever selection
  1602. keys have been defined.
  1603. `expert' is like `auto', but no special window with the keyword
  1604. will be shown, choices will only be listed in the prompt.
  1605. In all cases, the special interface is only used if access keys have
  1606. actually been assigned by the user, i.e. if keywords in the configuration
  1607. are followed by a letter in parenthesis, like TODO(t)."
  1608. :group 'org-todo
  1609. :set (lambda (var val)
  1610. (cond
  1611. ((eq var t) (set-default-toplevel-value var 'auto))
  1612. ((eq var 'prefix) (set-default-toplevel-value var nil))
  1613. (t (set-default-toplevel-value var val))))
  1614. :type '(choice
  1615. (const :tag "Never" nil)
  1616. (const :tag "Automatically, when key letter have been defined" auto)
  1617. (const :tag "Automatically, but don't show the selection window" expert)))
  1618. (defcustom org-provide-todo-statistics t
  1619. "Non-nil means update todo statistics after insert and toggle.
  1620. ALL-HEADLINES means update todo statistics by including headlines
  1621. with no TODO keyword as well, counting them as not done.
  1622. A list of TODO keywords means the same, but skip keywords that are
  1623. not in this list.
  1624. When set to a list of two lists, the first list contains keywords
  1625. to consider as TODO keywords, the second list contains keywords
  1626. to consider as DONE keywords.
  1627. When this is set, todo statistics is updated in the parent of the
  1628. current entry each time a todo state is changed."
  1629. :group 'org-todo
  1630. :type '(choice
  1631. (const :tag "Yes, only for TODO entries" t)
  1632. (const :tag "Yes, including all entries" all-headlines)
  1633. (repeat :tag "Yes, for TODOs in this list"
  1634. (string :tag "TODO keyword"))
  1635. (list :tag "Yes, for TODOs and DONEs in these lists"
  1636. (repeat (string :tag "TODO keyword"))
  1637. (repeat (string :tag "DONE keyword")))
  1638. (other :tag "No TODO statistics" nil)))
  1639. (defcustom org-hierarchical-todo-statistics t
  1640. "Non-nil means TODO statistics covers just direct children.
  1641. When nil, all entries in the subtree are considered.
  1642. This has only an effect if `org-provide-todo-statistics' is set.
  1643. To set this to nil for only a single subtree, use a COOKIE_DATA
  1644. property and include the word \"recursive\" into the value."
  1645. :group 'org-todo
  1646. :type 'boolean)
  1647. (defcustom org-after-todo-state-change-hook nil
  1648. "Hook which is run after the state of a TODO item was changed.
  1649. The new state (a string with a TODO keyword, or nil) is available in the
  1650. Lisp variable `org-state'."
  1651. :group 'org-todo
  1652. :type 'hook)
  1653. (defvar org-blocker-hook nil
  1654. "Hook for functions that are allowed to block a state change.
  1655. Functions in this hook should not modify the buffer.
  1656. Each function gets as its single argument a property list,
  1657. see `org-trigger-hook' for more information about this list.
  1658. If any of the functions in this hook returns nil, the state change
  1659. is blocked.")
  1660. (defvar org-trigger-hook nil
  1661. "Hook for functions that are triggered by a state change.
  1662. Each function gets as its single argument a property list with at
  1663. least the following elements:
  1664. (:type type-of-change :position pos-at-entry-start
  1665. :from old-state :to new-state)
  1666. Depending on the type, more properties may be present.
  1667. This mechanism is currently implemented for:
  1668. TODO state changes
  1669. ------------------
  1670. :type todo-state-change
  1671. :from previous state (keyword as a string), or nil, or a symbol
  1672. `todo' or `done', to indicate the general type of state.
  1673. :to new state, like in :from")
  1674. (defcustom org-enforce-todo-dependencies nil
  1675. "Non-nil means undone TODO entries will block switching the parent to DONE.
  1676. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  1677. be blocked if any prior sibling is not yet done.
  1678. Finally, if the parent is blocked because of ordered siblings of its own,
  1679. the child will also be blocked."
  1680. :set (lambda (var val)
  1681. (set-default-toplevel-value var val)
  1682. (if val
  1683. (add-hook 'org-blocker-hook
  1684. 'org-block-todo-from-children-or-siblings-or-parent)
  1685. (remove-hook 'org-blocker-hook
  1686. 'org-block-todo-from-children-or-siblings-or-parent)))
  1687. :group 'org-todo
  1688. :type 'boolean)
  1689. (defcustom org-enforce-todo-checkbox-dependencies nil
  1690. "Non-nil means unchecked boxes will block switching the parent to DONE.
  1691. When this is nil, checkboxes have no influence on switching TODO states.
  1692. When non-nil, you first need to check off all check boxes before the TODO
  1693. entry can be switched to DONE.
  1694. This variable needs to be set before org.el is loaded, and you need to
  1695. restart Emacs after a change to make the change effective. The only way
  1696. to change it while Emacs is running is through the customize interface."
  1697. :set (lambda (var val)
  1698. (set-default-toplevel-value var val)
  1699. (if val
  1700. (add-hook 'org-blocker-hook
  1701. 'org-block-todo-from-checkboxes)
  1702. (remove-hook 'org-blocker-hook
  1703. 'org-block-todo-from-checkboxes)))
  1704. :group 'org-todo
  1705. :type 'boolean)
  1706. (defcustom org-treat-insert-todo-heading-as-state-change nil
  1707. "Non-nil means inserting a TODO heading is treated as state change.
  1708. So when the command `\\[org-insert-todo-heading]' is used, state change
  1709. logging will apply if appropriate. When nil, the new TODO item will
  1710. be inserted directly, and no logging will take place."
  1711. :group 'org-todo
  1712. :type 'boolean)
  1713. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  1714. "Non-nil means switching TODO states with S-cursor counts as state change.
  1715. This is the default behavior. However, setting this to nil allows a
  1716. convenient way to select a TODO state and bypass any logging associated
  1717. with that."
  1718. :group 'org-todo
  1719. :type 'boolean)
  1720. (defcustom org-todo-state-tags-triggers nil
  1721. "Tag changes that should be triggered by TODO state changes.
  1722. This is a list. Each entry is
  1723. (state-change (tag . flag) .......)
  1724. State-change can be a string with a state, and empty string to indicate the
  1725. state that has no TODO keyword, or it can be one of the symbols `todo'
  1726. or `done', meaning any not-done or done state, respectively."
  1727. :group 'org-todo
  1728. :group 'org-tags
  1729. :type '(repeat
  1730. (cons (choice :tag "When changing to"
  1731. (const :tag "Not-done state" todo)
  1732. (const :tag "Done state" done)
  1733. (string :tag "State"))
  1734. (repeat
  1735. (cons :tag "Tag action"
  1736. (string :tag "Tag")
  1737. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  1738. (defcustom org-log-done nil
  1739. "Information to record when a task moves to the DONE state.
  1740. Possible values are:
  1741. nil Don't add anything, just change the keyword
  1742. time Add a time stamp to the task
  1743. note Prompt for a note and add it with template `org-log-note-headings'
  1744. This option can also be set with on a per-file-basis with
  1745. #+STARTUP: nologdone
  1746. #+STARTUP: logdone
  1747. #+STARTUP: lognotedone
  1748. You can have local logging settings for a subtree by setting the LOGGING
  1749. property to one or more of these keywords."
  1750. :group 'org-todo
  1751. :group 'org-progress
  1752. :type '(choice
  1753. (const :tag "No logging" nil)
  1754. (const :tag "Record CLOSED timestamp" time)
  1755. (const :tag "Record CLOSED timestamp with note." note)))
  1756. ;; Normalize old uses of org-log-done.
  1757. (cond
  1758. ((eq org-log-done t) (setq org-log-done 'time))
  1759. ((and (listp org-log-done) (memq 'done org-log-done))
  1760. (setq org-log-done 'note)))
  1761. (defcustom org-log-reschedule nil
  1762. "Information to record when the scheduling date of a task is modified.
  1763. Possible values are:
  1764. nil Don't add anything, just change the date
  1765. time Add a time stamp to the task
  1766. note Prompt for a note and add it with template `org-log-note-headings'
  1767. This option can also be set with on a per-file-basis with
  1768. #+STARTUP: nologreschedule
  1769. #+STARTUP: logreschedule
  1770. #+STARTUP: lognotereschedule
  1771. You can have local logging settings for a subtree by setting the LOGGING
  1772. property to one or more of these keywords.
  1773. This variable has an effect when calling `org-schedule' or
  1774. `org-agenda-schedule' only."
  1775. :group 'org-todo
  1776. :group 'org-progress
  1777. :type '(choice
  1778. (const :tag "No logging" nil)
  1779. (const :tag "Record timestamp" time)
  1780. (const :tag "Record timestamp with note" note)))
  1781. (defcustom org-log-redeadline nil
  1782. "Information to record when the deadline date of a task is modified.
  1783. Possible values are:
  1784. nil Don't add anything, just change the date
  1785. time Add a time stamp to the task
  1786. note Prompt for a note and add it with template `org-log-note-headings'
  1787. This option can also be set with on a per-file-basis with
  1788. #+STARTUP: nologredeadline
  1789. #+STARTUP: logredeadline
  1790. #+STARTUP: lognoteredeadline
  1791. You can have local logging settings for a subtree by setting the LOGGING
  1792. property to one or more of these keywords.
  1793. This variable has an effect when calling `org-deadline' or
  1794. `org-agenda-deadline' only."
  1795. :group 'org-todo
  1796. :group 'org-progress
  1797. :type '(choice
  1798. (const :tag "No logging" nil)
  1799. (const :tag "Record timestamp" time)
  1800. (const :tag "Record timestamp with note." note)))
  1801. (defcustom org-log-note-clock-out nil
  1802. "Non-nil means record a note when clocking out of an item.
  1803. This can also be configured on a per-file basis by adding one of
  1804. the following lines anywhere in the buffer:
  1805. #+STARTUP: lognoteclock-out
  1806. #+STARTUP: nolognoteclock-out"
  1807. :group 'org-todo
  1808. :group 'org-progress
  1809. :type 'boolean)
  1810. (defcustom org-log-done-with-time t
  1811. "Non-nil means the CLOSED time stamp will contain date and time.
  1812. When nil, only the date will be recorded."
  1813. :group 'org-progress
  1814. :type 'boolean)
  1815. (defcustom org-log-note-headings
  1816. '((done . "CLOSING NOTE %t")
  1817. (state . "State %-12s from %-12S %t")
  1818. (note . "Note taken on %t")
  1819. (reschedule . "Rescheduled from %S on %t")
  1820. (delschedule . "Not scheduled, was %S on %t")
  1821. (redeadline . "New deadline from %S on %t")
  1822. (deldeadline . "Removed deadline, was %S on %t")
  1823. (refile . "Refiled on %t")
  1824. (clock-out . ""))
  1825. "Headings for notes added to entries.
  1826. The value is an alist, with the car being a symbol indicating the
  1827. note context, and the cdr is the heading to be used. The heading
  1828. may also be the empty string. The following placeholders can be
  1829. used:
  1830. %t a time stamp.
  1831. %T an active time stamp instead the default inactive one
  1832. %d a short-format time stamp.
  1833. %D an active short-format time stamp.
  1834. %s the new TODO state or time stamp (inactive), in double quotes.
  1835. %S the old TODO state or time stamp (inactive), in double quotes.
  1836. %u the user name.
  1837. %U full user name.
  1838. In fact, it is not a good idea to change the `state' entry,
  1839. because Agenda Log mode depends on the format of these entries."
  1840. :group 'org-todo
  1841. :group 'org-progress
  1842. :type '(list :greedy t
  1843. (cons (const :tag "Heading when closing an item" done) string)
  1844. (cons (const :tag
  1845. "Heading when changing todo state (todo sequence only)"
  1846. state) string)
  1847. (cons (const :tag "Heading when just taking a note" note) string)
  1848. (cons (const :tag "Heading when rescheduling" reschedule) string)
  1849. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  1850. (cons (const :tag "Heading when changing deadline" redeadline) string)
  1851. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  1852. (cons (const :tag "Heading when refiling" refile) string)
  1853. (cons (const :tag "Heading when clocking out" clock-out) string)))
  1854. (unless (assq 'note org-log-note-headings)
  1855. (push '(note . "%t") org-log-note-headings))
  1856. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  1857. (defcustom org-log-into-drawer nil
  1858. "Non-nil means insert state change notes and time stamps into a drawer.
  1859. When nil, state changes notes will be inserted after the headline and
  1860. any scheduling and clock lines, but not inside a drawer.
  1861. The value of this variable should be the name of the drawer to use.
  1862. LOGBOOK is proposed as the default drawer for this purpose, you can
  1863. also set this to a string to define the drawer of your choice.
  1864. A value of t is also allowed, representing \"LOGBOOK\".
  1865. A value of t or nil can also be set with on a per-file-basis with
  1866. #+STARTUP: logdrawer
  1867. #+STARTUP: nologdrawer
  1868. If this variable is set, `org-log-state-notes-insert-after-drawers'
  1869. will be ignored.
  1870. You can set the property LOG_INTO_DRAWER to overrule this setting for
  1871. a subtree.
  1872. Do not check directly this variable in a Lisp program. Call
  1873. function `org-log-into-drawer' instead."
  1874. :group 'org-todo
  1875. :group 'org-progress
  1876. :type '(choice
  1877. (const :tag "Not into a drawer" nil)
  1878. (const :tag "LOGBOOK" t)
  1879. (string :tag "Other")))
  1880. (defun org-log-into-drawer ()
  1881. "Name of the log drawer, as a string, or nil.
  1882. This is the value of `org-log-into-drawer'. However, if the
  1883. current entry has or inherits a LOG_INTO_DRAWER property, it will
  1884. be used instead of the default value."
  1885. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  1886. (cond ((equal p "nil") nil)
  1887. ((equal p "t") "LOGBOOK")
  1888. ((stringp p) p)
  1889. (p "LOGBOOK")
  1890. ((stringp org-log-into-drawer) org-log-into-drawer)
  1891. (org-log-into-drawer "LOGBOOK"))))
  1892. (defcustom org-log-state-notes-insert-after-drawers nil
  1893. "Non-nil means insert state change notes after any drawers in entry.
  1894. Only the drawers that *immediately* follow the headline and the
  1895. deadline/scheduled line are skipped.
  1896. When nil, insert notes right after the heading and perhaps the line
  1897. with deadline/scheduling if present.
  1898. This variable will have no effect if `org-log-into-drawer' is
  1899. set."
  1900. :group 'org-todo
  1901. :group 'org-progress
  1902. :type 'boolean)
  1903. (defcustom org-log-states-order-reversed t
  1904. "Non-nil means the latest state note will be directly after heading.
  1905. When nil, the state change notes will be ordered according to time.
  1906. This option can also be set with on a per-file-basis with
  1907. #+STARTUP: logstatesreversed
  1908. #+STARTUP: nologstatesreversed"
  1909. :group 'org-todo
  1910. :group 'org-progress
  1911. :type 'boolean)
  1912. (defcustom org-todo-repeat-to-state nil
  1913. "The TODO state to which a repeater should return the repeating task.
  1914. By default this is the first task of a TODO sequence or the
  1915. previous state of a TYPE_TODO set. But you can specify to use
  1916. the previous state in a TODO sequence or a string.
  1917. Alternatively, you can set the :REPEAT_TO_STATE: property of the
  1918. entry, which has precedence over this option."
  1919. :group 'org-todo
  1920. :version "24.1"
  1921. :type '(choice (const :tag "Use the previous TODO state" t)
  1922. (const :tag "Use the head of the TODO sequence" nil)
  1923. (string :tag "Use a specific TODO state")))
  1924. (defcustom org-log-repeat 'time
  1925. "Non-nil means record moving through the DONE state when triggering repeat.
  1926. An auto-repeating task is immediately switched back to TODO when
  1927. marked DONE. If you are not logging state changes (by adding \"@\"
  1928. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  1929. record a closing note, there will be no record of the task moving
  1930. through DONE. This variable forces taking a note anyway.
  1931. nil Don't force a record
  1932. time Record a time stamp
  1933. note Prompt for a note and add it with template `org-log-note-headings'
  1934. This option can also be set with on a per-file-basis with
  1935. #+STARTUP: nologrepeat
  1936. #+STARTUP: logrepeat
  1937. #+STARTUP: lognoterepeat
  1938. You can have local logging settings for a subtree by setting the LOGGING
  1939. property to one or more of these keywords."
  1940. :group 'org-todo
  1941. :group 'org-progress
  1942. :type '(choice
  1943. (const :tag "Don't force a record" nil)
  1944. (const :tag "Force recording the DONE state" time)
  1945. (const :tag "Force recording a note with the DONE state" note)))
  1946. (defcustom org-todo-repeat-hook nil
  1947. "Hook that is run after a task has been repeated."
  1948. :package-version '(Org . "9.2")
  1949. :group 'org-todo
  1950. :type 'hook)
  1951. (defgroup org-priorities nil
  1952. "Priorities in Org mode."
  1953. :tag "Org Priorities"
  1954. :group 'org-todo)
  1955. (defvaralias 'org-enable-priority-commands 'org-priority-enable-commands)
  1956. (defcustom org-priority-enable-commands t
  1957. "Non-nil means priority commands are active.
  1958. When nil, these commands will be disabled, so that you never accidentally
  1959. set a priority."
  1960. :group 'org-priorities
  1961. :type 'boolean)
  1962. (defvaralias 'org-highest-priority 'org-priority-highest)
  1963. (defcustom org-priority-highest ?A
  1964. "The highest priority of TODO items.
  1965. A character like ?A, ?B, etc., or a numeric value like 1, 2, etc.
  1966. The default is the character ?A, which is 65 as a numeric value.
  1967. If you set `org-priority-highest' to a numeric value inferior to
  1968. 65, Org assumes you want to use digits for the priority cookie.
  1969. If you set it to >=65, Org assumes you want to use alphabetical
  1970. characters.
  1971. In both cases, the value of `org-priority-highest' must be
  1972. smaller than `org-priority-lowest': for example, if \"A\" is the
  1973. highest priority, it is smaller than the lowest \"C\" priority:
  1974. 65 < 67."
  1975. :group 'org-priorities
  1976. :type '(choice
  1977. (character :tag "Character")
  1978. (integer :tag "Integer (< 65)")))
  1979. (defvaralias 'org-lowest-priority 'org-priority-lowest)
  1980. (defcustom org-priority-lowest ?C
  1981. "The lowest priority of TODO items.
  1982. A character like ?C, ?B, etc., or a numeric value like 9, 8, etc.
  1983. The default is the character ?C, which is 67 as a numeric value.
  1984. If you set `org-priority-lowest' to a numeric value inferior to
  1985. 65, Org assumes you want to use digits for the priority cookie.
  1986. If you set it to >=65, Org assumes you want to use alphabetical
  1987. characters.
  1988. In both cases, the value of `org-priority-lowest' must be greater
  1989. than `org-priority-highest': for example, if \"C\" is the lowest
  1990. priority, it is greater than the highest \"A\" priority: 67 >
  1991. 65."
  1992. :group 'org-priorities
  1993. :type '(choice
  1994. (character :tag "Character")
  1995. (integer :tag "Integer (< 65)")))
  1996. (defvaralias 'org-default-priority 'org-priority-default)
  1997. (defcustom org-priority-default ?B
  1998. "The default priority of TODO items.
  1999. This is the priority an item gets if no explicit priority is given.
  2000. When starting to cycle on an empty priority the first step in the cycle
  2001. depends on `org-priority-start-cycle-with-default'. The resulting first
  2002. step priority must not exceed the range from `org-priority-highest' to
  2003. `org-priority-lowest' which means that `org-priority-default' has to be
  2004. in this range exclusive or inclusive to the range boundaries. Else the
  2005. first step refuses to set the default and the second will fall back on
  2006. \(depending on the command used) the highest or lowest priority."
  2007. :group 'org-priorities
  2008. :type '(choice
  2009. (character :tag "Character")
  2010. (integer :tag "Integer (< 65)")))
  2011. (defcustom org-priority-start-cycle-with-default t
  2012. "Non-nil means start with default priority when starting to cycle.
  2013. When this is nil, the first step in the cycle will be (depending on the
  2014. command used) one higher or lower than the default priority.
  2015. See also `org-priority-default'."
  2016. :group 'org-priorities
  2017. :type 'boolean)
  2018. (defvaralias 'org-get-priority-function 'org-priority-get-priority-function)
  2019. (defcustom org-priority-get-priority-function nil
  2020. "Function to extract the priority from a string.
  2021. The string is normally the headline. If this is nil, Org
  2022. computes the priority from the priority cookie like [#A] in the
  2023. headline. It returns an integer, increasing by 1000 for each
  2024. priority level.
  2025. The user can set a different function here, which should take a
  2026. string as an argument and return the numeric priority."
  2027. :group 'org-priorities
  2028. :version "24.1"
  2029. :type '(choice
  2030. (const nil)
  2031. (function)))
  2032. (defgroup org-time nil
  2033. "Options concerning time stamps and deadlines in Org mode."
  2034. :tag "Org Time"
  2035. :group 'org)
  2036. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2037. "Number of minutes to round time stamps to.
  2038. \\<org-mode-map>\
  2039. These are two values, the first applies when first creating a time stamp.
  2040. The second applies when changing it with the commands `S-up' and `S-down'.
  2041. When changing the time stamp, this means that it will change in steps
  2042. of N minutes, as given by the second value.
  2043. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2044. numbers should be factors of 60, so for example 5, 10, 15.
  2045. When this is larger than 1, you can still force an exact time stamp by using
  2046. a double prefix argument to a time stamp command like \
  2047. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2048. and by using a prefix arg to `S-up/down' to specify the exact number
  2049. of minutes to shift."
  2050. :group 'org-time
  2051. :get (lambda (var) ; Make sure both elements are there
  2052. (if (integerp (default-value var))
  2053. (list (default-value var) 5)
  2054. (default-value var)))
  2055. :type '(list
  2056. (integer :tag "when inserting times")
  2057. (integer :tag "when modifying times")))
  2058. ;; Normalize old customizations of this variable.
  2059. (when (integerp org-time-stamp-rounding-minutes)
  2060. (setq org-time-stamp-rounding-minutes
  2061. (list org-time-stamp-rounding-minutes
  2062. org-time-stamp-rounding-minutes)))
  2063. (defcustom org-display-custom-times nil
  2064. "Non-nil means overlay custom formats over all time stamps.
  2065. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2066. To turn this on on a per-file basis, insert anywhere in the file:
  2067. #+STARTUP: customtime"
  2068. :group 'org-time
  2069. :type 'sexp)
  2070. (make-variable-buffer-local 'org-display-custom-times)
  2071. (defcustom org-time-stamp-custom-formats
  2072. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2073. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2074. These are overlaid over the default ISO format if the variable
  2075. `org-display-custom-times' is set. Time like %H:%M should be at the
  2076. end of the second format. The custom formats are also honored by export
  2077. commands, if custom time display is turned on at the time of export."
  2078. :group 'org-time
  2079. :type 'sexp)
  2080. (defun org-time-stamp-format (&optional long inactive)
  2081. "Get the right format for a time string."
  2082. (let ((f (if long (cdr org-time-stamp-formats)
  2083. (car org-time-stamp-formats))))
  2084. (if inactive
  2085. (concat "[" (substring f 1 -1) "]")
  2086. f)))
  2087. (defcustom org-deadline-warning-days 14
  2088. "Number of days before expiration during which a deadline becomes active.
  2089. This variable governs the display in sparse trees and in the agenda.
  2090. When 0 or negative, it means use this number (the absolute value of it)
  2091. even if a deadline has a different individual lead time specified.
  2092. Custom commands can set this variable in the options section."
  2093. :group 'org-time
  2094. :group 'org-agenda-daily/weekly
  2095. :type 'integer)
  2096. (defcustom org-scheduled-delay-days 0
  2097. "Number of days before a scheduled item becomes active.
  2098. This variable governs the display in sparse trees and in the agenda.
  2099. The default value (i.e. 0) means: don't delay scheduled item.
  2100. When negative, it means use this number (the absolute value of it)
  2101. even if a scheduled item has a different individual delay time
  2102. specified.
  2103. Custom commands can set this variable in the options section."
  2104. :group 'org-time
  2105. :group 'org-agenda-daily/weekly
  2106. :version "24.4"
  2107. :package-version '(Org . "8.0")
  2108. :type 'integer)
  2109. (defcustom org-read-date-prefer-future t
  2110. "Non-nil means assume future for incomplete date input from user.
  2111. This affects the following situations:
  2112. 1. The user gives a month but not a year.
  2113. For example, if it is April and you enter \"feb 2\", this will be read
  2114. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2115. 2. The user gives a day, but no month.
  2116. For example, if today is the 15th, and you enter \"3\", Org will read
  2117. this as the third of *next* month. However, if you enter \"17\",
  2118. it will be considered as *this* month.
  2119. If you set this variable to the symbol `time', then also the following
  2120. will work:
  2121. 3. If the user gives a time.
  2122. If the time is before now, it will be interpreted as tomorrow.
  2123. Currently none of this works for ISO week specifications.
  2124. When this option is nil, the current day, month and year will always be
  2125. used as defaults.
  2126. See also `org-agenda-jump-prefer-future'."
  2127. :group 'org-time
  2128. :type '(choice
  2129. (const :tag "Never" nil)
  2130. (const :tag "Check month and day" t)
  2131. (const :tag "Check month, day, and time" time)))
  2132. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2133. "Should the agenda jump command prefer the future for incomplete dates?
  2134. The default is to do the same as configured in `org-read-date-prefer-future'.
  2135. But you can also set a deviating value here.
  2136. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2137. :group 'org-agenda
  2138. :group 'org-time
  2139. :version "24.1"
  2140. :type '(choice
  2141. (const :tag "Use org-read-date-prefer-future"
  2142. org-read-date-prefer-future)
  2143. (const :tag "Never" nil)
  2144. (const :tag "Always" t)))
  2145. (defcustom org-read-date-force-compatible-dates t
  2146. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2147. Depending on the system Emacs is running on, certain dates cannot
  2148. be represented with the type used internally to represent time.
  2149. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2150. correctly. Some systems allow for earlier dates, some for later,
  2151. some for both. One way to find out is to insert any date into an
  2152. Org buffer, putting the cursor on the year and hitting S-up and
  2153. S-down to test the range.
  2154. When this variable is set to t, the date/time prompt will not let
  2155. you specify dates outside the 1970-2037 range, so it is certain that
  2156. these dates will work in whatever version of Emacs you are
  2157. running, and also that you can move a file from one Emacs implementation
  2158. to another. Whenever Org is forcing the year for you, it will display
  2159. a message and beep.
  2160. When this variable is nil, Org will check if the date is
  2161. representable in the specific Emacs implementation you are using.
  2162. If not, it will force a year, usually the current year, and beep
  2163. to remind you. Currently this setting is not recommended because
  2164. the likelihood that you will open your Org files in an Emacs that
  2165. has limited date range is not negligible.
  2166. A workaround for this problem is to use diary sexp dates for time
  2167. stamps outside of this range."
  2168. :group 'org-time
  2169. :version "24.1"
  2170. :type 'boolean)
  2171. (defcustom org-read-date-display-live t
  2172. "Non-nil means display current interpretation of date prompt live.
  2173. This display will be in an overlay, in the minibuffer. Note that
  2174. live display is only active when `org-read-date-popup-calendar'
  2175. is non-nil."
  2176. :group 'org-time
  2177. :type 'boolean)
  2178. (defvaralias 'org-popup-calendar-for-date-prompt
  2179. 'org-read-date-popup-calendar)
  2180. (defcustom org-read-date-popup-calendar t
  2181. "Non-nil means pop up a calendar when prompting for a date.
  2182. In the calendar, the date can be selected with mouse-1. However, the
  2183. minibuffer will also be active, and you can simply enter the date as well.
  2184. When nil, only the minibuffer will be available."
  2185. :group 'org-time
  2186. :type 'boolean)
  2187. (defcustom org-extend-today-until 0
  2188. "The hour when your day really ends. Must be an integer.
  2189. This has influence for the following applications:
  2190. - When switching the agenda to \"today\". If it is still earlier than
  2191. the time given here, the day recognized as TODAY is actually yesterday.
  2192. - When a date is read from the user and it is still before the time given
  2193. here, the current date and time will be assumed to be yesterday, 23:59.
  2194. Also, timestamps inserted in capture templates follow this rule.
  2195. IMPORTANT: This is a feature whose implementation is and likely will
  2196. remain incomplete. Really, it is only here because past midnight seems to
  2197. be the favorite working time of John Wiegley :-)"
  2198. :group 'org-time
  2199. :type 'integer)
  2200. (defcustom org-use-effective-time nil
  2201. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2202. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2203. \"effective time\" of any timestamps between midnight and 8am will be
  2204. 23:59 of the previous day."
  2205. :group 'org-time
  2206. :version "24.1"
  2207. :type 'boolean)
  2208. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2209. "When non-nil, use the last clock out time for `org-todo'.
  2210. Note that this option has precedence over the combined use of
  2211. `org-use-effective-time' and `org-extend-today-until'."
  2212. :group 'org-time
  2213. :version "24.4"
  2214. :package-version '(Org . "8.0")
  2215. :type 'boolean)
  2216. (defcustom org-edit-timestamp-down-means-later nil
  2217. "Non-nil means S-down will increase the time in a time stamp.
  2218. When nil, S-up will increase."
  2219. :group 'org-time
  2220. :type 'boolean)
  2221. (defcustom org-calendar-follow-timestamp-change t
  2222. "Non-nil means make the calendar window follow timestamp changes.
  2223. When a timestamp is modified and the calendar window is visible, it will be
  2224. moved to the new date."
  2225. :group 'org-time
  2226. :type 'boolean)
  2227. (defgroup org-tags nil
  2228. "Options concerning tags in Org mode."
  2229. :tag "Org Tags"
  2230. :group 'org)
  2231. (defcustom org-tag-alist nil
  2232. "Default tags available in Org files.
  2233. The value of this variable is an alist. Associations either:
  2234. (TAG)
  2235. (TAG . SELECT)
  2236. (SPECIAL)
  2237. where TAG is a tag as a string, SELECT is character, used to
  2238. select that tag through the fast tag selection interface, and
  2239. SPECIAL is one of the following keywords: `:startgroup',
  2240. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2241. `:newline'. These keywords are used to define a hierarchy of
  2242. tags. See manual for details.
  2243. When this variable is nil, Org mode bases tag input on what is
  2244. already in the buffer. The value can be overridden locally by
  2245. using a TAGS keyword, e.g.,
  2246. #+TAGS: tag1 tag2
  2247. See also `org-tag-persistent-alist' to sidestep this behavior."
  2248. :group 'org-tags
  2249. :type '(repeat
  2250. (choice
  2251. (cons :tag "Tag with key"
  2252. (string :tag "Tag name")
  2253. (character :tag "Access char"))
  2254. (list :tag "Tag" (string :tag "Tag name"))
  2255. (const :tag "Start radio group" (:startgroup))
  2256. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2257. (const :tag "Group tags delimiter" (:grouptags))
  2258. (const :tag "End radio group" (:endgroup))
  2259. (const :tag "End tag group, non distinct" (:endgrouptag))
  2260. (const :tag "New line" (:newline)))))
  2261. (defcustom org-tag-persistent-alist nil
  2262. "Tags always available in Org files.
  2263. The value of this variable is an alist. Associations either:
  2264. (TAG)
  2265. (TAG . SELECT)
  2266. (SPECIAL)
  2267. where TAG is a tag as a string, SELECT is a character, used to
  2268. select that tag through the fast tag selection interface, and
  2269. SPECIAL is one of the following keywords: `:startgroup',
  2270. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2271. `:newline'. These keywords are used to define a hierarchy of
  2272. tags. See manual for details.
  2273. Unlike to `org-tag-alist', tags defined in this variable do not
  2274. depend on a local TAGS keyword. Instead, to disable these tags
  2275. on a per-file basis, insert anywhere in the file:
  2276. #+STARTUP: noptag"
  2277. :group 'org-tags
  2278. :type '(repeat
  2279. (choice
  2280. (cons :tag "Tag with key"
  2281. (string :tag "Tag name")
  2282. (character :tag "Access char"))
  2283. (list :tag "Tag" (string :tag "Tag name"))
  2284. (const :tag "Start radio group" (:startgroup))
  2285. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2286. (const :tag "Group tags delimiter" (:grouptags))
  2287. (const :tag "End radio group" (:endgroup))
  2288. (const :tag "End tag group, non distinct" (:endgrouptag))
  2289. (const :tag "New line" (:newline)))))
  2290. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2291. "If non-nil, always offer completion for all tags of all agenda files.
  2292. Setting this variable locally allows for dynamic generation of tag
  2293. completions in capture buffers.
  2294. (add-hook \\='org-capture-mode-hook
  2295. (lambda ()
  2296. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  2297. :group 'org-tags
  2298. :version "24.1"
  2299. :type 'boolean)
  2300. (defvar org-file-tags nil
  2301. "List of tags that can be inherited by all entries in the file.
  2302. The tags will be inherited if the variable `org-use-tag-inheritance'
  2303. says they should be.
  2304. This variable is populated from #+FILETAGS lines.")
  2305. (defcustom org-use-fast-tag-selection 'auto
  2306. "Non-nil means use fast tag selection scheme.
  2307. This is a special interface to select and deselect tags with single keys.
  2308. When nil, fast selection is never used.
  2309. When the symbol `auto', fast selection is used if and only if selection
  2310. characters for tags have been configured, either through the variable
  2311. `org-tag-alist' or through a #+TAGS line in the buffer.
  2312. When t, fast selection is always used and selection keys are assigned
  2313. automatically if necessary."
  2314. :group 'org-tags
  2315. :type '(choice
  2316. (const :tag "Always" t)
  2317. (const :tag "Never" nil)
  2318. (const :tag "When selection characters are configured" auto)))
  2319. (defcustom org-fast-tag-selection-single-key nil
  2320. "Non-nil means fast tag selection exits after first change.
  2321. When nil, you have to press RET to exit it.
  2322. During fast tag selection, you can toggle this flag with `C-c'.
  2323. This variable can also have the value `expert'. In this case, the window
  2324. displaying the tags menu is not even shown, until you press `C-c' again."
  2325. :group 'org-tags
  2326. :type '(choice
  2327. (const :tag "No" nil)
  2328. (const :tag "Yes" t)
  2329. (const :tag "Expert" expert)))
  2330. (defvar org-fast-tag-selection-include-todo nil
  2331. "Non-nil means fast tags selection interface will also offer TODO states.
  2332. This is an undocumented feature, you should not rely on it.")
  2333. (defcustom org-tags-column -77
  2334. "The column to which tags should be indented in a headline.
  2335. If this number is positive, it specifies the column. If it is negative,
  2336. it means that the tags should be flushright to that column. For example,
  2337. -80 works well for a normal 80 character screen.
  2338. When 0, place tags directly after headline text, with only one space in
  2339. between."
  2340. :group 'org-tags
  2341. :type 'integer)
  2342. (defcustom org-auto-align-tags t
  2343. "Non-nil keeps tags aligned when modifying headlines.
  2344. Some operations (i.e. demoting) change the length of a headline and
  2345. therefore shift the tags around. With this option turned on, after
  2346. each such operation the tags are again aligned to `org-tags-column'."
  2347. :group 'org-tags
  2348. :type 'boolean)
  2349. (defcustom org-use-tag-inheritance t
  2350. "Non-nil means tags in levels apply also for sublevels.
  2351. When nil, only the tags directly given in a specific line apply there.
  2352. This may also be a list of tags that should be inherited, or a regexp that
  2353. matches tags that should be inherited. Additional control is possible
  2354. with the variable `org-tags-exclude-from-inheritance' which gives an
  2355. explicit list of tags to be excluded from inheritance, even if the value of
  2356. `org-use-tag-inheritance' would select it for inheritance.
  2357. If this option is t, a match early-on in a tree can lead to a large
  2358. number of matches in the subtree when constructing the agenda or creating
  2359. a sparse tree. If you only want to see the first match in a tree during
  2360. a search, check out the variable `org-tags-match-list-sublevels'."
  2361. :group 'org-tags
  2362. :type '(choice
  2363. (const :tag "Not" nil)
  2364. (const :tag "Always" t)
  2365. (repeat :tag "Specific tags" (string :tag "Tag"))
  2366. (regexp :tag "Tags matched by regexp")))
  2367. (defcustom org-tags-exclude-from-inheritance nil
  2368. "List of tags that should never be inherited.
  2369. This is a way to exclude a few tags from inheritance. For way to do
  2370. the opposite, to actively allow inheritance for selected tags,
  2371. see the variable `org-use-tag-inheritance'."
  2372. :group 'org-tags
  2373. :type '(repeat (string :tag "Tag")))
  2374. (defun org-tag-inherit-p (tag)
  2375. "Check if TAG is one that should be inherited."
  2376. (cond
  2377. ((member tag org-tags-exclude-from-inheritance) nil)
  2378. ((eq org-use-tag-inheritance t) t)
  2379. ((not org-use-tag-inheritance) nil)
  2380. ((stringp org-use-tag-inheritance)
  2381. (string-match org-use-tag-inheritance tag))
  2382. ((listp org-use-tag-inheritance)
  2383. (member tag org-use-tag-inheritance))
  2384. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  2385. (defcustom org-tags-match-list-sublevels t
  2386. "Non-nil means list also sublevels of headlines matching a search.
  2387. This variable applies to tags/property searches, and also to stuck
  2388. projects because this search is based on a tags match as well.
  2389. When set to the symbol `indented', sublevels are indented with
  2390. leading dots.
  2391. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  2392. the sublevels of a headline matching a tag search often also match
  2393. the same search. Listing all of them can create very long lists.
  2394. Setting this variable to nil causes subtrees of a match to be skipped.
  2395. This variable is semi-obsolete and probably should always be true. It
  2396. is better to limit inheritance to certain tags using the variables
  2397. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  2398. :group 'org-tags
  2399. :type '(choice
  2400. (const :tag "No, don't list them" nil)
  2401. (const :tag "Yes, do list them" t)
  2402. (const :tag "List them, indented with leading dots" indented)))
  2403. (defcustom org-tags-sort-function nil
  2404. "When set, tags are sorted using this function as a comparator."
  2405. :group 'org-tags
  2406. :type '(choice
  2407. (const :tag "No sorting" nil)
  2408. (const :tag "Alphabetical" string-collate-lessp)
  2409. (const :tag "Reverse alphabetical" org-string-collate-greaterp)
  2410. (function :tag "Custom function" nil)))
  2411. (defvar org-tags-history nil
  2412. "History of minibuffer reads for tags.")
  2413. (defvar org-last-tags-completion-table nil
  2414. "The last used completion table for tags.")
  2415. (defvar org-after-tags-change-hook nil
  2416. "Hook that is run after the tags in a line have changed.")
  2417. (defgroup org-properties nil
  2418. "Options concerning properties in Org mode."
  2419. :tag "Org Properties"
  2420. :group 'org)
  2421. (defcustom org-property-format "%-10s %s"
  2422. "How property key/value pairs should be formatted by `indent-line'.
  2423. When `indent-line' hits a property definition, it will format the line
  2424. according to this format, mainly to make sure that the values are
  2425. lined-up with respect to each other."
  2426. :group 'org-properties
  2427. :type 'string)
  2428. (defcustom org-properties-postprocess-alist nil
  2429. "Alist of properties and functions to adjust inserted values.
  2430. Elements of this alist must be of the form
  2431. ([string] [function])
  2432. where [string] must be a property name and [function] must be a
  2433. lambda expression: this lambda expression must take one argument,
  2434. the value to adjust, and return the new value as a string.
  2435. For example, this element will allow the property \"Remaining\"
  2436. to be updated wrt the relation between the \"Effort\" property
  2437. and the clock summary:
  2438. ((\"Remaining\" (lambda(value)
  2439. (let ((clocksum (org-clock-sum-current-item))
  2440. (effort (org-duration-to-minutes
  2441. (org-entry-get (point) \"Effort\"))))
  2442. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  2443. :group 'org-properties
  2444. :version "24.1"
  2445. :type '(alist :key-type (string :tag "Property")
  2446. :value-type (function :tag "Function")))
  2447. (defcustom org-use-property-inheritance nil
  2448. "Non-nil means properties apply also for sublevels.
  2449. This setting is chiefly used during property searches. Turning it on can
  2450. cause significant overhead when doing a search, which is why it is not
  2451. on by default.
  2452. When nil, only the properties directly given in the current entry count.
  2453. When t, every property is inherited. The value may also be a list of
  2454. properties that should have inheritance, or a regular expression matching
  2455. properties that should be inherited.
  2456. However, note that some special properties use inheritance under special
  2457. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  2458. and the properties ending in \"_ALL\" when they are used as descriptor
  2459. for valid values of a property.
  2460. Note for programmers:
  2461. When querying an entry with `org-entry-get', you can control if inheritance
  2462. should be used. By default, `org-entry-get' looks only at the local
  2463. properties. You can request inheritance by setting the inherit argument
  2464. to t (to force inheritance) or to `selective' (to respect the setting
  2465. in this variable)."
  2466. :group 'org-properties
  2467. :type '(choice
  2468. (const :tag "Not" nil)
  2469. (const :tag "Always" t)
  2470. (repeat :tag "Specific properties" (string :tag "Property"))
  2471. (regexp :tag "Properties matched by regexp")))
  2472. (defun org-property-inherit-p (property)
  2473. "Return a non-nil value if PROPERTY should be inherited."
  2474. (cond
  2475. ((eq org-use-property-inheritance t) t)
  2476. ((not org-use-property-inheritance) nil)
  2477. ((stringp org-use-property-inheritance)
  2478. (string-match org-use-property-inheritance property))
  2479. ((listp org-use-property-inheritance)
  2480. (member-ignore-case property org-use-property-inheritance))
  2481. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  2482. (defcustom org-property-separators nil
  2483. "An alist to control how properties are combined.
  2484. The car of each item should be either a list of property names or
  2485. a regular expression, while the cdr should be the separator to
  2486. use when combining that property.
  2487. If an alist item cannot be found that matches a given property, a
  2488. single space will be used as the separator."
  2489. :group 'org-properties
  2490. :type '(alist :key-type (choice (repeat :tag "Properties" string)
  2491. (string :tag "Regular Expression"))
  2492. :value-type (restricted-sexp :tag "Separator"
  2493. :match-alternatives (stringp)
  2494. :value " ")))
  2495. (defun org--property-get-separator (property)
  2496. "Get the separator to use for combining PROPERTY."
  2497. (or
  2498. (catch 'separator
  2499. (dolist (spec org-property-separators)
  2500. (if (listp (car spec))
  2501. (if (member property (car spec))
  2502. (throw 'separator (cdr spec)))
  2503. (if (string-match-p (car spec) property)
  2504. (throw 'separator (cdr spec))))))
  2505. " "))
  2506. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  2507. "The default column format, if no other format has been defined.
  2508. This variable can be set on the per-file basis by inserting a line
  2509. #+COLUMNS: %25ITEM ....."
  2510. :group 'org-properties
  2511. :type 'string)
  2512. (defcustom org-columns-default-format-for-agenda nil
  2513. "The default column format in an agenda buffer.
  2514. This will be used for column view in the agenda unless a format has
  2515. been set by adding `org-overriding-columns-format' to the local
  2516. settings list of a custom agenda view. When nil, the columns format
  2517. for the first item in the agenda list will be used, or as a fall-back,
  2518. `org-columns-default-format'."
  2519. :group 'org-properties
  2520. :type '(choice
  2521. (const :tag "No default" nil)
  2522. (string :tag "Format string")))
  2523. (defcustom org-columns-ellipses ".."
  2524. "The ellipses to be used when a field in column view is truncated.
  2525. When this is the empty string, as many characters as possible are shown,
  2526. but then there will be no visual indication that the field has been truncated.
  2527. When this is a string of length N, the last N characters of a truncated
  2528. field are replaced by this string. If the column is narrower than the
  2529. ellipses string, only part of the ellipses string will be shown."
  2530. :group 'org-properties
  2531. :type 'string)
  2532. (defconst org-global-properties-fixed
  2533. '(("VISIBILITY_ALL" . "folded children content all")
  2534. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  2535. "List of property/value pairs that can be inherited by any entry.
  2536. These are fixed values, for the preset properties. The user variable
  2537. that can be used to add to this list is `org-global-properties'.
  2538. The entries in this list are cons cells where the car is a property
  2539. name and cdr is a string with the value. If the value represents
  2540. multiple items like an \"_ALL\" property, separate the items by
  2541. spaces.")
  2542. (defcustom org-global-properties nil
  2543. "List of property/value pairs that can be inherited by any entry.
  2544. This list will be combined with the constant `org-global-properties-fixed'.
  2545. The entries in this list are cons cells where the car is a property
  2546. name and cdr is a string with the value.
  2547. Buffer local properties are added either by a document property drawer
  2548. :PROPERTIES:
  2549. :NAME: VALUE
  2550. :END:
  2551. or by adding lines like
  2552. #+PROPERTY: NAME VALUE"
  2553. :group 'org-properties
  2554. :type '(repeat
  2555. (cons (string :tag "Property")
  2556. (string :tag "Value"))))
  2557. (defvar-local org-keyword-properties nil
  2558. "List of property/value pairs inherited by any entry.
  2559. Valid for the current buffer. This variable is populated from
  2560. PROPERTY keywords.
  2561. Note that properties are defined also in property drawers.
  2562. Properties defined there take precedence over properties defined
  2563. as keywords.")
  2564. (defgroup org-agenda nil
  2565. "Options concerning agenda views in Org mode."
  2566. :tag "Org Agenda"
  2567. :group 'org)
  2568. (defvar-local org-category nil
  2569. "Variable used by Org files to set a category for agenda display.
  2570. There are multiple ways to set the category. One way is to set
  2571. it in the document property drawer. For example:
  2572. :PROPERTIES:
  2573. :CATEGORY: ELisp
  2574. :END:
  2575. Other ways to define it is as an Emacs file variable, for example
  2576. # -*- mode: org; org-category: \"ELisp\"
  2577. or for the file to contain a special line:
  2578. #+CATEGORY: ELisp
  2579. If the file does not specify a category, then file's base name
  2580. is used instead.")
  2581. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  2582. (defcustom org-agenda-files nil
  2583. "The files to be used for agenda display.
  2584. If an entry is a directory, all files in that directory that are matched
  2585. by `org-agenda-file-regexp' will be part of the file list.
  2586. If the value of the variable is not a list but a single file name, then
  2587. the list of agenda files is actually stored and maintained in that file,
  2588. one agenda file per line. In this file paths can be given relative to
  2589. `org-directory'. Tilde expansion and environment variable substitution
  2590. are also made.
  2591. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  2592. and removed with `\\[org-remove-file]'."
  2593. :group 'org-agenda
  2594. :type '(choice
  2595. (repeat :tag "List of files and directories" file)
  2596. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  2597. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  2598. "Regular expression to match files for `org-agenda-files'.
  2599. If any element in the list in that variable contains a directory instead
  2600. of a normal file, all files in that directory that are matched by this
  2601. regular expression will be included."
  2602. :group 'org-agenda
  2603. :type 'regexp)
  2604. (defvaralias 'org-agenda-multi-occur-extra-files
  2605. 'org-agenda-text-search-extra-files)
  2606. (defcustom org-agenda-text-search-extra-files nil
  2607. "List of extra files to be searched by text search commands.
  2608. These files will be searched in addition to the agenda files by the
  2609. commands `org-search-view' (`\\[org-agenda] s') \
  2610. and `org-occur-in-agenda-files'.
  2611. Note that these files will only be searched for text search commands,
  2612. not for the other agenda views like todo lists, tag searches or the weekly
  2613. agenda. This variable is intended to list notes and possibly archive files
  2614. that should also be searched by these two commands.
  2615. In fact, if the first element in the list is the symbol `agenda-archives',
  2616. then all archive files of all agenda files will be added to the search
  2617. scope."
  2618. :group 'org-agenda
  2619. :type '(set :greedy t
  2620. (const :tag "Agenda Archives" agenda-archives)
  2621. (repeat :inline t (file))))
  2622. (defcustom org-agenda-skip-unavailable-files nil
  2623. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  2624. A nil value means to remove them, after a query, from the list."
  2625. :group 'org-agenda
  2626. :type 'boolean)
  2627. (defgroup org-latex nil
  2628. "Options for embedding LaTeX code into Org mode."
  2629. :tag "Org LaTeX"
  2630. :group 'org)
  2631. (defcustom org-format-latex-options
  2632. '(:foreground default :background default :scale 1.0
  2633. :html-foreground "Black" :html-background "Transparent"
  2634. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  2635. "Options for creating images from LaTeX fragments.
  2636. This is a property list with the following properties:
  2637. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  2638. `default' means use the foreground of the default face.
  2639. `auto' means use the foreground from the text face.
  2640. :background the background color, or \"Transparent\".
  2641. `default' means use the background of the default face.
  2642. `auto' means use the background from the text face.
  2643. :scale a scaling factor for the size of the images, to get more pixels
  2644. :html-foreground, :html-background, :html-scale
  2645. the same numbers for HTML export.
  2646. :matchers a list indicating which matchers should be used to
  2647. find LaTeX fragments. Valid members of this list are:
  2648. \"begin\" find environments
  2649. \"$1\" find single characters surrounded by $.$
  2650. \"$\" find math expressions surrounded by $...$
  2651. \"$$\" find math expressions surrounded by $$....$$
  2652. \"\\(\" find math expressions surrounded by \\(...\\)
  2653. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  2654. :group 'org-latex
  2655. :type 'plist)
  2656. (defcustom org-format-latex-signal-error t
  2657. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  2658. When nil, just push out a message."
  2659. :group 'org-latex
  2660. :version "24.1"
  2661. :type 'boolean)
  2662. (defcustom org-latex-to-mathml-jar-file nil
  2663. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  2664. Use this to specify additional executable file say a jar file.
  2665. When using MathToWeb as the converter, specify the full-path to
  2666. your mathtoweb.jar file."
  2667. :group 'org-latex
  2668. :version "24.1"
  2669. :type '(choice
  2670. (const :tag "None" nil)
  2671. (file :tag "JAR file" :must-match t)))
  2672. (defcustom org-latex-to-mathml-convert-command nil
  2673. "Command to convert LaTeX fragments to MathML.
  2674. Replace format-specifiers in the command as noted below and use
  2675. `shell-command' to convert LaTeX to MathML.
  2676. %j: Executable file in fully expanded form as specified by
  2677. `org-latex-to-mathml-jar-file'.
  2678. %I: Input LaTeX file in fully expanded form.
  2679. %i: The latex fragment to be converted.
  2680. %o: Output MathML file.
  2681. This command is used by `org-create-math-formula'.
  2682. When using MathToWeb as the converter, set this option to
  2683. \"java -jar %j -unicode -force -df %o %I\".
  2684. When using LaTeXML set this option to
  2685. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  2686. :group 'org-latex
  2687. :version "24.1"
  2688. :type '(choice
  2689. (const :tag "None" nil)
  2690. (string :tag "\nShell command")))
  2691. (defcustom org-latex-to-html-convert-command nil
  2692. "Command to convert LaTeX fragments to HTML.
  2693. This command is very open-ended: the output of the command will
  2694. directly replace the LaTeX fragment in the resulting HTML.
  2695. Replace format-specifiers in the command as noted below and use
  2696. `shell-command' to convert LaTeX to HTML.
  2697. %i: The LaTeX fragment to be converted.
  2698. For example, this could be used with LaTeXML as
  2699. \"latexmlc \\='literal:%i\\=' --profile=math --preload=siunitx.sty 2>/dev/null\"."
  2700. :group 'org-latex
  2701. :package-version '(Org . "9.4")
  2702. :type '(choice
  2703. (const :tag "None" nil)
  2704. (string :tag "Shell command")))
  2705. (defcustom org-preview-latex-default-process 'dvipng
  2706. "The default process to convert LaTeX fragments to image files.
  2707. All available processes and theirs documents can be found in
  2708. `org-preview-latex-process-alist', which see."
  2709. :group 'org-latex
  2710. :version "26.1"
  2711. :package-version '(Org . "9.0")
  2712. :type 'symbol)
  2713. (defcustom org-preview-latex-process-alist
  2714. '((dvipng
  2715. :programs ("latex" "dvipng")
  2716. :description "dvi > png"
  2717. :message "you need to install the programs: latex and dvipng."
  2718. :image-input-type "dvi"
  2719. :image-output-type "png"
  2720. :image-size-adjust (1.0 . 1.0)
  2721. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2722. :image-converter ("dvipng -D %D -T tight -o %O %f")
  2723. :transparent-image-converter
  2724. ("dvipng -D %D -T tight -bg Transparent -o %O %f"))
  2725. (dvisvgm
  2726. :programs ("latex" "dvisvgm")
  2727. :description "dvi > svg"
  2728. :message "you need to install the programs: latex and dvisvgm."
  2729. :image-input-type "dvi"
  2730. :image-output-type "svg"
  2731. :image-size-adjust (1.7 . 1.5)
  2732. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2733. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  2734. (imagemagick
  2735. :programs ("latex" "convert")
  2736. :description "pdf > png"
  2737. :message "you need to install the programs: latex and imagemagick."
  2738. :image-input-type "pdf"
  2739. :image-output-type "png"
  2740. :image-size-adjust (1.0 . 1.0)
  2741. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  2742. :image-converter
  2743. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  2744. "Definitions of external processes for LaTeX previewing.
  2745. Org mode can use some external commands to generate TeX snippet's images for
  2746. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  2747. `org-create-formula-image' how to call them.
  2748. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  2749. PROPERTIES accepts the following attributes:
  2750. :programs list of strings, required programs.
  2751. :description string, describe the process.
  2752. :message string, message it when required programs cannot be found.
  2753. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  2754. :image-output-type string, output file type of image converter (e.g., \"png\").
  2755. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  2756. image size showed in buffer and the cdr element is for
  2757. HTML file. This option is only useful for process
  2758. developers, users should use variable
  2759. `org-format-latex-options' instead.
  2760. :post-clean list of strings, files matched are to be cleaned up once
  2761. the image is generated. When nil, the files with \".dvi\",
  2762. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  2763. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  2764. be cleaned up.
  2765. :latex-header list of strings, the LaTeX header of the snippet file.
  2766. When nil, the fallback value is used instead, which is
  2767. controlled by `org-format-latex-header',
  2768. `org-latex-default-packages-alist' and
  2769. `org-latex-packages-alist', which see.
  2770. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  2771. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  2772. replaced with values defined below.
  2773. :image-converter list of image converter commands strings. Each of them is
  2774. given to the shell and supports any of the following
  2775. place-holders defined below.
  2776. If set, :transparent-image-converter is used instead of :image-converter to
  2777. convert an image when the background color is nil or \"Transparent\".
  2778. Place-holders used by `:image-converter' and `:latex-compiler':
  2779. %f input file name
  2780. %b base name of input file
  2781. %o base directory of input file
  2782. %O absolute output file name
  2783. Place-holders only used by `:image-converter':
  2784. %D dpi, which is used to adjust image size by some processing commands.
  2785. %S the image size scale ratio, which is used to adjust image size by some
  2786. processing commands."
  2787. :group 'org-latex
  2788. :version "26.1"
  2789. :package-version '(Org . "9.0")
  2790. :type '(alist :tag "LaTeX to image backends"
  2791. :value-type (plist)))
  2792. (defcustom org-preview-latex-image-directory "ltximg/"
  2793. "Path to store latex preview images.
  2794. A relative path here creates many directories relative to the
  2795. processed Org files paths. An absolute path puts all preview
  2796. images at the same place."
  2797. :group 'org-latex
  2798. :version "26.1"
  2799. :package-version '(Org . "9.0")
  2800. :type 'string)
  2801. (defun org-format-latex-mathml-available-p ()
  2802. "Return t if `org-latex-to-mathml-convert-command' is usable."
  2803. (save-match-data
  2804. (when (and (boundp 'org-latex-to-mathml-convert-command)
  2805. org-latex-to-mathml-convert-command)
  2806. (let ((executable (car (split-string
  2807. org-latex-to-mathml-convert-command))))
  2808. (when (executable-find executable)
  2809. (if (string-match
  2810. "%j" org-latex-to-mathml-convert-command)
  2811. (file-readable-p org-latex-to-mathml-jar-file)
  2812. t))))))
  2813. (defcustom org-format-latex-header "\\documentclass{article}
  2814. \\usepackage[usenames]{color}
  2815. \[DEFAULT-PACKAGES]
  2816. \[PACKAGES]
  2817. \\pagestyle{empty} % do not remove
  2818. % The settings below are copied from fullpage.sty
  2819. \\setlength{\\textwidth}{\\paperwidth}
  2820. \\addtolength{\\textwidth}{-3cm}
  2821. \\setlength{\\oddsidemargin}{1.5cm}
  2822. \\addtolength{\\oddsidemargin}{-2.54cm}
  2823. \\setlength{\\evensidemargin}{\\oddsidemargin}
  2824. \\setlength{\\textheight}{\\paperheight}
  2825. \\addtolength{\\textheight}{-\\headheight}
  2826. \\addtolength{\\textheight}{-\\headsep}
  2827. \\addtolength{\\textheight}{-\\footskip}
  2828. \\addtolength{\\textheight}{-3cm}
  2829. \\setlength{\\topmargin}{1.5cm}
  2830. \\addtolength{\\topmargin}{-2.54cm}"
  2831. "The document header used for processing LaTeX fragments.
  2832. It is imperative that this header make sure that no page number
  2833. appears on the page. The package defined in the variables
  2834. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  2835. will either replace the placeholder \"[PACKAGES]\" in this
  2836. header, or they will be appended."
  2837. :group 'org-latex
  2838. :type 'string)
  2839. (defun org-set-packages-alist (var val)
  2840. "Set the packages alist and make sure it has 3 elements per entry."
  2841. (set-default-toplevel-value var (mapcar (lambda (x)
  2842. (if (and (consp x) (= (length x) 2))
  2843. (list (car x) (nth 1 x) t)
  2844. x))
  2845. val)))
  2846. (defun org-get-packages-alist (var)
  2847. "Get the packages alist and make sure it has 3 elements per entry."
  2848. (mapcar (lambda (x)
  2849. (if (and (consp x) (= (length x) 2))
  2850. (list (car x) (nth 1 x) t)
  2851. x))
  2852. (default-value var)))
  2853. (defcustom org-latex-default-packages-alist
  2854. '(("AUTO" "inputenc" t ("pdflatex"))
  2855. ("T1" "fontenc" t ("pdflatex"))
  2856. ("" "graphicx" t)
  2857. ("" "longtable" nil)
  2858. ("" "wrapfig" nil)
  2859. ("" "rotating" nil)
  2860. ("normalem" "ulem" t)
  2861. ("" "amsmath" t)
  2862. ("" "amssymb" t)
  2863. ("" "capt-of" nil)
  2864. ("" "hyperref" nil))
  2865. "Alist of default packages to be inserted in the header.
  2866. Change this only if one of the packages here causes an
  2867. incompatibility with another package you are using.
  2868. The packages in this list are needed by one part or another of
  2869. Org mode to function properly:
  2870. - inputenc, fontenc: for basic font and character selection
  2871. - graphicx: for including images
  2872. - longtable: For multipage tables
  2873. - wrapfig: for figure placement
  2874. - rotating: for sideways figures and tables
  2875. - ulem: for underline and strike-through
  2876. - amsmath: for subscript and superscript and math environments
  2877. - amssymb: for various symbols used for interpreting the entities
  2878. in `org-entities'. You can skip some of this package if you don't
  2879. use any of the symbols.
  2880. - capt-of: for captions outside of floats
  2881. - hyperref: for cross references
  2882. Therefore you should not modify this variable unless you know
  2883. what you are doing. The one reason to change it anyway is that
  2884. you might be loading some other package that conflicts with one
  2885. of the default packages. Each element is either a cell or
  2886. a string.
  2887. A cell is of the format
  2888. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  2889. If SNIPPET-FLAG is non-nil, the package also needs to be included
  2890. when compiling LaTeX snippets into images for inclusion into
  2891. non-LaTeX output.
  2892. COMPILERS is a list of compilers that should include the package,
  2893. see `org-latex-compiler'. If the document compiler is not in the
  2894. list, and the list is non-nil, the package will not be inserted
  2895. in the final document.
  2896. A string will be inserted as-is in the header of the document."
  2897. :group 'org-latex
  2898. :group 'org-export-latex
  2899. :set 'org-set-packages-alist
  2900. :get 'org-get-packages-alist
  2901. :version "26.1"
  2902. :package-version '(Org . "8.3")
  2903. :type '(repeat
  2904. (choice
  2905. (list :tag "options/package pair"
  2906. (string :tag "options")
  2907. (string :tag "package")
  2908. (boolean :tag "Snippet")
  2909. (choice
  2910. (const :tag "For all compilers" nil)
  2911. (repeat :tag "Allowed compiler" string)))
  2912. (string :tag "A line of LaTeX"))))
  2913. (defcustom org-latex-packages-alist nil
  2914. "Alist of packages to be inserted in every LaTeX header.
  2915. These will be inserted after `org-latex-default-packages-alist'.
  2916. Each element is either a cell or a string.
  2917. A cell is of the format:
  2918. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  2919. SNIPPET-FLAG, when non-nil, indicates that this package is also
  2920. needed when turning LaTeX snippets into images for inclusion into
  2921. non-LaTeX output.
  2922. COMPILERS is a list of compilers that should include the package,
  2923. see `org-latex-compiler'. If the document compiler is not in the
  2924. list, and the list is non-nil, the package will not be inserted
  2925. in the final document.
  2926. A string will be inserted as-is in the header of the document.
  2927. Make sure that you only list packages here which:
  2928. - you want in every file;
  2929. - do not conflict with the setup in `org-format-latex-header';
  2930. - do not conflict with the default packages in
  2931. `org-latex-default-packages-alist'."
  2932. :group 'org-latex
  2933. :group 'org-export-latex
  2934. :set 'org-set-packages-alist
  2935. :get 'org-get-packages-alist
  2936. :type '(repeat
  2937. (choice
  2938. (list :tag "options/package pair"
  2939. (string :tag "options")
  2940. (string :tag "package")
  2941. (boolean :tag "Snippet"))
  2942. (string :tag "A line of LaTeX"))))
  2943. (defgroup org-appearance nil
  2944. "Settings for Org mode appearance."
  2945. :tag "Org Appearance"
  2946. :group 'org)
  2947. (defcustom org-level-color-stars-only nil
  2948. "Non-nil means fontify only the stars in each headline.
  2949. When nil, the entire headline is fontified.
  2950. Changing it requires restart of `font-lock-mode' to become effective
  2951. also in regions already fontified."
  2952. :group 'org-appearance
  2953. :type 'boolean)
  2954. (defcustom org-hide-leading-stars nil
  2955. "Non-nil means hide the first N-1 stars in a headline.
  2956. This works by using the face `org-hide' for these stars. This
  2957. face is white for a light background, and black for a dark
  2958. background. You may have to customize the face `org-hide' to
  2959. make this work.
  2960. Changing it requires restart of `font-lock-mode' to become effective
  2961. also in regions already fontified.
  2962. You may also set this on a per-file basis by adding one of the following
  2963. lines to the buffer:
  2964. #+STARTUP: hidestars
  2965. #+STARTUP: showstars"
  2966. :group 'org-appearance
  2967. :type 'boolean)
  2968. (defcustom org-hidden-keywords nil
  2969. "List of symbols corresponding to keywords to be hidden in the Org buffer.
  2970. For example, a value (title) for this list makes the document's title
  2971. appear in the buffer without the initial \"#+TITLE:\" part."
  2972. :group 'org-appearance
  2973. :package-version '(Org . "9.5")
  2974. :type '(set (const :tag "#+AUTHOR" author)
  2975. (const :tag "#+DATE" date)
  2976. (const :tag "#+EMAIL" email)
  2977. (const :tag "#+SUBTITLE" subtitle)
  2978. (const :tag "#+TITLE" title)))
  2979. (defcustom org-custom-properties nil
  2980. "List of properties (as strings) with a special meaning.
  2981. The default use of these custom properties is to let the user
  2982. hide them with `org-toggle-custom-properties-visibility'."
  2983. :group 'org-properties
  2984. :group 'org-appearance
  2985. :version "24.3"
  2986. :type '(repeat (string :tag "Property Name")))
  2987. (defcustom org-fontify-todo-headline nil
  2988. "Non-nil means change the face of a headline if it is marked as TODO.
  2989. Normally, only the TODO/DONE keyword indicates the state of a headline.
  2990. When this is non-nil, the headline after the keyword is set to the
  2991. `org-headline-todo' as an additional indication."
  2992. :group 'org-appearance
  2993. :package-version '(Org . "9.4")
  2994. :type 'boolean
  2995. :safe #'booleanp)
  2996. (defcustom org-fontify-done-headline t
  2997. "Non-nil means change the face of a headline if it is marked DONE.
  2998. Normally, only the TODO/DONE keyword indicates the state of a headline.
  2999. When this is non-nil, the headline after the keyword is set to the
  3000. `org-headline-done' as an additional indication."
  3001. :group 'org-appearance
  3002. :package-version '(Org . "9.4")
  3003. :type 'boolean)
  3004. (defcustom org-fontify-emphasized-text t
  3005. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3006. Changing this variable requires a restart of Emacs to take effect."
  3007. :group 'org-appearance
  3008. :type 'boolean)
  3009. (defcustom org-fontify-whole-heading-line nil
  3010. "Non-nil means fontify the whole line for headings.
  3011. This is useful when setting a background color for the
  3012. org-level-* faces."
  3013. :group 'org-appearance
  3014. :type 'boolean)
  3015. (defcustom org-fontify-whole-block-delimiter-line t
  3016. "Non-nil means fontify the whole line for begin/end lines of blocks.
  3017. This is useful when setting a background color for the
  3018. org-block-begin-line and org-block-end-line faces."
  3019. :group 'org-appearance
  3020. :type 'boolean)
  3021. (defcustom org-highlight-latex-and-related nil
  3022. "Non-nil means highlight LaTeX related syntax in the buffer.
  3023. When non-nil, the value should be a list containing any of the
  3024. following symbols:
  3025. `native' Highlight LaTeX snippets and environments natively.
  3026. `latex' Highlight LaTeX snippets and environments.
  3027. `script' Highlight subscript and superscript.
  3028. `entities' Highlight entities."
  3029. :group 'org-appearance
  3030. :version "24.4"
  3031. :package-version '(Org . "8.0")
  3032. :type '(choice
  3033. (const :tag "No highlighting" nil)
  3034. (set :greedy t :tag "Highlight"
  3035. (const :tag "LaTeX snippets and environments (native)" native)
  3036. (const :tag "LaTeX snippets and environments" latex)
  3037. (const :tag "Subscript and superscript" script)
  3038. (const :tag "Entities" entities))))
  3039. (defcustom org-hide-emphasis-markers nil
  3040. "Non-nil mean font-lock should hide the emphasis marker characters."
  3041. :group 'org-appearance
  3042. :type 'boolean
  3043. :safe #'booleanp)
  3044. (defcustom org-hide-macro-markers nil
  3045. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3046. :group 'org-appearance
  3047. :type 'boolean)
  3048. (defcustom org-pretty-entities nil
  3049. "Non-nil means show entities as UTF8 characters.
  3050. When nil, the \\name form remains in the buffer."
  3051. :group 'org-appearance
  3052. :version "24.1"
  3053. :type 'boolean)
  3054. (defcustom org-pretty-entities-include-sub-superscripts t
  3055. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3056. :group 'org-appearance
  3057. :version "24.1"
  3058. :type 'boolean)
  3059. (defvar org-emph-re nil
  3060. "Regular expression for matching emphasis.
  3061. After a match, the match groups contain these elements:
  3062. 0 The match of the full regular expression, including the characters
  3063. before and after the proper match
  3064. 1 The character before the proper match, or empty at beginning of line
  3065. 2 The proper match, including the leading and trailing markers
  3066. 3 The leading marker like * or /, indicating the type of highlighting
  3067. 4 The text between the emphasis markers, not including the markers
  3068. 5 The character after the match, empty at the end of a line")
  3069. (defvar org-verbatim-re nil
  3070. "Regular expression for matching verbatim text.")
  3071. (defvar org-emphasis-regexp-components) ; defined just below
  3072. (defvar org-emphasis-alist) ; defined just below
  3073. (defun org-set-emph-re (var val)
  3074. "Set variable and compute the emphasis regular expression."
  3075. (set-default-toplevel-value var val)
  3076. (when (and (boundp 'org-emphasis-alist)
  3077. (boundp 'org-emphasis-regexp-components)
  3078. org-emphasis-alist org-emphasis-regexp-components)
  3079. (pcase-let*
  3080. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3081. (body (if (<= nl 0) body
  3082. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3083. (template
  3084. (format (concat "\\([%s]\\|^\\)" ;before markers
  3085. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3086. "\\([%s]\\|$\\)") ;after markers
  3087. pre border border body border post)))
  3088. (setq org-emph-re (format template "*/_+"))
  3089. (setq org-verbatim-re (format template "=~")))))
  3090. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3091. ;; set this option proved cumbersome. See this message/thread:
  3092. ;; https://orgmode.org/list/B72CDC2B-72F6-43A8-AC70-E6E6295766EC@gmail.com
  3093. (defvar org-emphasis-regexp-components
  3094. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3095. "Components used to build the regular expression for emphasis.
  3096. This is a list with five entries. Terminology: In an emphasis string
  3097. like \" *strong word* \", we call the initial space PREMATCH, the final
  3098. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3099. and \"trong wor\" is the body. The different components in this variable
  3100. specify what is allowed/forbidden in each part:
  3101. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3102. post Chars allowed as postmatch. End of line will be allowed too.
  3103. border The chars *forbidden* as border characters.
  3104. body-regexp A regexp like \".\" to match a body character. Don't use
  3105. non-shy groups here, and don't allow newline here.
  3106. newline The maximum number of newlines allowed in an emphasis exp.
  3107. You need to reload Org or to restart Emacs after setting this.")
  3108. (defcustom org-emphasis-alist
  3109. '(("*" bold)
  3110. ("/" italic)
  3111. ("_" underline)
  3112. ("=" org-verbatim verbatim)
  3113. ("~" org-code verbatim)
  3114. ("+" (:strike-through t)))
  3115. "Alist of characters and faces to emphasize text.
  3116. Text starting and ending with a special character will be emphasized,
  3117. for example *bold*, _underlined_ and /italic/. This variable sets the
  3118. marker characters and the face to be used by font-lock for highlighting
  3119. in Org buffers.
  3120. You need to reload Org or to restart Emacs after customizing this."
  3121. :group 'org-appearance
  3122. :set 'org-set-emph-re
  3123. :version "24.4"
  3124. :package-version '(Org . "8.0")
  3125. :type '(repeat
  3126. (list
  3127. (string :tag "Marker character")
  3128. (choice
  3129. (face :tag "Font-lock-face")
  3130. (plist :tag "Face property list"))
  3131. (option (const verbatim)))))
  3132. (defvar org-protecting-blocks '("src" "example" "export")
  3133. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3134. This is needed for font-lock setup.")
  3135. ;;; Functions and variables from their packages
  3136. ;; Declared here to avoid compiler warnings
  3137. (defvar mark-active)
  3138. ;; Various packages
  3139. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3140. (declare-function calendar-forward-day "cal-move" (arg))
  3141. (declare-function calendar-goto-date "cal-move" (date))
  3142. (declare-function calendar-goto-today "cal-move" ())
  3143. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3144. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3145. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3146. (declare-function cdlatex-tab "ext:cdlatex" ())
  3147. (declare-function dired-get-filename
  3148. "dired"
  3149. (&optional localp no-error-if-not-filep))
  3150. (declare-function org-agenda-change-all-lines
  3151. "org-agenda"
  3152. (newhead hdmarker &optional fixface just-this))
  3153. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3154. "org-agenda"
  3155. (&optional end))
  3156. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3157. (declare-function org-agenda-format-item
  3158. "org-agenda"
  3159. (extra txt &optional level category tags dotime
  3160. remove-re habitp))
  3161. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3162. (declare-function org-agenda-save-markers-for-cut-and-paste
  3163. "org-agenda"
  3164. (beg end))
  3165. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3166. (declare-function org-agenda-skip "org-agenda" (&optional element))
  3167. (declare-function org-attach-expand "org-attach" (file))
  3168. (declare-function org-attach-reveal "org-attach" ())
  3169. (declare-function org-attach-reveal-in-emacs "org-attach" ())
  3170. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3171. (declare-function org-indent-mode "org-indent" (&optional arg))
  3172. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3173. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3174. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3175. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3176. (declare-function parse-time-string "parse-time" (string))
  3177. (defvar align-mode-rules-list)
  3178. (defvar calc-embedded-close-formula)
  3179. (defvar calc-embedded-open-formula)
  3180. (defvar calc-embedded-open-mode)
  3181. (defvar font-lock-unfontify-region-function)
  3182. (defvar org-agenda-tags-todo-honor-ignore-options)
  3183. (defvar remember-data-file)
  3184. (defvar texmathp-why)
  3185. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3186. (declare-function org-clock-update-mode-line "org-clock" (&optional refresh))
  3187. (declare-function org-resolve-clocks "org-clock"
  3188. (&optional also-non-dangling-p prompt last-valid))
  3189. (defvar org-clock-start-time)
  3190. (defvar org-clock-marker (make-marker)
  3191. "Marker recording the last clock-in.")
  3192. (defvar org-clock-hd-marker (make-marker)
  3193. "Marker recording the last clock-in, but the headline position.")
  3194. (defvar org-clock-heading ""
  3195. "The heading of the current clock entry.")
  3196. (defun org-clocking-buffer ()
  3197. "Return the buffer where the clock is currently running.
  3198. Return nil if no clock is running."
  3199. (marker-buffer org-clock-marker))
  3200. (defalias 'org-clock-is-active #'org-clocking-buffer)
  3201. (defun org-check-running-clock ()
  3202. "Check if the current buffer contains the running clock.
  3203. If yes, offer to stop it and to save the buffer with the changes."
  3204. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3205. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3206. (buffer-name))))
  3207. (org-clock-out)
  3208. (when (y-or-n-p "Save changed buffer?")
  3209. (save-buffer))))
  3210. (defun org-clocktable-try-shift (dir n)
  3211. "Check if this line starts a clock table, if yes, shift the time block."
  3212. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3213. (org-clocktable-shift dir n)))
  3214. ;;;###autoload
  3215. (defun org-clock-persistence-insinuate ()
  3216. "Set up hooks for clock persistence."
  3217. (require 'org-clock)
  3218. (add-hook 'org-mode-hook 'org-clock-load)
  3219. (add-hook 'kill-emacs-hook 'org-clock-save))
  3220. (defun org-clock-auto-clockout-insinuate ()
  3221. "Set up hook for auto clocking out when Emacs is idle.
  3222. See `org-clock-auto-clockout-timer'.
  3223. This function is meant to be added to the user configuration."
  3224. (require 'org-clock)
  3225. (add-hook 'org-clock-in-hook #'org-clock-auto-clockout t))
  3226. (defgroup org-archive nil
  3227. "Options concerning archiving in Org mode."
  3228. :tag "Org Archive"
  3229. :group 'org-structure)
  3230. (defcustom org-archive-location "%s_archive::"
  3231. "The location where subtrees should be archived.
  3232. The value of this variable is a string, consisting of two parts,
  3233. separated by a double-colon. The first part is a filename and
  3234. the second part is a headline.
  3235. When the filename is omitted, archiving happens in the same file.
  3236. %s in the filename will be replaced by the current file
  3237. name (without the directory part). Archiving to a different file
  3238. is useful to keep archived entries from contributing to the
  3239. Org Agenda.
  3240. The archived entries will be filed as subtrees of the specified
  3241. headline. When the headline is omitted, the subtrees are simply
  3242. filed away at the end of the file, as top-level entries. Also in
  3243. the heading you can use %s to represent the file name, this can be
  3244. useful when using the same archive for a number of different files.
  3245. Here are a few examples:
  3246. \"%s_archive::\"
  3247. If the current file is Projects.org, archive in file
  3248. Projects.org_archive, as top-level trees. This is the default.
  3249. \"::* Archived Tasks\"
  3250. Archive in the current file, under the top-level headline
  3251. \"* Archived Tasks\".
  3252. \"~/org/archive.org::\"
  3253. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3254. \"~/org/archive.org::* From %s\"
  3255. Archive in file ~/org/archive.org (absolute path), under headlines
  3256. \"From FILENAME\" where file name is the current file name.
  3257. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3258. The \"datetree/\" string is special, signifying to archive
  3259. items to the datetree. Items are placed in either the CLOSED
  3260. date of the item, or the current date if there is no CLOSED date.
  3261. The heading will be a subentry to the current date. There doesn't
  3262. need to be a heading, but there always needs to be a slash after
  3263. datetree. For example, to store archived items directly in the
  3264. datetree, use \"~/org/datetree.org::datetree/\".
  3265. \"basement::** Finished Tasks\"
  3266. Archive in file ./basement (relative path), as level 3 trees
  3267. below the level 2 heading \"** Finished Tasks\".
  3268. You may define it locally by setting an ARCHIVE property. If
  3269. such a property is found in the file or in an entry, and anywhere
  3270. up the hierarchy, it will be used.
  3271. You can also set it for the whole file using the keyword-syntax:
  3272. #+ARCHIVE: basement::** Finished Tasks"
  3273. :group 'org-archive
  3274. :type 'string)
  3275. (defcustom org-agenda-skip-archived-trees t
  3276. "Non-nil means the agenda will skip any items located in archived trees.
  3277. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3278. variable is no longer recommended, you should leave it at the value t.
  3279. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3280. :group 'org-archive
  3281. :group 'org-agenda-skip
  3282. :type 'boolean)
  3283. (defcustom org-columns-skip-archived-trees t
  3284. "Non-nil means ignore archived trees when creating column view."
  3285. :group 'org-archive
  3286. :group 'org-properties
  3287. :type 'boolean)
  3288. (defcustom org-sparse-tree-open-archived-trees nil
  3289. "Non-nil means sparse tree construction shows matches in archived trees.
  3290. When nil, matches in these trees are highlighted, but the trees are kept in
  3291. collapsed state."
  3292. :group 'org-archive
  3293. :group 'org-sparse-trees
  3294. :type 'boolean)
  3295. (defcustom org-sparse-tree-default-date-type nil
  3296. "The default date type when building a sparse tree.
  3297. When this is nil, a date is a scheduled or a deadline timestamp.
  3298. Otherwise, these types are allowed:
  3299. all: all timestamps
  3300. active: only active timestamps (<...>)
  3301. inactive: only inactive timestamps ([...])
  3302. scheduled: only scheduled timestamps
  3303. deadline: only deadline timestamps"
  3304. :type '(choice (const :tag "Scheduled or deadline" nil)
  3305. (const :tag "All timestamps" all)
  3306. (const :tag "Only active timestamps" active)
  3307. (const :tag "Only inactive timestamps" inactive)
  3308. (const :tag "Only scheduled timestamps" scheduled)
  3309. (const :tag "Only deadline timestamps" deadline)
  3310. (const :tag "Only closed timestamps" closed))
  3311. :version "26.1"
  3312. :package-version '(Org . "8.3")
  3313. :group 'org-sparse-trees)
  3314. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  3315. ;; Declare Column View Code
  3316. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  3317. (declare-function org-columns-compute "org-colview" (property))
  3318. ;; Declare ID code
  3319. (declare-function org-id-store-link "org-id")
  3320. (declare-function org-id-locations-load "org-id")
  3321. (declare-function org-id-locations-save "org-id")
  3322. (defvar org-id-track-globally)
  3323. ;;; Variables for pre-computed regular expressions, all buffer local
  3324. (defvar-local org-todo-regexp nil
  3325. "Matches any of the TODO state keywords.
  3326. Since TODO keywords are case-sensitive, `case-fold-search' is
  3327. expected to be bound to nil when matching against this regexp.")
  3328. (defvar-local org-not-done-regexp nil
  3329. "Matches any of the TODO state keywords except the last one.
  3330. Since TODO keywords are case-sensitive, `case-fold-search' is
  3331. expected to be bound to nil when matching against this regexp.")
  3332. (defvar-local org-not-done-heading-regexp nil
  3333. "Matches a TODO headline that is not done.
  3334. Since TODO keywords are case-sensitive, `case-fold-search' is
  3335. expected to be bound to nil when matching against this regexp.")
  3336. (defvar-local org-todo-line-regexp nil
  3337. "Matches a headline and puts TODO state into group 2 if present.
  3338. Since TODO keywords are case-sensitive, `case-fold-search' is
  3339. expected to be bound to nil when matching against this regexp.")
  3340. (defvar-local org-complex-heading-regexp nil
  3341. "Matches a headline and puts everything into groups:
  3342. group 1: Stars
  3343. group 2: The TODO keyword, maybe
  3344. group 3: Priority cookie
  3345. group 4: True headline
  3346. group 5: Tags
  3347. Since TODO keywords are case-sensitive, `case-fold-search' is
  3348. expected to be bound to nil when matching against this regexp.")
  3349. (defvar-local org-complex-heading-regexp-format nil
  3350. "Printf format to make regexp to match an exact headline.
  3351. This regexp will match the headline of any node which has the
  3352. exact headline text that is put into the format, but may have any
  3353. TODO state, priority, tags, statistics cookies (at the beginning
  3354. or end of the headline title), or COMMENT keyword.")
  3355. (defvar-local org-todo-line-tags-regexp nil
  3356. "Matches a headline and puts TODO state into group 2 if present.
  3357. Also put tags into group 4 if tags are present.")
  3358. (defconst org-plain-time-of-day-regexp
  3359. (concat
  3360. "\\(\\<[012]?[0-9]"
  3361. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3362. "\\(--?"
  3363. "\\(\\<[012]?[0-9]"
  3364. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3365. "\\)?")
  3366. "Regular expression to match a plain time or time range.
  3367. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3368. groups carry important information:
  3369. 0 the full match
  3370. 1 the first time, range or not
  3371. 8 the second time, if it is a range.")
  3372. (defconst org-plain-time-extension-regexp
  3373. (concat
  3374. "\\(\\<[012]?[0-9]"
  3375. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3376. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  3377. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  3378. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3379. groups carry important information:
  3380. 0 the full match
  3381. 7 hours of duration
  3382. 9 minutes of duration")
  3383. (defconst org-stamp-time-of-day-regexp
  3384. (concat
  3385. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  3386. "\\([012][0-9]:[0-5][0-9]\\)\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?>"
  3387. "\\(--?"
  3388. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  3389. "Regular expression to match a timestamp time or time range.
  3390. After a match, the following groups carry important information:
  3391. 0 the full match
  3392. 1 date plus weekday, for back referencing to make sure
  3393. both times are on the same day
  3394. 2 the first time, range or not
  3395. 4 the second time, if it is a range.")
  3396. (defconst org-startup-options
  3397. '(("fold" org-startup-folded t)
  3398. ("overview" org-startup-folded t)
  3399. ("nofold" org-startup-folded nil)
  3400. ("showall" org-startup-folded nil)
  3401. ("show2levels" org-startup-folded show2levels)
  3402. ("show3levels" org-startup-folded show3levels)
  3403. ("show4levels" org-startup-folded show4levels)
  3404. ("show5levels" org-startup-folded show5levels)
  3405. ("showeverything" org-startup-folded showeverything)
  3406. ("content" org-startup-folded content)
  3407. ("indent" org-startup-indented t)
  3408. ("noindent" org-startup-indented nil)
  3409. ("num" org-startup-numerated t)
  3410. ("nonum" org-startup-numerated nil)
  3411. ("hidestars" org-hide-leading-stars t)
  3412. ("showstars" org-hide-leading-stars nil)
  3413. ("odd" org-odd-levels-only t)
  3414. ("oddeven" org-odd-levels-only nil)
  3415. ("align" org-startup-align-all-tables t)
  3416. ("noalign" org-startup-align-all-tables nil)
  3417. ("shrink" org-startup-shrink-all-tables t)
  3418. ("inlineimages" org-startup-with-inline-images t)
  3419. ("noinlineimages" org-startup-with-inline-images nil)
  3420. ("latexpreview" org-startup-with-latex-preview t)
  3421. ("nolatexpreview" org-startup-with-latex-preview nil)
  3422. ("customtime" org-display-custom-times t)
  3423. ("logdone" org-log-done time)
  3424. ("lognotedone" org-log-done note)
  3425. ("nologdone" org-log-done nil)
  3426. ("lognoteclock-out" org-log-note-clock-out t)
  3427. ("nolognoteclock-out" org-log-note-clock-out nil)
  3428. ("logrepeat" org-log-repeat state)
  3429. ("lognoterepeat" org-log-repeat note)
  3430. ("logdrawer" org-log-into-drawer t)
  3431. ("nologdrawer" org-log-into-drawer nil)
  3432. ("logstatesreversed" org-log-states-order-reversed t)
  3433. ("nologstatesreversed" org-log-states-order-reversed nil)
  3434. ("nologrepeat" org-log-repeat nil)
  3435. ("logreschedule" org-log-reschedule time)
  3436. ("lognotereschedule" org-log-reschedule note)
  3437. ("nologreschedule" org-log-reschedule nil)
  3438. ("logredeadline" org-log-redeadline time)
  3439. ("lognoteredeadline" org-log-redeadline note)
  3440. ("nologredeadline" org-log-redeadline nil)
  3441. ("logrefile" org-log-refile time)
  3442. ("lognoterefile" org-log-refile note)
  3443. ("nologrefile" org-log-refile nil)
  3444. ("fninline" org-footnote-define-inline t)
  3445. ("nofninline" org-footnote-define-inline nil)
  3446. ("fnlocal" org-footnote-section nil)
  3447. ("fnauto" org-footnote-auto-label t)
  3448. ("fnprompt" org-footnote-auto-label nil)
  3449. ("fnconfirm" org-footnote-auto-label confirm)
  3450. ("fnplain" org-footnote-auto-label plain)
  3451. ("fnadjust" org-footnote-auto-adjust t)
  3452. ("nofnadjust" org-footnote-auto-adjust nil)
  3453. ("constcgs" constants-unit-system cgs)
  3454. ("constSI" constants-unit-system SI)
  3455. ("noptag" org-tag-persistent-alist nil)
  3456. ("hideblocks" org-hide-block-startup t)
  3457. ("nohideblocks" org-hide-block-startup nil)
  3458. ("hidedrawers" org-hide-drawer-startup t)
  3459. ("nohidedrawers" org-hide-drawer-startup nil)
  3460. ("beamer" org-startup-with-beamer-mode t)
  3461. ("entitiespretty" org-pretty-entities t)
  3462. ("entitiesplain" org-pretty-entities nil))
  3463. "Variable associated with STARTUP options for Org.
  3464. Each element is a list of three items: the startup options (as written
  3465. in the #+STARTUP line), the corresponding variable, and the value to set
  3466. this variable to if the option is found. An optional fourth element PUSH
  3467. means to push this value onto the list in the variable.")
  3468. (defcustom org-group-tags t
  3469. "When non-nil (the default), use group tags.
  3470. This can be turned on/off through `org-toggle-tags-groups'."
  3471. :group 'org-tags
  3472. :group 'org-startup
  3473. :type 'boolean)
  3474. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  3475. (defun org-toggle-tags-groups ()
  3476. "Toggle support for group tags.
  3477. Support for group tags is controlled by the option
  3478. `org-group-tags', which is non-nil by default."
  3479. (interactive)
  3480. (setq org-group-tags (not org-group-tags))
  3481. (cond ((and (derived-mode-p 'org-agenda-mode)
  3482. org-group-tags)
  3483. (org-agenda-redo))
  3484. ((derived-mode-p 'org-mode)
  3485. (let ((org-inhibit-startup t)) (org-mode))))
  3486. (message "Groups tags support has been turned %s"
  3487. (if org-group-tags "on" "off")))
  3488. (defun org--tag-add-to-alist (alist1 alist2)
  3489. "Merge tags from ALIST1 into ALIST2.
  3490. Duplicates tags outside a group are removed. Keywords and order
  3491. are preserved.
  3492. The function assumes ALIST1 and ALIST2 are proper tag alists.
  3493. See `org-tag-alist' for their structure."
  3494. (cond
  3495. ((null alist2) alist1)
  3496. ((null alist1) alist2)
  3497. (t
  3498. (let ((to-add nil)
  3499. (group-flag nil))
  3500. (dolist (tag-pair alist1)
  3501. (pcase tag-pair
  3502. (`(,(or :startgrouptag :startgroup))
  3503. (setq group-flag t)
  3504. (push tag-pair to-add))
  3505. (`(,(or :endgrouptag :endgroup))
  3506. (setq group-flag nil)
  3507. (push tag-pair to-add))
  3508. (`(,(or :grouptags :newline))
  3509. (push tag-pair to-add))
  3510. (`(,tag . ,_)
  3511. ;; Remove duplicates from ALIST1, unless they are in
  3512. ;; a group. Indeed, it makes sense to have a tag appear in
  3513. ;; multiple groups.
  3514. (when (or group-flag (not (assoc tag alist2)))
  3515. (push tag-pair to-add)))
  3516. (_ (error "Invalid association in tag alist: %S" tag-pair))))
  3517. ;; Preserve order of ALIST1.
  3518. (append (nreverse to-add) alist2)))))
  3519. (defun org-priority-to-value (s)
  3520. "Convert priority string S to its numeric value."
  3521. (or (save-match-data
  3522. (and (string-match "\\([0-9]+\\)" s)
  3523. (string-to-number (match-string 1 s))))
  3524. (string-to-char s)))
  3525. (defun org-set-regexps-and-options (&optional tags-only)
  3526. "Precompute regular expressions used in the current buffer.
  3527. When optional argument TAGS-ONLY is non-nil, only compute tags
  3528. related expressions."
  3529. (when (derived-mode-p 'org-mode)
  3530. (let ((alist (org-collect-keywords
  3531. (append '("FILETAGS" "TAGS")
  3532. (and (not tags-only)
  3533. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  3534. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  3535. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))
  3536. '("ARCHIVE" "CATEGORY" "COLUMNS" "PRIORITIES"))))
  3537. ;; Startup options. Get this early since it does change
  3538. ;; behavior for other options (e.g., tags).
  3539. (let ((startup (cl-mapcan (lambda (value) (split-string value))
  3540. (cdr (assoc "STARTUP" alist)))))
  3541. (dolist (option startup)
  3542. (pcase (assoc-string option org-startup-options t)
  3543. (`(,_ ,variable ,value t)
  3544. (unless (listp (symbol-value variable))
  3545. (set (make-local-variable variable) nil))
  3546. (add-to-list variable value))
  3547. (`(,_ ,variable ,value . ,_)
  3548. (set (make-local-variable variable) value))
  3549. (_ nil))))
  3550. (setq-local org-file-tags
  3551. (mapcar #'org-add-prop-inherited
  3552. (cl-mapcan (lambda (value)
  3553. (cl-mapcan
  3554. (lambda (k) (org-split-string k ":"))
  3555. (split-string value)))
  3556. (cdr (assoc "FILETAGS" alist)))))
  3557. (setq org-current-tag-alist
  3558. (org--tag-add-to-alist
  3559. org-tag-persistent-alist
  3560. (let ((tags (cdr (assoc "TAGS" alist))))
  3561. (if tags
  3562. (org-tag-string-to-alist
  3563. (mapconcat #'identity tags "\n"))
  3564. org-tag-alist))))
  3565. (setq org-tag-groups-alist
  3566. (org-tag-alist-to-groups org-current-tag-alist))
  3567. (unless tags-only
  3568. ;; Properties.
  3569. (let ((properties nil))
  3570. (dolist (value (cdr (assoc "PROPERTY" alist)))
  3571. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  3572. (setq properties (org--update-property-plist
  3573. (match-string-no-properties 1 value)
  3574. (match-string-no-properties 2 value)
  3575. properties))))
  3576. (setq-local org-keyword-properties properties))
  3577. ;; Archive location.
  3578. (let ((archive (cdr (assoc "ARCHIVE" alist))))
  3579. (when archive (setq-local org-archive-location archive)))
  3580. ;; Category.
  3581. (let ((category (cdr (assoc "CATEGORY" alist))))
  3582. (when category
  3583. (setq-local org-category (intern category))
  3584. (setq-local org-keyword-properties
  3585. (org--update-property-plist
  3586. "CATEGORY" category org-keyword-properties))))
  3587. ;; Columns.
  3588. (let ((column (cdr (assoc "COLUMNS" alist))))
  3589. (when column (setq-local org-columns-default-format column)))
  3590. ;; Constants.
  3591. (let ((store nil))
  3592. (dolist (pair (cl-mapcan #'split-string
  3593. (cdr (assoc "CONSTANTS" alist))))
  3594. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" pair)
  3595. (let* ((name (match-string 1 pair))
  3596. (value (match-string 2 pair))
  3597. (old (assoc name store)))
  3598. (if old (setcdr old value)
  3599. (push (cons name value) store)))))
  3600. (setq org-table-formula-constants-local store))
  3601. ;; Link abbreviations.
  3602. (let ((links
  3603. (delq nil
  3604. (mapcar
  3605. (lambda (value)
  3606. (and (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  3607. (cons (match-string-no-properties 1 value)
  3608. (match-string-no-properties 2 value))))
  3609. (cdr (assoc "LINK" alist))))))
  3610. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  3611. ;; Priorities.
  3612. (let ((value (cdr (assoc "PRIORITIES" alist))))
  3613. (pcase (and value (split-string value))
  3614. (`(,high ,low ,default . ,_)
  3615. (setq-local org-priority-highest (org-priority-to-value high))
  3616. (setq-local org-priority-lowest (org-priority-to-value low))
  3617. (setq-local org-priority-default (org-priority-to-value default)))))
  3618. ;; Scripts.
  3619. (let ((value (cdr (assoc "OPTIONS" alist))))
  3620. (dolist (option value)
  3621. (when (string-match "\\^:\\(t\\|nil\\|{}\\)" option)
  3622. (setq-local org-use-sub-superscripts
  3623. (read (match-string 1 option))))))
  3624. ;; TODO keywords.
  3625. (setq-local org-todo-kwd-alist nil)
  3626. (setq-local org-todo-key-alist nil)
  3627. (setq-local org-todo-key-trigger nil)
  3628. (setq-local org-todo-keywords-1 nil)
  3629. (setq-local org-done-keywords nil)
  3630. (setq-local org-todo-heads nil)
  3631. (setq-local org-todo-sets nil)
  3632. (setq-local org-todo-log-states nil)
  3633. (let ((todo-sequences
  3634. (or (append (mapcar (lambda (value)
  3635. (cons 'type (split-string value)))
  3636. (cdr (assoc "TYP_TODO" alist)))
  3637. (mapcar (lambda (value)
  3638. (cons 'sequence (split-string value)))
  3639. (append (cdr (assoc "TODO" alist))
  3640. (cdr (assoc "SEQ_TODO" alist)))))
  3641. (let ((d (default-value 'org-todo-keywords)))
  3642. (if (not (stringp (car d))) d
  3643. ;; XXX: Backward compatibility code.
  3644. (list (cons org-todo-interpretation d)))))))
  3645. (dolist (sequence todo-sequences)
  3646. (let* ((sequence (or (run-hook-with-args-until-success
  3647. 'org-todo-setup-filter-hook sequence)
  3648. sequence))
  3649. (sequence-type (car sequence))
  3650. (keywords (cdr sequence))
  3651. (sep (member "|" keywords))
  3652. names alist)
  3653. (dolist (k (remove "|" keywords))
  3654. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  3655. k)
  3656. (error "Invalid TODO keyword %s" k))
  3657. (let ((name (match-string 1 k))
  3658. (key (match-string 2 k))
  3659. (log (org-extract-log-state-settings k)))
  3660. (push name names)
  3661. (push (cons name (and key (string-to-char key))) alist)
  3662. (when log (push log org-todo-log-states))))
  3663. (let* ((names (nreverse names))
  3664. (done (if sep (org-remove-keyword-keys (cdr sep))
  3665. (last names)))
  3666. (head (car names))
  3667. (tail (list sequence-type head (car done) (org-last done))))
  3668. (add-to-list 'org-todo-heads head 'append)
  3669. (push names org-todo-sets)
  3670. (setq org-done-keywords (append org-done-keywords done nil))
  3671. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  3672. (setq org-todo-key-alist
  3673. (append org-todo-key-alist
  3674. (and alist
  3675. (append '((:startgroup))
  3676. (nreverse alist)
  3677. '((:endgroup))))))
  3678. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  3679. (setq org-todo-sets (nreverse org-todo-sets)
  3680. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  3681. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  3682. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  3683. ;; Compute the regular expressions and other local variables.
  3684. ;; Using `org-outline-regexp-bol' would complicate them much,
  3685. ;; because of the fixed white space at the end of that string.
  3686. (unless org-done-keywords
  3687. (setq org-done-keywords
  3688. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  3689. (setq org-not-done-keywords
  3690. (org-delete-all org-done-keywords
  3691. (copy-sequence org-todo-keywords-1))
  3692. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  3693. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  3694. org-not-done-heading-regexp
  3695. (format org-heading-keyword-regexp-format org-not-done-regexp)
  3696. org-todo-line-regexp
  3697. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  3698. org-complex-heading-regexp
  3699. (concat "^\\(\\*+\\)"
  3700. "\\(?: +" org-todo-regexp "\\)?"
  3701. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3702. "\\(?: +\\(.*?\\)\\)??"
  3703. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  3704. "[ \t]*$")
  3705. org-complex-heading-regexp-format
  3706. (concat "^\\(\\*+\\)"
  3707. "\\(?: +" org-todo-regexp "\\)?"
  3708. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3709. "\\(?: +"
  3710. ;; Headline might be commented
  3711. "\\(?:" org-comment-string " +\\)?"
  3712. ;; Stats cookies can be stuck to body.
  3713. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  3714. "\\(%s\\)"
  3715. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  3716. "\\)"
  3717. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  3718. "[ \t]*$")
  3719. org-todo-line-tags-regexp
  3720. (concat "^\\(\\*+\\)"
  3721. "\\(?: +" org-todo-regexp "\\)?"
  3722. "\\(?: +\\(.*?\\)\\)??"
  3723. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  3724. "[ \t]*$"))
  3725. (org-compute-latex-and-related-regexp)))))
  3726. (defun org-collect-keywords (keywords &optional unique directory)
  3727. "Return values for KEYWORDS in current buffer, as an alist.
  3728. KEYWORDS is a list of strings. Return value is a list of
  3729. elements with the pattern:
  3730. (NAME . LIST-OF-VALUES)
  3731. where NAME is the upcase name of the keyword, and LIST-OF-VALUES
  3732. is a list of non-empty values, as strings, in order of appearance
  3733. in the buffer.
  3734. When KEYWORD appears in UNIQUE list, LIST-OF-VALUE is its first
  3735. value, empty or not, appearing in the buffer, as a string.
  3736. When KEYWORD appears in DIRECTORIES, each value is a cons cell:
  3737. (VALUE . DIRECTORY)
  3738. where VALUE is the regular value, and DIRECTORY is the variable
  3739. `default-directory' for the buffer containing the keyword. This
  3740. is important for values containing relative file names, since the
  3741. function follows SETUPFILE keywords, and may change its working
  3742. directory."
  3743. (let* ((keywords (cons "SETUPFILE" (mapcar #'upcase keywords)))
  3744. (unique (mapcar #'upcase unique))
  3745. (alist (org--collect-keywords-1
  3746. keywords unique directory
  3747. (and buffer-file-name (list buffer-file-name))
  3748. nil)))
  3749. ;; Re-order results.
  3750. (dolist (entry alist)
  3751. (pcase entry
  3752. (`(,_ . ,(and value (pred consp)))
  3753. (setcdr entry (nreverse value)))))
  3754. (nreverse alist)))
  3755. (defun org--collect-keywords-1 (keywords unique directory files alist)
  3756. (org-with-point-at 1
  3757. (let ((case-fold-search t)
  3758. (regexp (org-make-options-regexp keywords)))
  3759. (while (and keywords (re-search-forward regexp nil t))
  3760. (let ((element (org-element-at-point)))
  3761. (when (eq 'keyword (org-element-type element))
  3762. (let ((value (org-element-property :value element)))
  3763. (pcase (org-element-property :key element)
  3764. ("SETUPFILE"
  3765. (when (and (org-string-nw-p value)
  3766. (not buffer-read-only)) ;FIXME: bug in Gnus?
  3767. (let* ((uri (org-strip-quotes value))
  3768. (uri-is-url (org-url-p uri))
  3769. (uri (if uri-is-url
  3770. uri
  3771. (expand-file-name uri))))
  3772. (unless (member uri files)
  3773. (with-temp-buffer
  3774. (unless uri-is-url
  3775. (setq default-directory (file-name-directory uri)))
  3776. (let ((contents (org-file-contents uri :noerror)))
  3777. (when contents
  3778. (insert contents)
  3779. ;; Fake Org mode: `org-element-at-point'
  3780. ;; doesn't need full set-up.
  3781. (let ((major-mode 'org-mode))
  3782. (setq alist
  3783. (org--collect-keywords-1
  3784. keywords unique directory
  3785. (cons uri files)
  3786. alist))))))))))
  3787. (keyword
  3788. (let ((entry (assoc keyword alist))
  3789. (final
  3790. (cond ((not (member keyword directory)) value)
  3791. (buffer-file-name
  3792. (cons value
  3793. (file-name-directory buffer-file-name)))
  3794. (t (cons value default-directory)))))
  3795. (cond ((member keyword unique)
  3796. (push (cons keyword final) alist)
  3797. (setq keywords (remove keyword keywords))
  3798. (setq regexp (org-make-options-regexp keywords)))
  3799. ((null entry) (push (list keyword final) alist))
  3800. (t (push final (cdr entry)))))))))))
  3801. alist)))
  3802. (defun org-tag-string-to-alist (s)
  3803. "Return tag alist associated to string S.
  3804. S is a value for TAGS keyword or produced with
  3805. `org-tag-alist-to-string'. Return value is an alist suitable for
  3806. `org-tag-alist' or `org-tag-persistent-alist'."
  3807. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  3808. (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
  3809. "\\(?:(\\(.\\))\\)?\\'"))
  3810. alist group-flag)
  3811. (dolist (tokens lines (cdr (nreverse alist)))
  3812. (push '(:newline) alist)
  3813. (while tokens
  3814. (let ((token (pop tokens)))
  3815. (pcase token
  3816. ("{"
  3817. (push '(:startgroup) alist)
  3818. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3819. ("}"
  3820. (push '(:endgroup) alist)
  3821. (setq group-flag nil))
  3822. ("["
  3823. (push '(:startgrouptag) alist)
  3824. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3825. ("]"
  3826. (push '(:endgrouptag) alist)
  3827. (setq group-flag nil))
  3828. (":"
  3829. (push '(:grouptags) alist))
  3830. ((guard (string-match tag-re token))
  3831. (let ((tag (match-string 1 token))
  3832. (key (and (match-beginning 2)
  3833. (string-to-char (match-string 2 token)))))
  3834. ;; Push all tags in groups, no matter if they already
  3835. ;; appear somewhere else in the list.
  3836. (when (or group-flag (not (assoc tag alist)))
  3837. (push (cons tag key) alist))))))))))
  3838. (defun org-tag-alist-to-string (alist &optional skip-key)
  3839. "Return tag string associated to ALIST.
  3840. ALIST is an alist, as defined in `org-tag-alist' or
  3841. `org-tag-persistent-alist', or produced with
  3842. `org-tag-string-to-alist'.
  3843. Return value is a string suitable as a value for \"TAGS\"
  3844. keyword.
  3845. When optional argument SKIP-KEY is non-nil, skip selection keys
  3846. next to tags."
  3847. (mapconcat (lambda (token)
  3848. (pcase token
  3849. (`(:startgroup) "{")
  3850. (`(:endgroup) "}")
  3851. (`(:startgrouptag) "[")
  3852. (`(:endgrouptag) "]")
  3853. (`(:grouptags) ":")
  3854. (`(:newline) "\\n")
  3855. ((and
  3856. (guard (not skip-key))
  3857. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  3858. (format "%s(%c)" tag key))
  3859. (`(,(and tag (pred stringp)) . ,_) tag)
  3860. (_ (user-error "Invalid tag token: %S" token))))
  3861. alist
  3862. " "))
  3863. (defun org-tag-alist-to-groups (alist)
  3864. "Return group alist from tag ALIST.
  3865. ALIST is an alist, as defined in `org-tag-alist' or
  3866. `org-tag-persistent-alist', or produced with
  3867. `org-tag-string-to-alist'. Return value is an alist following
  3868. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  3869. a string, summarizing TAGS, as a list of strings."
  3870. (let (groups group-status current-group)
  3871. (dolist (token alist (nreverse groups))
  3872. (pcase token
  3873. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  3874. (`(,(or :endgroup :endgrouptag))
  3875. (when (eq group-status 'append)
  3876. (push (nreverse current-group) groups))
  3877. (setq group-status nil current-group nil))
  3878. (`(:grouptags) (setq group-status 'append))
  3879. ((and `(,tag . ,_) (guard group-status))
  3880. (if (eq group-status 'append) (push tag current-group)
  3881. (setq current-group (list tag))))
  3882. (_ nil)))))
  3883. (defvar org--file-cache (make-hash-table :test #'equal)
  3884. "Hash table to store contents of files referenced via a URL.
  3885. This is the cache of file URLs read using `org-file-contents'.")
  3886. (defun org-reset-file-cache ()
  3887. "Reset the cache of files downloaded by `org-file-contents'."
  3888. (clrhash org--file-cache))
  3889. (defun org-file-contents (file &optional noerror nocache)
  3890. "Return the contents of FILE, as a string.
  3891. FILE can be a file name or URL.
  3892. If FILE is a URL, download the contents. If the URL contents are
  3893. already cached in the `org--file-cache' hash table, the download step
  3894. is skipped.
  3895. If NOERROR is non-nil, ignore the error when unable to read the FILE
  3896. from file or URL, and return nil.
  3897. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  3898. is available. This option applies only if FILE is a URL."
  3899. (let* ((is-url (org-url-p file))
  3900. (cache (and is-url
  3901. (not nocache)
  3902. (gethash file org--file-cache))))
  3903. (cond
  3904. (cache)
  3905. (is-url
  3906. (if (org--should-fetch-remote-resource-p file)
  3907. (with-current-buffer (url-retrieve-synchronously file)
  3908. (goto-char (point-min))
  3909. ;; Move point to after the url-retrieve header.
  3910. (search-forward "\n\n" nil :move)
  3911. ;; Search for the success code only in the url-retrieve header.
  3912. (if (save-excursion
  3913. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  3914. ;; Update the cache `org--file-cache' and return contents.
  3915. (puthash file
  3916. (buffer-substring-no-properties (point) (point-max))
  3917. org--file-cache)
  3918. (funcall (if noerror #'message #'user-error)
  3919. "Unable to fetch file from %S"
  3920. file)
  3921. nil))
  3922. (funcall (if noerror #'message #'user-error)
  3923. "The remote resource %S is considered unsafe, and will not be downloaded."
  3924. file)))
  3925. (t
  3926. (with-temp-buffer
  3927. (condition-case nil
  3928. (progn
  3929. (insert-file-contents file)
  3930. (buffer-string))
  3931. (file-error
  3932. (funcall (if noerror #'message #'user-error)
  3933. "Unable to read file %S"
  3934. file)
  3935. nil)))))))
  3936. (defun org--should-fetch-remote-resource-p (uri)
  3937. "Return non-nil if the URI should be fetched."
  3938. (or (eq org-resource-download-policy t)
  3939. (org--safe-remote-resource-p uri)
  3940. (and (eq org-resource-download-policy 'prompt)
  3941. (org--confirm-resource-safe uri))))
  3942. (defun org--safe-remote-resource-p (uri)
  3943. "Return non-nil if URI is considered safe.
  3944. This checks every pattern in `org-safe-remote-resources', and
  3945. returns non-nil if any of them match."
  3946. (let ((uri-patterns org-safe-remote-resources)
  3947. (file-uri (and buffer-file-name
  3948. (concat "file://" (file-truename buffer-file-name))))
  3949. match-p)
  3950. (while (and (not match-p) uri-patterns)
  3951. (setq match-p (or (string-match-p (car uri-patterns) uri)
  3952. (and file-uri (string-match-p (car uri-patterns) file-uri)))
  3953. uri-patterns (cdr uri-patterns)))
  3954. match-p))
  3955. (defun org--confirm-resource-safe (uri)
  3956. "Ask the user if URI should be considered safe, returning non-nil if so."
  3957. (unless noninteractive
  3958. (let ((current-file (and buffer-file-name (file-truename buffer-file-name)))
  3959. (domain (and (string-match
  3960. (rx (seq "http" (? "s") "://")
  3961. (optional (+ (not (any "@/\n"))) "@")
  3962. (optional "www.")
  3963. (one-or-more (not (any ":/?\n"))))
  3964. uri)
  3965. (match-string 0 uri)))
  3966. (buf (get-buffer-create "*Org Remote Resource*")))
  3967. ;; Set up the contents of the *Org Remote Resource* buffer.
  3968. (with-current-buffer buf
  3969. (erase-buffer)
  3970. (insert "An org-mode document would like to download "
  3971. (propertize uri 'face '(:inherit org-link :weight normal))
  3972. ", which is not considered safe.\n\n"
  3973. "Do you want to download this? You can type\n "
  3974. (propertize "!" 'face 'success)
  3975. " to download this resource, and permanantly mark it as safe.\n "
  3976. (if domain
  3977. (concat
  3978. (propertize "d" 'face 'success)
  3979. " to download this resource, and mark the domain ("
  3980. (propertize domain 'face '(:inherit org-link :weight normal))
  3981. ") as safe.\n ")
  3982. "")
  3983. (propertize "f" 'face 'success)
  3984. (if current-file
  3985. (concat
  3986. " to download this resource, and permanantly mark all resources in "
  3987. (propertize current-file 'face 'underline)
  3988. " as safe.\n ")
  3989. "")
  3990. (propertize "y" 'face 'warning)
  3991. " to download this resource, just this once.\n "
  3992. (propertize "n" 'face 'error)
  3993. " to skip this resource.\n")
  3994. (setq-local cursor-type nil)
  3995. (set-buffer-modified-p nil)
  3996. (goto-char (point-min)))
  3997. ;; Display the buffer and read a choice.
  3998. (save-window-excursion
  3999. (pop-to-buffer buf)
  4000. (let* ((exit-chars (append '(?y ?n ?! ?d ?\s) (and current-file '(?f))))
  4001. (prompt (format "Please type y, n%s, d, or !%s: "
  4002. (if current-file ", f" "")
  4003. (if (< (line-number-at-pos (point-max))
  4004. (window-body-height))
  4005. ""
  4006. ", or C-v/M-v to scroll")))
  4007. char)
  4008. (setq char (read-char-choice prompt exit-chars))
  4009. (when (memq char '(?! ?f ?d))
  4010. (customize-push-and-save
  4011. 'org-safe-remote-resources
  4012. (list (if (eq char ?d)
  4013. (concat "\\`" (regexp-quote domain) "\\(?:/\\|\\'\\)")
  4014. (concat "\\`"
  4015. (regexp-quote
  4016. (if (and (= char ?f) current-file)
  4017. (concat "file://" current-file) uri))
  4018. "\\'")))))
  4019. (prog1 (memq char '(?y ?n ?! ?d ?\s ?f))
  4020. (quit-window t)))))))
  4021. (defun org-extract-log-state-settings (x)
  4022. "Extract the log state setting from a TODO keyword string.
  4023. This will extract info from a string like \"WAIT(w@/!)\"."
  4024. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4025. (let ((kw (match-string 1 x))
  4026. (log1 (and (match-end 3) (match-string 3 x)))
  4027. (log2 (and (match-end 4) (match-string 4 x))))
  4028. (and (or log1 log2)
  4029. (list kw
  4030. (and log1 (if (equal log1 "!") 'time 'note))
  4031. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4032. (defun org-remove-keyword-keys (list)
  4033. "Remove a pair of parenthesis at the end of each string in LIST."
  4034. (mapcar (lambda (x)
  4035. (if (string-match "(.*)$" x)
  4036. (substring x 0 (match-beginning 0))
  4037. x))
  4038. list))
  4039. (defun org-assign-fast-keys (alist)
  4040. "Assign fast keys to a keyword-key alist.
  4041. Respect keys that are already there."
  4042. (let (new e (alt ?0))
  4043. (while (setq e (pop alist))
  4044. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4045. (cdr e)) ;; Key already assigned.
  4046. (push e new)
  4047. (let ((clist (string-to-list (downcase (car e))))
  4048. (used (append new alist)))
  4049. (when (= (car clist) ?@)
  4050. (pop clist))
  4051. (while (and clist (rassoc (car clist) used))
  4052. (pop clist))
  4053. (unless clist
  4054. (while (rassoc alt used)
  4055. (cl-incf alt)))
  4056. (push (cons (car e) (or (car clist) alt)) new))))
  4057. (nreverse new)))
  4058. ;;; Some variables used in various places
  4059. (defvar org-window-configuration nil
  4060. "Used in various places to store a window configuration.")
  4061. (defvar org-selected-window nil
  4062. "Used in various places to store a window configuration.")
  4063. (defvar org-finish-function nil
  4064. "Function to be called when `C-c C-c' is used.
  4065. This is for getting out of special buffers like capture.")
  4066. (defvar org-last-state)
  4067. ;; Defined somewhere in this file, but used before definition.
  4068. (defvar org-entities) ;; defined in org-entities.el
  4069. (defvar org-struct-menu)
  4070. (defvar org-org-menu)
  4071. (defvar org-tbl-menu)
  4072. ;;;; Define the Org mode
  4073. (defun org-before-change-function (_beg _end)
  4074. "Every change indicates that a table might need an update."
  4075. (setq org-table-may-need-update t))
  4076. (defvar org-mode-map)
  4077. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4078. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4079. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4080. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4081. (defvar bidi-paragraph-direction)
  4082. (defvar buffer-face-mode-face)
  4083. (require 'outline)
  4084. ;; Other stuff we need.
  4085. (require 'time-date)
  4086. (when (< emacs-major-version 28) ; preloaded in Emacs 28
  4087. (require 'easymenu))
  4088. (require 'org-entities)
  4089. (require 'org-faces)
  4090. (require 'org-list)
  4091. (require 'org-pcomplete)
  4092. (require 'org-src)
  4093. (require 'org-footnote)
  4094. (require 'org-macro)
  4095. ;; babel
  4096. (require 'ob)
  4097. (defvar org-element-cache-persistent); Defined in org-element.el
  4098. (defvar org-element-use-cache); Defined in org-element.el
  4099. (defvar org-mode-loading nil
  4100. "Non-nil during Org mode initialisation.")
  4101. (defvar org-agenda-file-menu-enabled t
  4102. "When non-nil, refresh Agenda files in Org menu when loading Org.")
  4103. ;;;###autoload
  4104. (define-derived-mode org-mode outline-mode "Org"
  4105. "Outline-based notes management and organizer, alias
  4106. \"Carsten's outline-mode for keeping track of everything.\"
  4107. Org mode develops organizational tasks around a NOTES file which
  4108. contains information about projects as plain text. Org mode is
  4109. implemented on top of Outline mode, which is ideal to keep the content
  4110. of large files well structured. It supports ToDo items, deadlines and
  4111. time stamps, which magically appear in the diary listing of the Emacs
  4112. calendar. Tables are easily created with a built-in table editor.
  4113. Plain text URL-like links connect to websites, emails (VM), Usenet
  4114. messages (Gnus), BBDB entries, and any files related to the project.
  4115. For printing and sharing of notes, an Org file (or a part of it)
  4116. can be exported as a structured ASCII or HTML file.
  4117. The following commands are available:
  4118. \\{org-mode-map}"
  4119. (setq-local org-mode-loading t)
  4120. (org-load-modules-maybe)
  4121. (when org-agenda-file-menu-enabled
  4122. (org-install-agenda-files-menu))
  4123. (when (and org-link-descriptive
  4124. (eq org-fold-core-style 'overlays))
  4125. (add-to-invisibility-spec '(org-link)))
  4126. (org-fold-initialize (or (and (stringp org-ellipsis) (not (equal "" org-ellipsis)) org-ellipsis)
  4127. "..."))
  4128. (make-local-variable 'org-link-descriptive)
  4129. (when (eq org-fold-core-style 'overlays) (add-to-invisibility-spec '(org-hide-block . t)))
  4130. (if org-link-descriptive
  4131. (org-fold-core-set-folding-spec-property (car org-link--link-folding-spec) :visible nil)
  4132. (org-fold-core-set-folding-spec-property (car org-link--link-folding-spec) :visible t))
  4133. (setq-local outline-regexp org-outline-regexp)
  4134. (setq-local outline-level 'org-outline-level)
  4135. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4136. (unless org-display-table
  4137. (setq org-display-table (make-display-table)))
  4138. (set-display-table-slot
  4139. org-display-table 4
  4140. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4141. org-ellipsis)))
  4142. (setq buffer-display-table org-display-table))
  4143. (org-set-regexps-and-options)
  4144. (org-set-font-lock-defaults)
  4145. (when (and org-tag-faces (not org-tags-special-faces-re))
  4146. ;; tag faces set outside customize.... force initialization.
  4147. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4148. ;; Calc embedded
  4149. (setq-local calc-embedded-open-mode "# ")
  4150. ;; Modify a few syntax entries
  4151. (modify-syntax-entry ?\" "\"")
  4152. (modify-syntax-entry ?\\ "_")
  4153. (modify-syntax-entry ?~ "_")
  4154. (modify-syntax-entry ?< "(>")
  4155. (modify-syntax-entry ?> ")<")
  4156. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4157. ;; Activate before-change-function
  4158. (setq-local org-table-may-need-update t)
  4159. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4160. ;; Check for running clock before killing a buffer
  4161. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4162. ;; Initialize cache.
  4163. (org-element-cache-reset)
  4164. (when (and org-element-cache-persistent
  4165. org-element-use-cache)
  4166. (org-persist-load 'org-element--cache (current-buffer) t))
  4167. ;; Initialize macros templates.
  4168. (org-macro-initialize-templates)
  4169. ;; Initialize radio targets.
  4170. (org-update-radio-target-regexp)
  4171. ;; Indentation.
  4172. (setq-local indent-line-function 'org-indent-line)
  4173. (setq-local indent-region-function 'org-indent-region)
  4174. ;; Filling and auto-filling.
  4175. (org-setup-filling)
  4176. ;; Comments.
  4177. (org-setup-comments-handling)
  4178. ;; Beginning/end of defun
  4179. (setq-local beginning-of-defun-function 'org-backward-element)
  4180. (setq-local end-of-defun-function
  4181. (lambda ()
  4182. (if (not (org-at-heading-p))
  4183. (org-forward-element)
  4184. (org-forward-element)
  4185. (forward-char -1))))
  4186. ;; Next error for sparse trees
  4187. (setq-local next-error-function 'org-occur-next-match)
  4188. ;; Make commit log messages from Org documents easier.
  4189. (setq-local add-log-current-defun-function #'org-add-log-current-headline)
  4190. ;; Make sure dependence stuff works reliably, even for users who set it
  4191. ;; too late :-(
  4192. (if org-enforce-todo-dependencies
  4193. (add-hook 'org-blocker-hook
  4194. 'org-block-todo-from-children-or-siblings-or-parent)
  4195. (remove-hook 'org-blocker-hook
  4196. 'org-block-todo-from-children-or-siblings-or-parent))
  4197. (if org-enforce-todo-checkbox-dependencies
  4198. (add-hook 'org-blocker-hook
  4199. 'org-block-todo-from-checkboxes)
  4200. (remove-hook 'org-blocker-hook
  4201. 'org-block-todo-from-checkboxes))
  4202. ;; Align options lines
  4203. (setq-local
  4204. align-mode-rules-list
  4205. '((org-in-buffer-settings
  4206. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4207. (modes . '(org-mode)))))
  4208. ;; Setup the pcomplete hooks
  4209. (setq-local pcomplete-command-completion-function #'org-pcomplete-initial)
  4210. (setq-local pcomplete-command-name-function #'org-command-at-point)
  4211. (setq-local pcomplete-default-completion-function #'ignore)
  4212. (setq-local pcomplete-parse-arguments-function #'org-parse-arguments)
  4213. (setq-local pcomplete-termination-string "")
  4214. (add-hook 'completion-at-point-functions
  4215. #'pcomplete-completions-at-point nil t)
  4216. (setq-local buffer-face-mode-face 'org-default)
  4217. ;; If empty file that did not turn on Org mode automatically, make
  4218. ;; it to.
  4219. (when (and org-insert-mode-line-in-empty-file
  4220. (called-interactively-p 'any)
  4221. (= (point-min) (point-max)))
  4222. (insert "# -*- mode: org -*-\n\n"))
  4223. (unless org-inhibit-startup
  4224. (org-unmodified
  4225. (when org-startup-with-beamer-mode (org-beamer-mode))
  4226. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4227. (org-table-map-tables
  4228. (cond ((and org-startup-align-all-tables
  4229. org-startup-shrink-all-tables)
  4230. (lambda () (org-table-align) (org-table-shrink)))
  4231. (org-startup-align-all-tables #'org-table-align)
  4232. (t #'org-table-shrink))
  4233. t))
  4234. (when org-startup-with-inline-images (org-display-inline-images))
  4235. (when org-startup-with-latex-preview (org-latex-preview '(16)))
  4236. (unless org-inhibit-startup-visibility-stuff (org-cycle-set-startup-visibility))
  4237. (when org-startup-truncated (setq truncate-lines t))
  4238. (when org-startup-numerated (require 'org-num) (org-num-mode 1))
  4239. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))))
  4240. ;; Add a custom keymap for `visual-line-mode' so that activating
  4241. ;; this minor mode does not override Org's keybindings.
  4242. ;; FIXME: Probably `visual-line-mode' should take care of this.
  4243. (let ((oldmap (cdr (assoc 'visual-line-mode minor-mode-map-alist)))
  4244. (newmap (make-sparse-keymap)))
  4245. (set-keymap-parent newmap oldmap)
  4246. (define-key newmap [remap move-beginning-of-line] nil)
  4247. (define-key newmap [remap move-end-of-line] nil)
  4248. (define-key newmap [remap kill-line] nil)
  4249. (make-local-variable 'minor-mode-overriding-map-alist)
  4250. (push `(visual-line-mode . ,newmap) minor-mode-overriding-map-alist))
  4251. ;; Activate `org-table-header-line-mode'
  4252. (when org-table-header-line-p
  4253. (org-table-header-line-mode 1))
  4254. ;; Try to set `org-hide' face correctly.
  4255. (let ((foreground (org-find-invisible-foreground)))
  4256. (when foreground
  4257. (set-face-foreground 'org-hide foreground)))
  4258. ;; Set face extension as requested.
  4259. (org--set-faces-extend '(org-block-begin-line org-block-end-line)
  4260. org-fontify-whole-block-delimiter-line)
  4261. (org--set-faces-extend org-level-faces org-fontify-whole-heading-line)
  4262. (setq-local org-mode-loading nil))
  4263. ;; Update `customize-package-emacs-version-alist'
  4264. (add-to-list 'customize-package-emacs-version-alist
  4265. '(Org ("8.0" . "24.4")
  4266. ("8.1" . "24.4")
  4267. ("8.2" . "24.4")
  4268. ("8.2.7" . "24.4")
  4269. ("8.3" . "26.1")
  4270. ("9.0" . "26.1")
  4271. ("9.1" . "26.1")
  4272. ("9.2" . "27.1")
  4273. ("9.3" . "27.1")
  4274. ("9.4" . "27.2")
  4275. ("9.5" . "28.1")
  4276. ("9.6" . "29.1")))
  4277. (defvar org-mode-transpose-word-syntax-table
  4278. (let ((st (make-syntax-table text-mode-syntax-table)))
  4279. (dolist (c org-emphasis-alist st)
  4280. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4281. (when (fboundp 'abbrev-table-put)
  4282. (abbrev-table-put org-mode-abbrev-table
  4283. :parents (list text-mode-abbrev-table)))
  4284. (defun org-find-invisible-foreground ()
  4285. (let ((candidates (remove
  4286. "unspecified-bg"
  4287. (nconc
  4288. (list (face-background 'default)
  4289. (face-background 'org-default))
  4290. (mapcar
  4291. (lambda (alist)
  4292. (when (boundp alist)
  4293. (cdr (assq 'background-color (symbol-value alist)))))
  4294. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4295. (list (face-foreground 'org-hide))))))
  4296. (car (remove nil candidates))))
  4297. (defun org-current-time (&optional rounding-minutes past)
  4298. "Current time, possibly rounded to ROUNDING-MINUTES.
  4299. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4300. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4301. the rounding returns a past time."
  4302. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4303. (car org-time-stamp-rounding-minutes)))
  4304. (now (current-time)))
  4305. (if (< r 1)
  4306. now
  4307. (let* ((time (decode-time now))
  4308. (res (org-encode-time
  4309. (apply #'list
  4310. 0 (* r (round (nth 1 time) r))
  4311. (nthcdr 2 time)))))
  4312. (if (or (not past) (time-less-p res now))
  4313. res
  4314. (time-subtract res (* r 60)))))))
  4315. (defun org-today ()
  4316. "Return today date, considering `org-extend-today-until'."
  4317. (time-to-days
  4318. (time-since (* 3600 org-extend-today-until))))
  4319. ;;;; Font-Lock stuff, including the activators
  4320. (defconst org-match-sexp-depth 3
  4321. "Number of stacked braces for sub/superscript matching.")
  4322. (defun org-create-multibrace-regexp (left right n)
  4323. "Create a regular expression which will match a balanced sexp.
  4324. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4325. as single character strings.
  4326. The regexp returned will match the entire expression including the
  4327. delimiters. It will also define a single group which contains the
  4328. match except for the outermost delimiters. The maximum depth of
  4329. stacked delimiters is N. Escaping delimiters is not possible."
  4330. (let* ((nothing (concat "[^" left right "]*?"))
  4331. (or "\\|")
  4332. (re nothing)
  4333. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4334. (while (> n 1)
  4335. (setq n (1- n)
  4336. re (concat re or next)
  4337. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4338. (concat left "\\(" re "\\)" right)))
  4339. (defconst org-match-substring-regexp
  4340. (concat
  4341. "\\(\\S-\\)\\([_^]\\)\\("
  4342. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4343. "\\|"
  4344. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4345. "\\|"
  4346. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4347. "The regular expression matching a sub- or superscript.")
  4348. (defconst org-match-substring-with-braces-regexp
  4349. (concat
  4350. "\\(\\S-\\)\\([_^]\\)"
  4351. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4352. "The regular expression matching a sub- or superscript, forcing braces.")
  4353. (defvar org-emph-face nil)
  4354. (defun org-do-emphasis-faces (limit)
  4355. "Run through the buffer and emphasize strings."
  4356. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  4357. (car org-emphasis-regexp-components))))
  4358. (catch :exit
  4359. (while (re-search-forward quick-re limit t)
  4360. (let* ((marker (match-string 2))
  4361. (verbatim? (member marker '("~" "="))))
  4362. (when (save-excursion
  4363. (goto-char (match-beginning 0))
  4364. (and
  4365. ;; Do not match table hlines.
  4366. (not (and (equal marker "+")
  4367. (org-match-line
  4368. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  4369. ;; Do not match headline stars. Do not consider
  4370. ;; stars of a headline as closing marker for bold
  4371. ;; markup either.
  4372. (not (and (equal marker "*")
  4373. (save-excursion
  4374. (forward-char)
  4375. (skip-chars-backward "*")
  4376. (looking-at-p org-outline-regexp-bol))))
  4377. ;; Match full emphasis markup regexp.
  4378. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  4379. ;; Do not span over paragraph boundaries.
  4380. (not (string-match-p org-element-paragraph-separate
  4381. (match-string 2)))
  4382. ;; Do not span over cells in table rows.
  4383. (not (and (save-match-data (org-match-line "[ \t]*|"))
  4384. (string-match-p "|" (match-string 4))))))
  4385. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist))
  4386. (m (if org-hide-emphasis-markers 4 2)))
  4387. (font-lock-prepend-text-property
  4388. (match-beginning m) (match-end m) 'face face)
  4389. (when verbatim?
  4390. (org-remove-flyspell-overlays-in
  4391. (match-beginning 0) (match-end 0))
  4392. (when (and (org-fold-core-folding-spec-p 'org-link)
  4393. (org-fold-core-folding-spec-p 'org-link-description))
  4394. (org-fold-region (match-beginning 0) (match-end 0) nil 'org-link)
  4395. (org-fold-region (match-beginning 0) (match-end 0) nil 'org-link-description))
  4396. (remove-text-properties (match-beginning 2) (match-end 2)
  4397. '(display t invisible t intangible t)))
  4398. (add-text-properties (match-beginning 2) (match-end 2)
  4399. '(font-lock-multiline t org-emphasis t))
  4400. (when (and org-hide-emphasis-markers
  4401. (not (org-at-comment-p)))
  4402. (add-text-properties (match-end 4) (match-beginning 5)
  4403. '(invisible t))
  4404. (add-text-properties (match-beginning 3) (match-end 3)
  4405. '(invisible t)))
  4406. (throw :exit t))))))))
  4407. (defun org-emphasize (&optional char)
  4408. "Insert or change an emphasis, i.e. a font like bold or italic.
  4409. If there is an active region, change that region to a new emphasis.
  4410. If there is no region, just insert the marker characters and position
  4411. the cursor between them.
  4412. CHAR should be the marker character. If it is a space, it means to
  4413. remove the emphasis of the selected region.
  4414. If CHAR is not given (for example in an interactive call) it will be
  4415. prompted for."
  4416. (interactive)
  4417. (let ((erc org-emphasis-regexp-components)
  4418. (string "") beg end move s)
  4419. (if (org-region-active-p)
  4420. (setq beg (region-beginning)
  4421. end (region-end)
  4422. string (buffer-substring beg end))
  4423. (setq move t))
  4424. (unless char
  4425. (message "Emphasis marker or tag: [%s]"
  4426. (mapconcat #'car org-emphasis-alist ""))
  4427. (setq char (read-char-exclusive)))
  4428. (if (equal char ?\s)
  4429. (setq s ""
  4430. move nil)
  4431. (unless (assoc (char-to-string char) org-emphasis-alist)
  4432. (user-error "No such emphasis marker: \"%c\"" char))
  4433. (setq s (char-to-string char)))
  4434. (while (and (> (length string) 1)
  4435. (equal (substring string 0 1) (substring string -1))
  4436. (assoc (substring string 0 1) org-emphasis-alist))
  4437. (setq string (substring string 1 -1)))
  4438. (setq string (concat s string s))
  4439. (when beg (delete-region beg end))
  4440. (unless (or (bolp)
  4441. (string-match (concat "[" (nth 0 erc) "\n]")
  4442. (char-to-string (char-before (point)))))
  4443. (insert " "))
  4444. (unless (or (eobp)
  4445. (string-match (concat "[" (nth 1 erc) "\n]")
  4446. (char-to-string (char-after (point)))))
  4447. (insert " ") (backward-char 1))
  4448. (insert string)
  4449. (and move (backward-char 1))))
  4450. (defconst org-nonsticky-props
  4451. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  4452. (defsubst org-rear-nonsticky-at (pos)
  4453. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  4454. (defun org-activate-links--overlays (limit)
  4455. "Add link properties to links.
  4456. This includes angle, plain, and bracket links."
  4457. (catch :exit
  4458. (while (re-search-forward org-link-any-re limit t)
  4459. (let* ((start (match-beginning 0))
  4460. (end (match-end 0))
  4461. (visible-start (or (match-beginning 3) (match-beginning 2)))
  4462. (visible-end (or (match-end 3) (match-end 2)))
  4463. (style (cond ((eq ?< (char-after start)) 'angle)
  4464. ((eq ?\[ (char-after (1+ start))) 'bracket)
  4465. (t 'plain))))
  4466. (when (and (memq style org-highlight-links)
  4467. ;; Do not span over paragraph boundaries.
  4468. (not (string-match-p org-element-paragraph-separate
  4469. (match-string 0)))
  4470. ;; Do not confuse plain links with tags.
  4471. (not (and (eq style 'plain)
  4472. (let ((face (get-text-property
  4473. (max (1- start) (point-min)) 'face)))
  4474. (if (consp face) (memq 'org-tag face)
  4475. (eq 'org-tag face))))))
  4476. (let* ((link-object (save-excursion
  4477. (goto-char start)
  4478. (save-match-data (org-element-link-parser))))
  4479. (link (org-element-property :raw-link link-object))
  4480. (type (org-element-property :type link-object))
  4481. (path (org-element-property :path link-object))
  4482. (face-property (pcase (org-link-get-parameter type :face)
  4483. ((and (pred functionp) face) (funcall face path))
  4484. ((and (pred facep) face) face)
  4485. ((and (pred consp) face) face) ;anonymous
  4486. (_ 'org-link)))
  4487. (properties ;for link's visible part
  4488. (list 'mouse-face (or (org-link-get-parameter type :mouse-face)
  4489. 'highlight)
  4490. 'keymap (or (org-link-get-parameter type :keymap)
  4491. org-mouse-map)
  4492. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  4493. ((and (pred stringp) echo) echo)
  4494. ((and (pred functionp) echo) echo)
  4495. (_ (concat "LINK: " link)))
  4496. 'htmlize-link (pcase (org-link-get-parameter type
  4497. :htmlize-link)
  4498. ((and (pred functionp) f) (funcall f))
  4499. (_ `(:uri ,link)))
  4500. 'font-lock-multiline t)))
  4501. (org-remove-flyspell-overlays-in start end)
  4502. (org-rear-nonsticky-at end)
  4503. (if (not (eq 'bracket style))
  4504. (progn
  4505. (add-face-text-property start end face-property)
  4506. (add-text-properties start end properties))
  4507. ;; Handle invisible parts in bracket links.
  4508. (remove-text-properties start end '(invisible nil))
  4509. (let ((hidden
  4510. (append `(invisible
  4511. ,(or (org-link-get-parameter type :display)
  4512. 'org-link))
  4513. properties)))
  4514. (add-text-properties start visible-start hidden)
  4515. (add-face-text-property start end face-property)
  4516. (add-text-properties visible-start visible-end properties)
  4517. (add-text-properties visible-end end hidden)
  4518. (org-rear-nonsticky-at visible-start)
  4519. (org-rear-nonsticky-at visible-end)))
  4520. (let ((f (org-link-get-parameter type :activate-func)))
  4521. (when (functionp f)
  4522. (funcall f start end path (eq style 'bracket))))
  4523. (throw :exit t))))) ;signal success
  4524. nil))
  4525. (defun org-activate-links--text-properties (limit)
  4526. "Add link properties to links.
  4527. This includes angle, plain, and bracket links."
  4528. (catch :exit
  4529. (while (re-search-forward org-link-any-re limit t)
  4530. (let* ((start (match-beginning 0))
  4531. (end (match-end 0))
  4532. (visible-start (or (match-beginning 3) (match-beginning 2)))
  4533. (visible-end (or (match-end 3) (match-end 2)))
  4534. (style (cond ((eq ?< (char-after start)) 'angle)
  4535. ((eq ?\[ (char-after (1+ start))) 'bracket)
  4536. (t 'plain))))
  4537. (when (and (memq style org-highlight-links)
  4538. ;; Do not span over paragraph boundaries.
  4539. (not (string-match-p org-element-paragraph-separate
  4540. (match-string 0)))
  4541. ;; Do not confuse plain links with tags.
  4542. (not (and (eq style 'plain)
  4543. (let ((face (get-text-property
  4544. (max (1- start) (point-min)) 'face)))
  4545. (if (consp face) (memq 'org-tag face)
  4546. (eq 'org-tag face))))))
  4547. (let* ((link-object (save-excursion
  4548. (goto-char start)
  4549. (save-match-data (org-element-link-parser))))
  4550. (link (org-element-property :raw-link link-object))
  4551. (type (org-element-property :type link-object))
  4552. (path (org-element-property :path link-object))
  4553. (face-property (pcase (org-link-get-parameter type :face)
  4554. ((and (pred functionp) face) (funcall face path))
  4555. ((and (pred facep) face) face)
  4556. ((and (pred consp) face) face) ;anonymous
  4557. (_ 'org-link)))
  4558. (properties ;for link's visible part
  4559. (list 'mouse-face (or (org-link-get-parameter type :mouse-face)
  4560. 'highlight)
  4561. 'keymap (or (org-link-get-parameter type :keymap)
  4562. org-mouse-map)
  4563. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  4564. ((and (pred stringp) echo) echo)
  4565. ((and (pred functionp) echo) echo)
  4566. (_ (concat "LINK: " link)))
  4567. 'htmlize-link (pcase (org-link-get-parameter type
  4568. :htmlize-link)
  4569. ((and (pred functionp) f) (funcall f))
  4570. (_ `(:uri ,link)))
  4571. 'font-lock-multiline t)))
  4572. (org-remove-flyspell-overlays-in start end)
  4573. (org-rear-nonsticky-at end)
  4574. (if (not (eq 'bracket style))
  4575. (progn
  4576. (add-face-text-property start end face-property)
  4577. (add-text-properties start end properties))
  4578. ;; Initialise folding when used outside org-mode.
  4579. (unless (or (derived-mode-p 'org-mode)
  4580. (and (org-fold-folding-spec-p 'org-link-description)
  4581. (org-fold-folding-spec-p 'org-link)))
  4582. (org-fold-initialize (or (and (stringp org-ellipsis) (not (equal "" org-ellipsis)) org-ellipsis)
  4583. "...")))
  4584. ;; Handle invisible parts in bracket links.
  4585. (let ((spec (or (org-link-get-parameter type :display)
  4586. 'org-link)))
  4587. (unless (org-fold-folding-spec-p spec)
  4588. (org-fold-add-folding-spec spec
  4589. (cdr org-link--link-folding-spec)
  4590. nil
  4591. 'append)
  4592. (org-fold-core-set-folding-spec-property spec :visible t))
  4593. (org-fold-region start end nil 'org-link)
  4594. (org-fold-region start end nil 'org-link-description)
  4595. ;; We are folding the whole emphasised text with SPEC
  4596. ;; first. It makes everything invisible (or whatever
  4597. ;; the user wants).
  4598. (org-fold-region start end t spec)
  4599. ;; The visible part of the text is folded using
  4600. ;; 'org-link-description, which is forcing this part of
  4601. ;; the text to be visible.
  4602. (org-fold-region visible-start visible-end t 'org-link-description)
  4603. (add-text-properties start end properties)
  4604. (add-face-text-property start end face-property)
  4605. (org-rear-nonsticky-at visible-start)
  4606. (org-rear-nonsticky-at visible-end)))
  4607. (let ((f (org-link-get-parameter type :activate-func)))
  4608. (when (functionp f)
  4609. (funcall f start end path (eq style 'bracket))))
  4610. (throw :exit t))))) ;signal success
  4611. nil))
  4612. (defsubst org-activate-links (limit)
  4613. "Add link properties to links.
  4614. This includes angle, plain, and bracket links."
  4615. (if (eq org-fold-core-style 'text-properties)
  4616. (org-activate-links--text-properties limit)
  4617. (org-activate-links--overlays limit)))
  4618. (defun org-activate-code (limit)
  4619. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  4620. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4621. (remove-text-properties (match-beginning 0) (match-end 0)
  4622. '(display t invisible t intangible t))
  4623. t))
  4624. (defcustom org-src-fontify-natively t
  4625. "When non-nil, fontify code in code blocks.
  4626. See also the `org-block' face."
  4627. :type 'boolean
  4628. :version "26.1"
  4629. :package-version '(Org . "8.3")
  4630. :group 'org-appearance
  4631. :group 'org-babel)
  4632. (defcustom org-allow-promoting-top-level-subtree nil
  4633. "When non-nil, allow promoting a top level subtree.
  4634. The leading star of the top level headline will be replaced
  4635. by a #."
  4636. :type 'boolean
  4637. :version "24.1"
  4638. :group 'org-appearance)
  4639. (defun org-fontify-meta-lines-and-blocks (limit)
  4640. (condition-case nil
  4641. (org-fontify-meta-lines-and-blocks-1 limit)
  4642. (error (message "Org mode fontification error in %S at %d"
  4643. (current-buffer)
  4644. (line-number-at-pos)))))
  4645. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  4646. "Fontify #+ lines and blocks."
  4647. (let ((case-fold-search t))
  4648. (when (re-search-forward
  4649. (rx bol (group (zero-or-more (any " \t")) "#"
  4650. (group (group (or (seq "+" (one-or-more (any "a-zA-Z")) (optional ":"))
  4651. (any " \t")
  4652. eol))
  4653. (optional (group "_" (group (one-or-more (any "a-zA-Z"))))))
  4654. (zero-or-more (any " \t"))
  4655. (group (group (zero-or-more (not (any " \t\n"))))
  4656. (zero-or-more (any " \t"))
  4657. (group (zero-or-more any)))))
  4658. limit t)
  4659. (let ((beg (match-beginning 0))
  4660. (end-of-beginline (match-end 0))
  4661. ;; Including \n at end of #+begin line will include \n
  4662. ;; after the end of block content.
  4663. (block-start (match-end 0))
  4664. (block-end nil)
  4665. (lang (match-string 7)) ; The language, if it is a source block.
  4666. (bol-after-beginline (line-beginning-position 2))
  4667. (dc1 (downcase (match-string 2)))
  4668. (dc3 (downcase (match-string 3)))
  4669. (whole-blockline org-fontify-whole-block-delimiter-line)
  4670. beg-of-endline end-of-endline nl-before-endline quoting block-type)
  4671. (cond
  4672. ((and (match-end 4) (equal dc3 "+begin"))
  4673. ;; Truly a block
  4674. (setq block-type (downcase (match-string 5))
  4675. ;; Src, example, export, maybe more.
  4676. quoting (member block-type org-protecting-blocks))
  4677. (when (re-search-forward
  4678. (rx-to-string `(group bol (or (seq (one-or-more "*") space)
  4679. (seq (zero-or-more (any " \t"))
  4680. "#+end"
  4681. ,(match-string 4)
  4682. word-end
  4683. (zero-or-more any)))))
  4684. ;; We look further than LIMIT on purpose.
  4685. nil t)
  4686. ;; We do have a matching #+end line.
  4687. (setq beg-of-endline (match-beginning 0)
  4688. end-of-endline (match-end 0)
  4689. nl-before-endline (1- (match-beginning 0)))
  4690. (setq block-end (match-beginning 0)) ; Include the final newline.
  4691. (when quoting
  4692. (org-remove-flyspell-overlays-in bol-after-beginline nl-before-endline)
  4693. (remove-text-properties beg end-of-endline
  4694. '(display t invisible t intangible t)))
  4695. (add-text-properties
  4696. beg end-of-endline '(font-lock-fontified t font-lock-multiline t))
  4697. (org-remove-flyspell-overlays-in beg bol-after-beginline)
  4698. (org-remove-flyspell-overlays-in nl-before-endline end-of-endline)
  4699. (cond
  4700. ((and lang (not (string= lang "")) org-src-fontify-natively)
  4701. (save-match-data
  4702. (org-src-font-lock-fontify-block lang block-start block-end))
  4703. (add-text-properties bol-after-beginline block-end '(src-block t)))
  4704. (quoting
  4705. (add-text-properties
  4706. bol-after-beginline beg-of-endline
  4707. (list 'face
  4708. (list :inherit
  4709. (let ((face-name
  4710. (intern (format "org-block-%s" lang))))
  4711. (append (and (facep face-name) (list face-name))
  4712. '(org-block)))))))
  4713. ((not org-fontify-quote-and-verse-blocks))
  4714. ((string= block-type "quote")
  4715. (add-face-text-property
  4716. bol-after-beginline beg-of-endline 'org-quote t))
  4717. ((string= block-type "verse")
  4718. (add-face-text-property
  4719. bol-after-beginline beg-of-endline 'org-verse t)))
  4720. ;; Fontify the #+begin and #+end lines of the blocks
  4721. (add-text-properties
  4722. beg (if whole-blockline bol-after-beginline end-of-beginline)
  4723. '(face org-block-begin-line))
  4724. (unless (eq (char-after beg-of-endline) ?*)
  4725. (add-text-properties
  4726. beg-of-endline
  4727. (if whole-blockline
  4728. (let ((beg-of-next-line (1+ end-of-endline)))
  4729. (min (point-max) beg-of-next-line))
  4730. (min (point-max) end-of-endline))
  4731. '(face org-block-end-line)))
  4732. t))
  4733. ((member dc1 '("+title:" "+subtitle:" "+author:" "+email:" "+date:"))
  4734. (org-remove-flyspell-overlays-in
  4735. (match-beginning 0)
  4736. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  4737. (add-text-properties
  4738. beg (match-end 3)
  4739. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  4740. '(font-lock-fontified t invisible t)
  4741. '(font-lock-fontified t face org-document-info-keyword)))
  4742. (add-text-properties
  4743. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  4744. (if (string-equal dc1 "+title:")
  4745. '(font-lock-fontified t face org-document-title)
  4746. '(font-lock-fontified t face org-document-info))))
  4747. ((string-prefix-p "+caption" dc1)
  4748. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  4749. (remove-text-properties (match-beginning 0) (match-end 0)
  4750. '(display t invisible t intangible t))
  4751. ;; Handle short captions
  4752. (save-excursion
  4753. (beginning-of-line)
  4754. (looking-at (rx (group (zero-or-more (any " \t"))
  4755. "#+caption"
  4756. (optional "[" (zero-or-more any) "]")
  4757. ":")
  4758. (zero-or-more (any " \t")))))
  4759. (add-text-properties (line-beginning-position) (match-end 1)
  4760. '(font-lock-fontified t face org-meta-line))
  4761. (add-text-properties (match-end 0) (line-end-position)
  4762. '(font-lock-fontified t face org-block))
  4763. t)
  4764. ((member dc3 '(" " ""))
  4765. ;; Just a comment, the plus was not there
  4766. (org-remove-flyspell-overlays-in beg (match-end 0))
  4767. (add-text-properties
  4768. beg (match-end 0)
  4769. '(font-lock-fontified t face font-lock-comment-face)))
  4770. (t ;; Just any other in-buffer setting, but not indented
  4771. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4772. (remove-text-properties (match-beginning 0) (match-end 0)
  4773. '(display t invisible t intangible t))
  4774. (add-text-properties beg (match-end 0)
  4775. '(font-lock-fontified t face org-meta-line))
  4776. t))))))
  4777. (defun org-fontify-drawers (limit)
  4778. "Fontify drawers."
  4779. (when (re-search-forward org-drawer-regexp limit t)
  4780. (add-text-properties (1- (match-beginning 1)) (1+ (match-end 1))
  4781. '(font-lock-fontified t face org-drawer))
  4782. (org-remove-flyspell-overlays-in
  4783. (line-beginning-position) (line-beginning-position 2))
  4784. t))
  4785. (defun org-fontify-macros (limit)
  4786. "Fontify macros."
  4787. (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
  4788. (let ((begin (match-beginning 0))
  4789. (opening-end (match-beginning 1)))
  4790. (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
  4791. (match-string 1))
  4792. (let ((end (match-end 1))
  4793. (closing-start (match-beginning 1)))
  4794. (add-text-properties
  4795. begin end
  4796. '(font-lock-multiline t font-lock-fontified t face org-macro))
  4797. (org-remove-flyspell-overlays-in begin end)
  4798. (when org-hide-macro-markers
  4799. (add-text-properties begin opening-end '(invisible t))
  4800. (add-text-properties closing-start end '(invisible t)))
  4801. t)))))
  4802. (defun org-fontify-extend-region (beg end _old-len)
  4803. (let ((end (if (progn (goto-char end) (looking-at-p "^[*#]"))
  4804. (1+ end) end))
  4805. (begin-re "\\(\\\\\\[\\|\\(#\\+begin_\\|\\\\begin{\\)\\S-+\\)")
  4806. (end-re "\\(\\\\\\]\\|\\(#\\+end_\\|\\\\end{\\)\\S-+\\)")
  4807. (extend
  4808. (lambda (r1 r2 dir)
  4809. (let ((re (replace-regexp-in-string
  4810. "\\(begin\\|end\\)" r1
  4811. (replace-regexp-in-string
  4812. "[][]" r2
  4813. (match-string-no-properties 0)))))
  4814. (re-search-forward (regexp-quote re) nil t dir)))))
  4815. (goto-char beg)
  4816. (back-to-indentation)
  4817. (save-match-data
  4818. (cond ((looking-at end-re)
  4819. (cons (or (funcall extend "begin" "[" -1) beg) end))
  4820. ((looking-at begin-re)
  4821. (cons beg (or (funcall extend "end" "]" 1) end)))
  4822. (t (cons beg end))))))
  4823. (defun org-activate-footnote-links (limit)
  4824. "Add text properties for footnotes."
  4825. (let ((fn (org-footnote-next-reference-or-definition limit)))
  4826. (when fn
  4827. (let* ((beg (nth 1 fn))
  4828. (end (nth 2 fn))
  4829. (label (car fn))
  4830. (referencep (/= (line-beginning-position) beg)))
  4831. (when (and referencep (nth 3 fn))
  4832. (save-excursion
  4833. (goto-char beg)
  4834. (search-forward (or label "fn:"))
  4835. (org-remove-flyspell-overlays-in beg (match-end 0))))
  4836. (add-text-properties beg end
  4837. (list 'mouse-face 'highlight
  4838. 'keymap org-mouse-map
  4839. 'help-echo
  4840. (if referencep "Footnote reference"
  4841. "Footnote definition")
  4842. 'font-lock-fontified t
  4843. 'font-lock-multiline t
  4844. 'face 'org-footnote))))))
  4845. (defun org-activate-dates (limit)
  4846. "Add text properties for dates."
  4847. (when (and (re-search-forward org-tsr-regexp-both limit t)
  4848. (not (equal (char-before (match-beginning 0)) 91)))
  4849. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4850. (add-text-properties (match-beginning 0) (match-end 0)
  4851. (list 'mouse-face 'highlight
  4852. 'keymap org-mouse-map))
  4853. (org-rear-nonsticky-at (match-end 0))
  4854. (when org-display-custom-times
  4855. ;; If it's a date range, activate custom time for second date.
  4856. (when (match-end 3)
  4857. (org-display-custom-time (match-beginning 3) (match-end 3)))
  4858. (org-display-custom-time (match-beginning 1) (match-end 1)))
  4859. t))
  4860. (defun org-activate-target-links (limit)
  4861. "Add text properties for target matches."
  4862. (when org-target-link-regexp
  4863. (let ((case-fold-search t))
  4864. ;; `org-target-link-regexp' matches one character before the
  4865. ;; actual target.
  4866. (unless (bolp) (forward-char -1))
  4867. (when (re-search-forward org-target-link-regexp limit t)
  4868. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4869. (add-text-properties (match-beginning 1) (match-end 1)
  4870. (list 'mouse-face 'highlight
  4871. 'keymap org-mouse-map
  4872. 'help-echo "Radio target link"
  4873. 'org-linked-text t))
  4874. (org-rear-nonsticky-at (match-end 1))
  4875. t))))
  4876. (defvar org-latex-and-related-regexp nil
  4877. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  4878. (defun org-compute-latex-and-related-regexp ()
  4879. "Compute regular expression for LaTeX, entities and sub/superscript.
  4880. Result depends on variable `org-highlight-latex-and-related'."
  4881. (let ((re-sub
  4882. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  4883. ((eq org-use-sub-superscripts '{})
  4884. (list org-match-substring-with-braces-regexp))
  4885. (org-use-sub-superscripts (list org-match-substring-regexp))))
  4886. (re-latex
  4887. (when (or (memq 'latex org-highlight-latex-and-related)
  4888. (memq 'native org-highlight-latex-and-related))
  4889. (let ((matchers (plist-get org-format-latex-options :matchers)))
  4890. (delq nil
  4891. (mapcar (lambda (x)
  4892. (and (member (car x) matchers) (nth 1 x)))
  4893. org-latex-regexps)))))
  4894. (re-entities
  4895. (when (memq 'entities org-highlight-latex-and-related)
  4896. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\
  4897. \\($\\|{}\\|[^[:alpha:]]\\)"))))
  4898. (setq-local org-latex-and-related-regexp
  4899. (mapconcat #'identity
  4900. (append re-latex re-entities re-sub)
  4901. "\\|"))))
  4902. (defun org-do-latex-and-related (limit)
  4903. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  4904. Stop at first highlighted object, if any. Return t if some
  4905. highlighting was done, nil otherwise."
  4906. (when (org-string-nw-p org-latex-and-related-regexp)
  4907. (let ((latex-prefix-re (rx (or "$" "\\(" "\\[")))
  4908. (blank-line-re (rx (and "\n" (zero-or-more (or " " "\t")) "\n"))))
  4909. (catch 'found
  4910. (while (and (< (point) limit)
  4911. (re-search-forward org-latex-and-related-regexp nil t))
  4912. (cond
  4913. ((>= (match-beginning 0) limit)
  4914. (throw 'found nil))
  4915. ((cl-some (lambda (f)
  4916. (memq f '(org-code org-verbatim underline
  4917. org-special-keyword)))
  4918. (save-excursion
  4919. (goto-char (1+ (match-beginning 0)))
  4920. (face-at-point nil t))))
  4921. ;; Try to limit false positives. In this case, ignore
  4922. ;; $$...$$, \(...\), and \[...\] LaTeX constructs if they
  4923. ;; contain an empty line.
  4924. ((save-excursion
  4925. (goto-char (match-beginning 0))
  4926. (and (looking-at-p latex-prefix-re)
  4927. (save-match-data
  4928. (re-search-forward blank-line-re (1- (match-end 0)) t)))))
  4929. (t
  4930. (let* ((offset (if (memq (char-after (1+ (match-beginning 0)))
  4931. '(?_ ?^))
  4932. 1
  4933. 0))
  4934. (start (+ offset (match-beginning 0)))
  4935. (end (match-end 0)))
  4936. (if (memq 'native org-highlight-latex-and-related)
  4937. (org-src-font-lock-fontify-block "latex" start end)
  4938. (font-lock-prepend-text-property start end
  4939. 'face 'org-latex-and-related))
  4940. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  4941. '(font-lock-multiline t))
  4942. (throw 'found t)))))
  4943. nil))))
  4944. (defun org-restart-font-lock ()
  4945. "Restart `font-lock-mode', to force refontification."
  4946. (when font-lock-mode
  4947. (font-lock-mode -1)
  4948. (font-lock-mode 1)))
  4949. (defun org-activate-tags (limit)
  4950. (when (re-search-forward org-tag-line-re limit t)
  4951. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4952. (add-text-properties (match-beginning 1) (match-end 1)
  4953. (list 'mouse-face 'highlight
  4954. 'keymap org-mouse-map))
  4955. (org-rear-nonsticky-at (match-end 1))
  4956. t))
  4957. (defun org-outline-level ()
  4958. "Compute the outline level of the heading at point.
  4959. If this is called at a normal headline, the level is the number
  4960. of stars. Use `org-reduced-level' to remove the effect of
  4961. `org-odd-levels'. Unlike to `org-current-level', this function
  4962. takes into consideration inlinetasks."
  4963. (org-with-wide-buffer
  4964. (end-of-line)
  4965. (if (re-search-backward org-outline-regexp-bol nil t)
  4966. (1- (- (match-end 0) (match-beginning 0)))
  4967. 0)))
  4968. (defvar org-font-lock-keywords nil)
  4969. (defsubst org-re-property (property &optional literal allow-null value)
  4970. "Return a regexp matching a PROPERTY line.
  4971. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  4972. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  4973. non-nil, match properties even without a value.
  4974. Match group 3 is set to the value when it exists. If there is no
  4975. value and ALLOW-NULL is non-nil, it is set to the empty string.
  4976. With optional argument VALUE, match only property lines with
  4977. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  4978. unless LITERAL is non-nil."
  4979. (concat
  4980. "^\\(?4:[ \t]*\\)"
  4981. (format "\\(?1::\\(?2:%s\\):\\)"
  4982. (if literal property (regexp-quote property)))
  4983. (cond (value
  4984. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  4985. (if literal value (regexp-quote value))))
  4986. (allow-null
  4987. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  4988. (t
  4989. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  4990. (defconst org-property-re
  4991. (org-re-property "\\S-+" 'literal t)
  4992. "Regular expression matching a property line.
  4993. There are four matching groups:
  4994. 1: :PROPKEY: including the leading and trailing colon,
  4995. 2: PROPKEY without the leading and trailing colon,
  4996. 3: PROPVAL without leading or trailing spaces,
  4997. 4: the indentation of the current line,
  4998. 5: trailing whitespace.")
  4999. (defvar org-font-lock-hook nil
  5000. "Functions to be called for special font lock stuff.")
  5001. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  5002. (defvar org-font-lock-set-keywords-hook nil
  5003. "Functions that can manipulate `org-font-lock-extra-keywords'.
  5004. This is called after `org-font-lock-extra-keywords' is defined, but before
  5005. it is installed to be used by font lock. This can be useful if something
  5006. needs to be inserted at a specific position in the font-lock sequence.")
  5007. (defun org-font-lock-hook (limit)
  5008. "Run `org-font-lock-hook' within LIMIT."
  5009. (run-hook-with-args 'org-font-lock-hook limit))
  5010. (defun org-set-font-lock-defaults ()
  5011. "Set font lock defaults for the current buffer."
  5012. (let ((org-font-lock-extra-keywords
  5013. (list
  5014. ;; Call the hook
  5015. '(org-font-lock-hook)
  5016. ;; Headlines
  5017. `(,(if org-fontify-whole-heading-line
  5018. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  5019. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  5020. (1 (org-get-level-face 1))
  5021. (2 (org-get-level-face 2))
  5022. (3 (org-get-level-face 3)))
  5023. ;; Table lines
  5024. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  5025. (1 'org-table t))
  5026. ;; Table internals
  5027. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  5028. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  5029. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  5030. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  5031. ;; Properties
  5032. (list org-property-re
  5033. '(1 'org-special-keyword t)
  5034. '(3 'org-property-value t))
  5035. ;; Drawers
  5036. '(org-fontify-drawers)
  5037. ;; Link related fontification.
  5038. '(org-activate-links)
  5039. (when (memq 'tag org-highlight-links) '(org-activate-tags (1 'org-tag prepend)))
  5040. (when (memq 'radio org-highlight-links) '(org-activate-target-links (1 'org-link t)))
  5041. (when (memq 'date org-highlight-links) '(org-activate-dates (0 'org-date t)))
  5042. (when (memq 'footnote org-highlight-links) '(org-activate-footnote-links))
  5043. ;; Targets.
  5044. (list org-radio-target-regexp '(0 'org-target t))
  5045. (list org-target-regexp '(0 'org-target t))
  5046. ;; Diary sexps.
  5047. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5048. ;; Macro
  5049. '(org-fontify-macros)
  5050. ;; TODO keyword
  5051. (list (format org-heading-keyword-regexp-format
  5052. org-todo-regexp)
  5053. '(2 (org-get-todo-face 2) prepend))
  5054. ;; TODO
  5055. (when org-fontify-todo-headline
  5056. (list (format org-heading-keyword-regexp-format
  5057. (concat
  5058. "\\(?:"
  5059. (mapconcat 'regexp-quote org-not-done-keywords "\\|")
  5060. "\\)"))
  5061. '(2 'org-headline-todo prepend)))
  5062. ;; DONE
  5063. (when org-fontify-done-headline
  5064. (list (format org-heading-keyword-regexp-format
  5065. (concat
  5066. "\\(?:"
  5067. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5068. "\\)"))
  5069. '(2 'org-headline-done prepend)))
  5070. ;; Priorities
  5071. '(org-font-lock-add-priority-faces)
  5072. ;; Tags
  5073. '(org-font-lock-add-tag-faces)
  5074. ;; Tags groups
  5075. (when (and org-group-tags org-tag-groups-alist)
  5076. (list (concat org-outline-regexp-bol ".+\\(:"
  5077. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5078. ":\\).*$")
  5079. '(1 'org-tag-group prepend)))
  5080. ;; Special keywords
  5081. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5082. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5083. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5084. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5085. ;; Emphasis
  5086. (when org-fontify-emphasized-text '(org-do-emphasis-faces))
  5087. ;; Checkboxes
  5088. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5089. 1 'org-checkbox prepend)
  5090. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5091. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5092. (0 (org-get-checkbox-statistics-face) prepend)))
  5093. ;; Description list items
  5094. '("\\(?:^[ \t]*[-+]\\|^[ \t]+[*]\\)[ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5095. 1 'org-list-dt prepend)
  5096. ;; Inline export snippets
  5097. '("\\(@@\\)\\([a-z-]+:\\).*?\\(@@\\)"
  5098. (1 'font-lock-comment-face t)
  5099. (2 'org-tag t)
  5100. (3 'font-lock-comment-face t))
  5101. ;; ARCHIVEd headings
  5102. (list (concat
  5103. org-outline-regexp-bol
  5104. "\\(.*:" org-archive-tag ":.*\\)")
  5105. '(1 'org-archived prepend))
  5106. ;; Specials
  5107. '(org-do-latex-and-related)
  5108. '(org-fontify-entities)
  5109. '(org-raise-scripts)
  5110. ;; Code
  5111. '(org-activate-code (1 'org-code t))
  5112. ;; COMMENT
  5113. (list (format
  5114. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5115. org-todo-regexp
  5116. org-comment-string)
  5117. '(9 'org-special-keyword t))
  5118. ;; Blocks and meta lines
  5119. '(org-fontify-meta-lines-and-blocks)
  5120. '(org-fontify-inline-src-blocks)
  5121. ;; Citations. When an activate processor is specified, if
  5122. ;; specified, try loading it beforehand.
  5123. (progn
  5124. (unless (null org-cite-activate-processor)
  5125. (org-cite-try-load-processor org-cite-activate-processor))
  5126. '(org-cite-activate)))))
  5127. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5128. (run-hooks 'org-font-lock-set-keywords-hook)
  5129. ;; Now set the full font-lock-keywords
  5130. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5131. (setq-local font-lock-defaults
  5132. '(org-font-lock-keywords t nil nil backward-paragraph))
  5133. (setq-local font-lock-extend-after-change-region-function
  5134. #'org-fontify-extend-region)
  5135. (kill-local-variable 'font-lock-keywords)
  5136. nil))
  5137. (defun org-toggle-pretty-entities ()
  5138. "Toggle the composition display of entities as UTF8 characters."
  5139. (interactive)
  5140. (setq-local org-pretty-entities (not org-pretty-entities))
  5141. (org-restart-font-lock)
  5142. (if org-pretty-entities
  5143. (message "Entities are now displayed as UTF8 characters")
  5144. (save-restriction
  5145. (widen)
  5146. (decompose-region (point-min) (point-max))
  5147. (message "Entities are now displayed as plain text"))))
  5148. (defvar-local org-custom-properties-overlays nil
  5149. "List of overlays used for custom properties.")
  5150. (defun org-toggle-custom-properties-visibility ()
  5151. "Display or hide properties in `org-custom-properties'."
  5152. (interactive)
  5153. (if org-custom-properties-overlays
  5154. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5155. (setq org-custom-properties-overlays nil))
  5156. (when org-custom-properties
  5157. (org-with-wide-buffer
  5158. (goto-char (point-min))
  5159. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5160. (while (re-search-forward regexp nil t)
  5161. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5162. (when (and end (< (point) end))
  5163. ;; Hide first custom property in current drawer.
  5164. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5165. (overlay-put o 'invisible t)
  5166. (overlay-put o 'org-custom-property t)
  5167. (push o org-custom-properties-overlays))
  5168. ;; Hide additional custom properties in the same drawer.
  5169. (while (re-search-forward regexp end t)
  5170. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5171. (overlay-put o 'invisible t)
  5172. (overlay-put o 'org-custom-property t)
  5173. (push o org-custom-properties-overlays)))))
  5174. ;; Each entry is limited to a single property drawer.
  5175. (outline-next-heading)))))))
  5176. (defun org-fontify-entities (limit)
  5177. "Find an entity to fontify."
  5178. (let (ee)
  5179. (when org-pretty-entities
  5180. (catch 'match
  5181. ;; "\_ "-family is left out on purpose. Only the first one,
  5182. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5183. ;; confusing when adding a second white space character.
  5184. (while (re-search-forward
  5185. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5186. limit t)
  5187. (when (and (not (org-at-comment-p))
  5188. (setq ee (org-entity-get (match-string 1)))
  5189. (= (length (nth 6 ee)) 1))
  5190. (let* ((end (if (equal (match-string 2) "{}")
  5191. (match-end 2)
  5192. (match-end 1))))
  5193. (add-text-properties
  5194. (match-beginning 0) end
  5195. (list 'font-lock-fontified t))
  5196. (compose-region (match-beginning 0) end
  5197. (nth 6 ee) nil)
  5198. (backward-char 1)
  5199. (throw 'match t))))
  5200. nil))))
  5201. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5202. "Fontify string S like in Org mode."
  5203. (with-temp-buffer
  5204. (insert s)
  5205. (let ((org-odd-levels-only odd-levels))
  5206. (org-mode)
  5207. (font-lock-ensure)
  5208. (if org-link-descriptive
  5209. (org-link-display-format
  5210. (buffer-string))
  5211. (buffer-string)))))
  5212. (defun org-get-level-face (n)
  5213. "Get the right face for match N in font-lock matching of headlines."
  5214. (let* ((org-l0 (- (match-end 2) (match-beginning 1) 1))
  5215. (org-l (if org-odd-levels-only (1+ (/ org-l0 2)) org-l0))
  5216. (org-f (if org-cycle-level-faces
  5217. (nth (% (1- org-l) org-n-level-faces) org-level-faces)
  5218. (nth (1- (min org-l org-n-level-faces)) org-level-faces))))
  5219. (cond
  5220. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5221. ((eq n 2) org-f)
  5222. (t (unless org-level-color-stars-only org-f)))))
  5223. (defun org-face-from-face-or-color (context inherit face-or-color)
  5224. "Create a face list that inherits INHERIT, but sets the foreground color.
  5225. When FACE-OR-COLOR is not a string, just return it."
  5226. (if (stringp face-or-color)
  5227. (list :inherit inherit
  5228. (cdr (assoc context org-faces-easy-properties))
  5229. face-or-color)
  5230. face-or-color))
  5231. (defun org-get-todo-face (kwd)
  5232. "Get the right face for a TODO keyword KWD.
  5233. If KWD is a number, get the corresponding match group."
  5234. (when (numberp kwd) (setq kwd (match-string kwd)))
  5235. (or (org-face-from-face-or-color
  5236. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5237. (and (member kwd org-done-keywords) 'org-done)
  5238. 'org-todo))
  5239. (defun org-get-priority-face (priority)
  5240. "Get the right face for PRIORITY.
  5241. PRIORITY is a character."
  5242. (or (org-face-from-face-or-color
  5243. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5244. 'org-priority))
  5245. (defun org-get-tag-face (tag)
  5246. "Get the right face for TAG.
  5247. If TAG is a number, get the corresponding match group."
  5248. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5249. (or (org-face-from-face-or-color
  5250. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5251. 'org-tag)))
  5252. (defvar org-priority-regexp) ; defined later in the file
  5253. (defun org-font-lock-add-priority-faces (limit)
  5254. "Add the special priority faces."
  5255. (while (re-search-forward (concat "^\\*+" org-priority-regexp) limit t)
  5256. (let ((beg (match-beginning 1))
  5257. (end (1+ (match-end 2))))
  5258. (add-face-text-property
  5259. beg end
  5260. (org-get-priority-face (string-to-char (match-string 2))))
  5261. (add-text-properties
  5262. beg end
  5263. (list 'font-lock-fontified t)))))
  5264. (defun org-font-lock-add-tag-faces (limit)
  5265. "Add the special tag faces."
  5266. (when (and org-tag-faces org-tags-special-faces-re)
  5267. (while (re-search-forward org-tags-special-faces-re limit t)
  5268. (add-face-text-property
  5269. (match-beginning 1)
  5270. (match-end 1)
  5271. (org-get-tag-face 1))
  5272. (add-text-properties (match-beginning 1) (match-end 1)
  5273. (list 'font-lock-fontified t))
  5274. (backward-char 1))))
  5275. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5276. "Remove fontification and activation overlays from links."
  5277. (font-lock-default-unfontify-region beg end)
  5278. (with-silent-modifications
  5279. (decompose-region beg end)
  5280. (remove-text-properties beg end
  5281. '(mouse-face t keymap t org-linked-text t
  5282. invisible t intangible t
  5283. org-emphasis t))
  5284. (org-fold-region beg end nil 'org-link)
  5285. (org-fold-region beg end nil 'org-link-description)
  5286. (org-fold-core-update-optimisation beg end)
  5287. (org-remove-font-lock-display-properties beg end)))
  5288. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5289. ((raise 0.3) (height 0.7))
  5290. ((raise -0.5))
  5291. ((raise 0.5)))
  5292. "Display properties for showing superscripts and subscripts.")
  5293. (defun org-remove-font-lock-display-properties (beg end)
  5294. "Remove specific display properties that have been added by font lock.
  5295. The will remove the raise properties that are used to show superscripts
  5296. and subscripts."
  5297. (let (next prop)
  5298. (while (< beg end)
  5299. (setq next (next-single-property-change beg 'display nil end)
  5300. prop (get-text-property beg 'display))
  5301. (when (member prop org-script-display)
  5302. (put-text-property beg next 'display nil))
  5303. (setq beg next))))
  5304. (defun org-raise-scripts (limit)
  5305. "Add raise properties to sub/superscripts."
  5306. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5307. (re-search-forward
  5308. (if (eq org-use-sub-superscripts t)
  5309. org-match-substring-regexp
  5310. org-match-substring-with-braces-regexp)
  5311. limit t))
  5312. (let* ((pos (point)) table-p comment-p
  5313. (mpos (match-beginning 3))
  5314. (emph-p (get-text-property mpos 'org-emphasis))
  5315. (link-p (get-text-property mpos 'mouse-face))
  5316. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5317. (goto-char (line-beginning-position))
  5318. (setq table-p (looking-at-p org-table-dataline-regexp)
  5319. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5320. (goto-char pos)
  5321. ;; Handle a_b^c
  5322. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5323. (unless (or comment-p emph-p link-p keyw-p)
  5324. (put-text-property (match-beginning 3) (match-end 0)
  5325. 'display
  5326. (if (equal (char-after (match-beginning 2)) ?^)
  5327. (nth (if table-p 3 1) org-script-display)
  5328. (nth (if table-p 2 0) org-script-display)))
  5329. (put-text-property (match-beginning 2) (match-end 3)
  5330. 'org-emphasis t)
  5331. (add-text-properties (match-beginning 2) (match-end 2)
  5332. (list 'invisible t))
  5333. (when (and (eq (char-after (match-beginning 3)) ?{)
  5334. (eq (char-before (match-end 3)) ?}))
  5335. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5336. (list 'invisible t))
  5337. (add-text-properties (1- (match-end 3)) (match-end 3)
  5338. (list 'invisible t))))
  5339. t)))
  5340. (defun org-remove-empty-overlays-at (pos)
  5341. "Remove outline overlays that do not contain non-white stuff."
  5342. (dolist (o (overlays-at pos))
  5343. (and (eq 'outline (overlay-get o 'invisible))
  5344. (not (string-match-p
  5345. "\\S-" (buffer-substring (overlay-start o)
  5346. (overlay-end o))))
  5347. (delete-overlay o))))
  5348. ;; FIXME: This function is unused.
  5349. (defun org-show-empty-lines-in-parent ()
  5350. "Move to the parent and re-show empty lines before visible headlines."
  5351. (save-excursion
  5352. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  5353. (org-cycle-show-empty-lines context))))
  5354. (defun org-files-list ()
  5355. "Return `org-agenda-files' list, plus all open Org files.
  5356. This is useful for operations that need to scan all of a user's
  5357. open and agenda-wise Org files."
  5358. (let ((files (mapcar #'expand-file-name (org-agenda-files))))
  5359. (dolist (buf (buffer-list))
  5360. (with-current-buffer buf
  5361. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  5362. (cl-pushnew (expand-file-name (buffer-file-name)) files
  5363. :test #'equal))))
  5364. files))
  5365. (defsubst org-entry-beginning-position ()
  5366. "Return the beginning position of the current entry."
  5367. (save-excursion (org-back-to-heading t) (point)))
  5368. (defsubst org-entry-end-position ()
  5369. "Return the end position of the current entry."
  5370. (save-excursion (outline-next-heading) (point)))
  5371. (defun org-subtree-end-visible-p ()
  5372. "Is the end of the current subtree visible?"
  5373. (pos-visible-in-window-p
  5374. (save-excursion (org-end-of-subtree t) (point))))
  5375. (defun org-first-headline-recenter ()
  5376. "Move cursor to the first headline and recenter the headline."
  5377. (let ((window (get-buffer-window)))
  5378. (when window
  5379. (goto-char (point-min))
  5380. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  5381. (set-window-start window (line-beginning-position))))))
  5382. ;; FIXME: It was in the middle of visibility section. Where should it go to?
  5383. (defvar org-called-with-limited-levels nil
  5384. "Non-nil when `org-with-limited-levels' is currently active.")
  5385. ;;; Indirect buffer display of subtrees
  5386. (defvar org-indirect-dedicated-frame nil
  5387. "This is the frame being used for indirect tree display.")
  5388. (defvar org-last-indirect-buffer nil)
  5389. (defun org-tree-to-indirect-buffer (&optional arg)
  5390. "Create indirect buffer and narrow it to current subtree.
  5391. With a numerical prefix ARG, go up to this level and then take that tree.
  5392. If ARG is negative, go up that many levels.
  5393. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  5394. indirect buffer previously made with this command, to avoid proliferation of
  5395. indirect buffers. However, when you call the command with a \
  5396. `\\[universal-argument]' prefix, or
  5397. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  5398. so that you can work with several indirect buffers at the same time. If
  5399. `org-indirect-buffer-display' is `dedicated-frame', the \
  5400. `\\[universal-argument]' prefix also
  5401. requests that a new frame be made for the new buffer, so that the dedicated
  5402. frame is not changed."
  5403. (interactive "P")
  5404. (let ((cbuf (current-buffer))
  5405. (cwin (selected-window))
  5406. (pos (point))
  5407. beg end level heading ibuf)
  5408. (save-excursion
  5409. (org-back-to-heading t)
  5410. (when (numberp arg)
  5411. (setq level (org-outline-level))
  5412. (when (< arg 0) (setq arg (+ level arg)))
  5413. (while (> (setq level (org-outline-level)) arg)
  5414. (org-up-heading-safe)))
  5415. (setq beg (point)
  5416. heading (org-get-heading 'no-tags))
  5417. (org-end-of-subtree t t)
  5418. (when (and (not (eobp)) (org-at-heading-p)) (backward-char 1))
  5419. (setq end (point)))
  5420. (when (and (buffer-live-p org-last-indirect-buffer)
  5421. (not (eq org-indirect-buffer-display 'new-frame))
  5422. (not arg))
  5423. (kill-buffer org-last-indirect-buffer))
  5424. (setq ibuf (org-get-indirect-buffer cbuf heading)
  5425. org-last-indirect-buffer ibuf)
  5426. (cond
  5427. ((or (eq org-indirect-buffer-display 'new-frame)
  5428. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  5429. (select-frame (make-frame))
  5430. (delete-other-windows)
  5431. (pop-to-buffer-same-window ibuf)
  5432. (org-set-frame-title heading))
  5433. ((eq org-indirect-buffer-display 'dedicated-frame)
  5434. (raise-frame
  5435. (select-frame (or (and org-indirect-dedicated-frame
  5436. (frame-live-p org-indirect-dedicated-frame)
  5437. org-indirect-dedicated-frame)
  5438. (setq org-indirect-dedicated-frame (make-frame)))))
  5439. (delete-other-windows)
  5440. (pop-to-buffer-same-window ibuf)
  5441. (org-set-frame-title (concat "Indirect: " heading)))
  5442. ((eq org-indirect-buffer-display 'current-window)
  5443. (pop-to-buffer-same-window ibuf))
  5444. ((eq org-indirect-buffer-display 'other-window)
  5445. (pop-to-buffer ibuf))
  5446. (t (error "Invalid value")))
  5447. (narrow-to-region beg end)
  5448. (org-fold-show-all '(headings drawers blocks))
  5449. (goto-char pos)
  5450. (run-hook-with-args 'org-cycle-hook 'all)
  5451. (and (window-live-p cwin) (select-window cwin))))
  5452. (defun org-get-indirect-buffer (&optional buffer heading)
  5453. (setq buffer (or buffer (current-buffer)))
  5454. (let ((n 1) (base (buffer-name buffer)) bname)
  5455. (while (buffer-live-p
  5456. (get-buffer
  5457. (setq bname
  5458. (concat base "-"
  5459. (if heading (concat heading "-" (number-to-string n))
  5460. (number-to-string n))))))
  5461. (setq n (1+ n)))
  5462. (condition-case nil
  5463. (let ((indirect-buffer (make-indirect-buffer buffer bname 'clone)))
  5464. ;; Decouple folding state. We need to do it manually since
  5465. ;; `make-indirect-buffer' does not run
  5466. ;; `clone-indirect-buffer-hook'.
  5467. (org-fold-core-decouple-indirect-buffer-folds)
  5468. ;; Return the buffer.
  5469. indirect-buffer)
  5470. (error (make-indirect-buffer buffer bname)))))
  5471. (defun org-set-frame-title (title)
  5472. "Set the title of the current frame to the string TITLE."
  5473. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  5474. ;;;; Structure editing
  5475. ;;; Inserting headlines
  5476. (defun org--blank-before-heading-p (&optional parent)
  5477. "Non-nil when an empty line should precede a new heading here.
  5478. When optional argument PARENT is non-nil, consider parent
  5479. headline instead of current one."
  5480. (pcase (assq 'heading org-blank-before-new-entry)
  5481. (`(heading . auto)
  5482. (save-excursion
  5483. (org-with-limited-levels
  5484. (unless (and (org-before-first-heading-p)
  5485. (not (outline-next-heading)))
  5486. (org-back-to-heading t)
  5487. (when parent (org-up-heading-safe))
  5488. (cond ((not (bobp))
  5489. (org-previous-line-empty-p))
  5490. ((outline-next-heading)
  5491. (org-previous-line-empty-p))
  5492. ;; Ignore trailing spaces on last buffer line.
  5493. ((progn (skip-chars-backward " \t") (bolp))
  5494. (org-previous-line-empty-p))
  5495. (t nil))))))
  5496. (`(heading . ,value) value)
  5497. (_ nil)))
  5498. (defun org-insert-heading (&optional arg invisible-ok top)
  5499. "Insert a new heading or an item with the same depth at point.
  5500. If point is at the beginning of a heading, insert a new heading
  5501. or a new headline above the current one. When at the beginning
  5502. of a regular line of text, turn it into a heading.
  5503. If point is in the middle of a line, split it and create a new
  5504. headline with the text in the current line after point (see
  5505. `org-M-RET-may-split-line' on how to modify this behavior). As
  5506. a special case, on a headline, splitting can only happen on the
  5507. title itself. E.g., this excludes breaking stars or tags.
  5508. With a `\\[universal-argument]' prefix, set \
  5509. `org-insert-heading-respect-content' to
  5510. a non-nil value for the duration of the command. This forces the
  5511. insertion of a heading after the current subtree, independently
  5512. on the location of point.
  5513. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  5514. insert the heading at the end of the tree
  5515. above the current heading. For example, if point is within a
  5516. 2nd-level heading, then it will insert a 2nd-level heading at
  5517. the end of the 1st-level parent subtree.
  5518. When INVISIBLE-OK is set, stop at invisible headlines when going
  5519. back. This is important for non-interactive uses of the
  5520. command.
  5521. When optional argument TOP is non-nil, insert a level 1 heading,
  5522. unconditionally."
  5523. (interactive "P")
  5524. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  5525. (level (org-current-level))
  5526. (stars (make-string (if (and level (not top)) level 1) ?*)))
  5527. (cond
  5528. ((or org-insert-heading-respect-content
  5529. (member arg '((4) (16)))
  5530. (and (not invisible-ok)
  5531. (invisible-p (max (1- (point)) (point-min)))))
  5532. ;; Position point at the location of insertion. Make sure we
  5533. ;; end up on a visible headline if INVISIBLE-OK is nil.
  5534. (org-with-limited-levels
  5535. (if (not level) (outline-next-heading) ;before first headline
  5536. (org-back-to-heading invisible-ok)
  5537. (when (equal arg '(16)) (org-up-heading-safe))
  5538. (org-end-of-subtree)))
  5539. (unless (bolp) (insert "\n"))
  5540. (when (and blank? (save-excursion
  5541. (backward-char)
  5542. (org-before-first-heading-p)))
  5543. (insert "\n")
  5544. (backward-char))
  5545. (when (and (not level) (not (eobp)) (not (bobp)))
  5546. (when (org-at-heading-p) (insert "\n"))
  5547. (backward-char))
  5548. (unless (and blank? (org-previous-line-empty-p))
  5549. (org-N-empty-lines-before-current (if blank? 1 0)))
  5550. (insert stars " ")
  5551. ;; When INVISIBLE-OK is non-nil, ensure newly created headline
  5552. ;; is visible.
  5553. (unless invisible-ok
  5554. (if (eq org-fold-core-style 'text-properties)
  5555. (cond
  5556. ((org-fold-folded-p
  5557. (max (point-min)
  5558. (1- (line-beginning-position)))
  5559. 'headline)
  5560. (org-fold-region (line-end-position 0) (line-end-position) nil 'headline))
  5561. (t nil))
  5562. (pcase (get-char-property-and-overlay (point) 'invisible)
  5563. (`(outline . ,o)
  5564. (move-overlay o (overlay-start o) (line-end-position 0)))
  5565. (_ nil)))))
  5566. ;; At a headline...
  5567. ((org-at-heading-p)
  5568. (cond ((bolp)
  5569. (when blank? (save-excursion (insert "\n")))
  5570. (save-excursion (insert stars " \n"))
  5571. (unless (and blank? (org-previous-line-empty-p))
  5572. (org-N-empty-lines-before-current (if blank? 1 0)))
  5573. (end-of-line))
  5574. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  5575. (org-match-line org-complex-heading-regexp)
  5576. (org-pos-in-match-range (point) 4))
  5577. ;; Grab the text that should moved to the new headline.
  5578. ;; Preserve tags.
  5579. (let ((split (delete-and-extract-region (point) (match-end 4))))
  5580. (if (looking-at "[ \t]*$") (replace-match "")
  5581. (org-align-tags))
  5582. (end-of-line)
  5583. (when blank? (insert "\n"))
  5584. (insert "\n" stars " ")
  5585. (when (org-string-nw-p split) (insert split))))
  5586. (t
  5587. (end-of-line)
  5588. (when blank? (insert "\n"))
  5589. (insert "\n" stars " "))))
  5590. ;; On regular text, turn line into a headline or split, if
  5591. ;; appropriate.
  5592. ((bolp)
  5593. (insert stars " ")
  5594. (unless (and blank? (org-previous-line-empty-p))
  5595. (org-N-empty-lines-before-current (if blank? 1 0))))
  5596. (t
  5597. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  5598. (end-of-line))
  5599. (insert "\n" stars " ")
  5600. (unless (and blank? (org-previous-line-empty-p))
  5601. (org-N-empty-lines-before-current (if blank? 1 0))))))
  5602. (run-hooks 'org-insert-heading-hook))
  5603. (defun org-N-empty-lines-before-current (n)
  5604. "Make the number of empty lines before current exactly N.
  5605. So this will delete or add empty lines."
  5606. (let ((column (current-column)))
  5607. (beginning-of-line)
  5608. (unless (bobp)
  5609. (let ((start (save-excursion
  5610. (skip-chars-backward " \r\t\n")
  5611. (line-end-position))))
  5612. (delete-region start (line-end-position 0))))
  5613. (insert (make-string n ?\n))
  5614. (move-to-column column)))
  5615. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  5616. "Return the heading of the current entry, without the stars.
  5617. When NO-TAGS is non-nil, don't include tags.
  5618. When NO-TODO is non-nil, don't include TODO keywords.
  5619. When NO-PRIORITY is non-nil, don't include priority cookie.
  5620. When NO-COMMENT is non-nil, don't include COMMENT string.
  5621. Return nil before first heading."
  5622. (unless (org-before-first-heading-p)
  5623. (save-excursion
  5624. (org-back-to-heading t)
  5625. (let ((case-fold-search nil))
  5626. (looking-at org-complex-heading-regexp)
  5627. ;; When using `org-fold-core--optimise-for-huge-buffers',
  5628. ;; returned text will be invisible. Clear it up.
  5629. (save-match-data
  5630. (org-fold-core-remove-optimisation (match-beginning 0) (match-end 0)))
  5631. (let ((todo (and (not no-todo) (match-string 2)))
  5632. (priority (and (not no-priority) (match-string 3)))
  5633. (headline (pcase (match-string 4)
  5634. (`nil "")
  5635. ((and (guard no-comment) h)
  5636. (replace-regexp-in-string
  5637. (eval-when-compile
  5638. (format "\\`%s[ \t]+" org-comment-string))
  5639. "" h))
  5640. (h h)))
  5641. (tags (and (not no-tags) (match-string 5))))
  5642. ;; Restore cleared optimisation.
  5643. (org-fold-core-update-optimisation (match-beginning 0) (match-end 0))
  5644. (mapconcat #'identity
  5645. (delq nil (list todo priority headline tags))
  5646. " "))))))
  5647. (defun org-heading-components ()
  5648. "Return the components of the current heading.
  5649. This is a list with the following elements:
  5650. - the level as an integer
  5651. - the reduced level, different if `org-odd-levels-only' is set.
  5652. - the TODO keyword, or nil
  5653. - the priority character, like ?A, or nil if no priority is given
  5654. - the headline text itself, or the tags string if no headline text
  5655. - the tags string, or nil."
  5656. (save-excursion
  5657. (org-back-to-heading t)
  5658. (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
  5659. (org-fold-core-remove-optimisation (match-beginning 0) (match-end 0))
  5660. (prog1
  5661. (list (length (match-string 1))
  5662. (org-reduced-level (length (match-string 1)))
  5663. (match-string-no-properties 2)
  5664. (and (match-end 3) (aref (match-string 3) 2))
  5665. (match-string-no-properties 4)
  5666. (match-string-no-properties 5))
  5667. (org-fold-core-update-optimisation (match-beginning 0) (match-end 0))))))
  5668. (defun org-get-entry ()
  5669. "Get the entry text, after heading, entire subtree."
  5670. (save-excursion
  5671. (org-back-to-heading t)
  5672. (filter-buffer-substring (line-beginning-position 2) (org-end-of-subtree t))))
  5673. (defun org-edit-headline (&optional heading)
  5674. "Edit the current headline.
  5675. Set it to HEADING when provided."
  5676. (interactive)
  5677. (org-with-wide-buffer
  5678. (org-back-to-heading t)
  5679. (let ((case-fold-search nil))
  5680. (when (looking-at org-complex-heading-regexp)
  5681. (let* ((old (match-string-no-properties 4))
  5682. (new (save-match-data
  5683. (org-trim (or heading (read-string "Edit: " old))))))
  5684. (unless (equal old new)
  5685. (if old (replace-match new t t nil 4)
  5686. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  5687. (insert " " new))
  5688. (org-align-tags)
  5689. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  5690. (defun org-insert-heading-after-current ()
  5691. "Insert a new heading with same level as current, after current subtree."
  5692. (interactive)
  5693. (org-back-to-heading)
  5694. (org-insert-heading)
  5695. (org-move-subtree-down)
  5696. (end-of-line 1))
  5697. (defun org-insert-heading-respect-content (&optional invisible-ok)
  5698. "Insert heading with `org-insert-heading-respect-content' set to t."
  5699. (interactive)
  5700. (org-insert-heading '(4) invisible-ok))
  5701. (defun org-insert-todo-heading-respect-content (&optional _)
  5702. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  5703. (interactive)
  5704. (let ((org-insert-heading-respect-content t))
  5705. (org-insert-todo-heading '(4) t)))
  5706. (defun org-insert-todo-heading (arg &optional force-heading)
  5707. "Insert a new heading with the same level and TODO state as current heading.
  5708. If the heading has no TODO state, or if the state is DONE, use
  5709. the first state (TODO by default). Also with one prefix arg,
  5710. force first state. With two prefix args, force inserting at the
  5711. end of the parent subtree.
  5712. When called at a plain list item, insert a new item with an
  5713. unchecked check box."
  5714. (interactive "P")
  5715. (when (or force-heading (not (org-insert-item 'checkbox)))
  5716. (org-insert-heading (or (and (equal arg '(16)) '(16))
  5717. force-heading))
  5718. (save-excursion
  5719. (org-forward-heading-same-level -1)
  5720. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  5721. (let* ((new-mark-x
  5722. (if (or (equal arg '(4))
  5723. (not (match-beginning 2))
  5724. (member (match-string 2) org-done-keywords))
  5725. (car org-todo-keywords-1)
  5726. (match-string 2)))
  5727. (new-mark
  5728. (or
  5729. (run-hook-with-args-until-success
  5730. 'org-todo-get-default-hook new-mark-x nil)
  5731. new-mark-x)))
  5732. (beginning-of-line 1)
  5733. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  5734. (if org-treat-insert-todo-heading-as-state-change
  5735. (org-todo new-mark)
  5736. (insert new-mark " "))))
  5737. (when org-provide-todo-statistics
  5738. (org-update-parent-todo-statistics))))
  5739. (defun org-insert-subheading (arg)
  5740. "Insert a new subheading and demote it.
  5741. Works for outline headings and for plain lists alike."
  5742. (interactive "P")
  5743. (org-insert-heading arg)
  5744. (cond
  5745. ((org-at-heading-p) (org-do-demote))
  5746. ((org-at-item-p) (org-indent-item))))
  5747. (defun org-insert-todo-subheading (arg)
  5748. "Insert a new subheading with TODO keyword or checkbox and demote it.
  5749. Works for outline headings and for plain lists alike."
  5750. (interactive "P")
  5751. (org-insert-todo-heading arg)
  5752. (cond
  5753. ((org-at-heading-p) (org-do-demote))
  5754. ((org-at-item-p) (org-indent-item))))
  5755. ;;; Promotion and Demotion
  5756. (defvar org-after-demote-entry-hook nil
  5757. "Hook run after an entry has been demoted.
  5758. The cursor will be at the beginning of the entry.
  5759. When a subtree is being demoted, the hook will be called for each node.")
  5760. (defvar org-after-promote-entry-hook nil
  5761. "Hook run after an entry has been promoted.
  5762. The cursor will be at the beginning of the entry.
  5763. When a subtree is being promoted, the hook will be called for each node.")
  5764. (defun org-promote-subtree ()
  5765. "Promote the entire subtree.
  5766. See also `org-promote'."
  5767. (interactive)
  5768. (save-excursion
  5769. (org-back-to-heading t)
  5770. (combine-change-calls (point) (save-excursion (org-end-of-subtree t))
  5771. (org-with-limited-levels (org-map-tree 'org-promote))))
  5772. (org-fix-position-after-promote))
  5773. (defun org-demote-subtree ()
  5774. "Demote the entire subtree.
  5775. See `org-demote' and `org-promote'."
  5776. (interactive)
  5777. (save-excursion
  5778. (org-back-to-heading t)
  5779. (combine-change-calls (point) (save-excursion (org-end-of-subtree t))
  5780. (org-with-limited-levels (org-map-tree 'org-demote))))
  5781. (org-fix-position-after-promote))
  5782. (defun org-do-promote ()
  5783. "Promote the current heading higher up the tree.
  5784. If the region is active in `transient-mark-mode', promote all
  5785. headings in the region."
  5786. (interactive)
  5787. (save-excursion
  5788. (if (org-region-active-p)
  5789. (org-map-region 'org-promote (region-beginning) (region-end))
  5790. (org-promote)))
  5791. (org-fix-position-after-promote))
  5792. (defun org-do-demote ()
  5793. "Demote the current heading lower down the tree.
  5794. If the region is active in `transient-mark-mode', demote all
  5795. headings in the region."
  5796. (interactive)
  5797. (save-excursion
  5798. (if (org-region-active-p)
  5799. (org-map-region 'org-demote (region-beginning) (region-end))
  5800. (org-demote)))
  5801. (org-fix-position-after-promote))
  5802. (defun org-fix-position-after-promote ()
  5803. "Fix cursor position and indentation after demoting/promoting."
  5804. (let ((pos (point)))
  5805. (when (save-excursion
  5806. (beginning-of-line)
  5807. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  5808. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  5809. (cond ((eobp) (insert " "))
  5810. ((eolp) (insert " "))
  5811. ((equal (char-after) ?\s) (forward-char 1))))))
  5812. (defun org-current-level ()
  5813. "Return the level of the current entry, or nil if before the first headline.
  5814. The level is the number of stars at the beginning of the
  5815. headline. Use `org-reduced-level' to remove the effect of
  5816. `org-odd-levels'. Unlike to `org-outline-level', this function
  5817. ignores inlinetasks."
  5818. (let ((level (org-with-limited-levels (org-outline-level))))
  5819. (and (> level 0) level)))
  5820. (defun org-get-previous-line-level ()
  5821. "Return the outline depth of the last headline before the current line.
  5822. Returns 0 for the first headline in the buffer, and nil if before the
  5823. first headline."
  5824. (and (org-current-level)
  5825. (or (and (/= (line-beginning-position) (point-min))
  5826. (save-excursion (beginning-of-line 0) (org-current-level)))
  5827. 0)))
  5828. (defun org-reduced-level (l)
  5829. "Compute the effective level of a heading.
  5830. This takes into account the setting of `org-odd-levels-only'."
  5831. (cond
  5832. ((zerop l) 0)
  5833. (org-odd-levels-only (1+ (floor (/ l 2))))
  5834. (t l)))
  5835. (defun org-level-increment ()
  5836. "Return the number of stars that will be added or removed at a
  5837. time to headlines when structure editing, based on the value of
  5838. `org-odd-levels-only'."
  5839. (if org-odd-levels-only 2 1))
  5840. (defun org-get-valid-level (level &optional change)
  5841. "Rectify a level change under the influence of `org-odd-levels-only'.
  5842. LEVEL is a current level, CHANGE is by how much the level should
  5843. be modified. Even if CHANGE is nil, LEVEL may be returned
  5844. modified because even level numbers will become the next higher
  5845. odd number. Returns values greater than 0."
  5846. (if org-odd-levels-only
  5847. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  5848. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  5849. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  5850. (max 1 (+ level (or change 0)))))
  5851. (defun org-promote ()
  5852. "Promote the current heading higher up the tree."
  5853. (org-with-wide-buffer
  5854. (org-back-to-heading t)
  5855. (let* ((after-change-functions (remq 'flyspell-after-change-function
  5856. after-change-functions))
  5857. (level (save-match-data (funcall outline-level)))
  5858. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  5859. (diff (abs (- level (length up-head) -1))))
  5860. (cond
  5861. ((and (= level 1) org-allow-promoting-top-level-subtree)
  5862. (replace-match "# " nil t))
  5863. ((= level 1)
  5864. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  5865. (t (replace-match (apply #'propertize up-head (text-properties-at (match-beginning 0))) t)))
  5866. (unless (= level 1)
  5867. (when org-auto-align-tags (org-align-tags))
  5868. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  5869. (run-hooks 'org-after-promote-entry-hook))))
  5870. (defun org-demote ()
  5871. "Demote the current heading lower down the tree."
  5872. (org-with-wide-buffer
  5873. (org-back-to-heading t)
  5874. (let* ((after-change-functions (remq 'flyspell-after-change-function
  5875. after-change-functions))
  5876. (level (save-match-data (funcall outline-level)))
  5877. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  5878. (diff (abs (- level (length down-head) -1))))
  5879. (org-fold-core-ignore-fragility-checks
  5880. (replace-match (apply #'propertize down-head (text-properties-at (match-beginning 0))) t)
  5881. (when org-auto-align-tags (org-align-tags))
  5882. (when org-adapt-indentation (org-fixup-indentation diff)))
  5883. (run-hooks 'org-after-demote-entry-hook))))
  5884. (defun org-cycle-level ()
  5885. "Cycle the level of an empty headline through possible states.
  5886. This goes first to child, then to parent, level, then up the hierarchy.
  5887. After top level, it switches back to sibling level."
  5888. (interactive)
  5889. (let ((org-adapt-indentation nil))
  5890. (when (org-point-at-end-of-empty-headline)
  5891. (setq this-command 'org-cycle-level) ; Only needed for caching
  5892. (let ((cur-level (org-current-level))
  5893. (prev-level (org-get-previous-line-level)))
  5894. (cond
  5895. ;; If first headline in file, promote to top-level.
  5896. ((= prev-level 0)
  5897. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  5898. do (org-do-promote)))
  5899. ;; If same level as prev, demote one.
  5900. ((= prev-level cur-level)
  5901. (org-do-demote))
  5902. ;; If parent is top-level, promote to top level if not already.
  5903. ((= prev-level 1)
  5904. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  5905. do (org-do-promote)))
  5906. ;; If top-level, return to prev-level.
  5907. ((= cur-level 1)
  5908. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  5909. do (org-do-demote)))
  5910. ;; If less than prev-level, promote one.
  5911. ((< cur-level prev-level)
  5912. (org-do-promote))
  5913. ;; If deeper than prev-level, promote until higher than
  5914. ;; prev-level.
  5915. ((> cur-level prev-level)
  5916. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  5917. do (org-do-promote))))
  5918. t))))
  5919. (defun org-map-tree (fun)
  5920. "Call FUN for every heading underneath the current one."
  5921. (org-back-to-heading t)
  5922. (let ((level (funcall outline-level)))
  5923. (save-excursion
  5924. (funcall fun)
  5925. (while (and (progn
  5926. (outline-next-heading)
  5927. (> (funcall outline-level) level))
  5928. (not (eobp)))
  5929. (funcall fun)))))
  5930. (defun org-map-region (fun beg end)
  5931. "Call FUN for every heading between BEG and END."
  5932. (let ((org-ignore-region t))
  5933. (save-excursion
  5934. (setq end (copy-marker end))
  5935. (goto-char beg)
  5936. (when (and (re-search-forward org-outline-regexp-bol nil t)
  5937. (< (point) end))
  5938. (funcall fun))
  5939. (while (and (progn
  5940. (outline-next-heading)
  5941. (< (point) end))
  5942. (not (eobp)))
  5943. (funcall fun)))))
  5944. (defun org-fixup-indentation (diff)
  5945. "Change the indentation in the current entry by DIFF.
  5946. DIFF is an integer. Indentation is done according to the
  5947. following rules:
  5948. - Planning information and property drawers are always indented
  5949. according to the new level of the headline;
  5950. - Footnote definitions and their contents are ignored;
  5951. - Inlinetasks' boundaries are not shifted;
  5952. - Empty lines are ignored;
  5953. - Other lines' indentation are shifted by DIFF columns, unless
  5954. it would introduce a structural change in the document, in
  5955. which case no shifting is done at all.
  5956. Assume point is at a heading or an inlinetask beginning."
  5957. (org-with-wide-buffer
  5958. (narrow-to-region (line-beginning-position)
  5959. (save-excursion
  5960. (if (org-with-limited-levels (org-at-heading-p))
  5961. (org-with-limited-levels (outline-next-heading))
  5962. (org-inlinetask-goto-end))
  5963. (point)))
  5964. (forward-line)
  5965. ;; Indent properly planning info and property drawer.
  5966. (when (looking-at-p org-planning-line-re)
  5967. (org-indent-line)
  5968. (forward-line))
  5969. (when (looking-at org-property-drawer-re)
  5970. (goto-char (match-end 0))
  5971. (forward-line)
  5972. (org-indent-region (match-beginning 0) (match-end 0)))
  5973. (when (looking-at org-logbook-drawer-re)
  5974. (let ((end-marker (move-marker (make-marker) (match-end 0)))
  5975. (col (+ (current-indentation) diff)))
  5976. (when (wholenump col)
  5977. (while (< (point) end-marker)
  5978. (if (natnump diff)
  5979. (insert (make-string diff 32))
  5980. (delete-char (abs diff)))
  5981. (forward-line)))))
  5982. (catch 'no-shift
  5983. (when (or (zerop diff) (not (eq org-adapt-indentation t)))
  5984. (throw 'no-shift nil))
  5985. ;; If DIFF is negative, first check if a shift is possible at all
  5986. ;; (e.g., it doesn't break structure). This can only happen if
  5987. ;; some contents are not properly indented.
  5988. (let ((case-fold-search t))
  5989. (when (< diff 0)
  5990. (let ((diff (- diff))
  5991. (forbidden-re (concat org-outline-regexp
  5992. "\\|"
  5993. (substring org-footnote-definition-re 1))))
  5994. (save-excursion
  5995. (while (not (eobp))
  5996. (cond
  5997. ((looking-at-p "[ \t]*$") (forward-line))
  5998. ((and (looking-at-p org-footnote-definition-re)
  5999. (let ((e (org-element-at-point)))
  6000. (and (eq (org-element-type e) 'footnote-definition)
  6001. (goto-char (org-element-property :end e))))))
  6002. ((looking-at-p org-outline-regexp) (forward-line))
  6003. ;; Give up if shifting would move before column 0 or
  6004. ;; if it would introduce a headline or a footnote
  6005. ;; definition.
  6006. (t
  6007. (skip-chars-forward " \t")
  6008. (let ((ind (current-column)))
  6009. (when (or (< ind diff)
  6010. (and (= ind diff) (looking-at-p forbidden-re)))
  6011. (throw 'no-shift nil)))
  6012. ;; Ignore contents of example blocks and source
  6013. ;; blocks if their indentation is meant to be
  6014. ;; preserved. Jump to block's closing line.
  6015. (beginning-of-line)
  6016. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6017. (let ((e (org-element-at-point)))
  6018. (and (memq (org-element-type e)
  6019. '(example-block src-block))
  6020. (or org-src-preserve-indentation
  6021. (org-element-property :preserve-indent e))
  6022. (goto-char (org-element-property :end e))
  6023. (progn (skip-chars-backward " \r\t\n")
  6024. (beginning-of-line)
  6025. t))))
  6026. (forward-line))))))))
  6027. ;; Shift lines but footnote definitions, inlinetasks boundaries
  6028. ;; by DIFF. Also skip contents of source or example blocks
  6029. ;; when indentation is meant to be preserved.
  6030. (while (not (eobp))
  6031. (cond
  6032. ((and (looking-at-p org-footnote-definition-re)
  6033. (let ((e (org-element-at-point)))
  6034. (and (eq (org-element-type e) 'footnote-definition)
  6035. (goto-char (org-element-property :end e))))))
  6036. ((looking-at-p org-outline-regexp) (forward-line))
  6037. ((looking-at-p "[ \t]*$") (forward-line))
  6038. (t
  6039. (indent-line-to (+ (current-indentation) diff))
  6040. (beginning-of-line)
  6041. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6042. (let ((e (org-element-at-point)))
  6043. (and (memq (org-element-type e)
  6044. '(example-block src-block))
  6045. (or org-src-preserve-indentation
  6046. (org-element-property :preserve-indent e))
  6047. (goto-char (org-element-property :end e))
  6048. (progn (skip-chars-backward " \r\t\n")
  6049. (beginning-of-line)
  6050. t))))
  6051. (forward-line)))))))))
  6052. (defun org-convert-to-odd-levels ()
  6053. "Convert an Org file with all levels allowed to one with odd levels.
  6054. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  6055. level 5 etc."
  6056. (interactive)
  6057. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  6058. (let ((outline-level 'org-outline-level)
  6059. (org-odd-levels-only nil) n)
  6060. (save-excursion
  6061. (goto-char (point-min))
  6062. (while (re-search-forward "^\\*\\*+ " nil t)
  6063. (setq n (- (length (match-string 0)) 2))
  6064. (while (>= (setq n (1- n)) 0)
  6065. (org-demote))
  6066. (end-of-line 1))))))
  6067. (defun org-convert-to-oddeven-levels ()
  6068. "Convert an Org file with only odd levels to one with odd/even levels.
  6069. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  6070. file contains a section with an even level, conversion would
  6071. destroy the structure of the file. An error is signaled in this
  6072. case."
  6073. (interactive)
  6074. (goto-char (point-min))
  6075. ;; First check if there are no even levels
  6076. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  6077. (org-fold-show-set-visibility 'canonical)
  6078. (error "Not all levels are odd in this file. Conversion not possible"))
  6079. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  6080. (let ((outline-regexp org-outline-regexp)
  6081. (outline-level 'org-outline-level)
  6082. (org-odd-levels-only nil) n)
  6083. (save-excursion
  6084. (goto-char (point-min))
  6085. (while (re-search-forward "^\\*\\*+ " nil t)
  6086. (setq n (/ (1- (length (match-string 0))) 2))
  6087. (while (>= (setq n (1- n)) 0)
  6088. (org-promote))
  6089. (end-of-line 1))))))
  6090. (defun org-tr-level (n)
  6091. "Make N odd if required."
  6092. (if org-odd-levels-only (1+ (/ n 2)) n))
  6093. ;;; Vertical tree motion, cutting and pasting of subtrees
  6094. (defun org-move-subtree-up (&optional arg)
  6095. "Move the current subtree up past ARG headlines of the same level."
  6096. (interactive "p")
  6097. (org-move-subtree-down (- (prefix-numeric-value arg))))
  6098. (defun org-clean-visibility-after-subtree-move ()
  6099. "Fix visibility issues after moving a subtree."
  6100. ;; First, find a reasonable region to look at:
  6101. ;; Start two siblings above, end three below
  6102. (let* ((beg (save-excursion
  6103. (and (org-get-previous-sibling)
  6104. (org-get-previous-sibling))
  6105. (point)))
  6106. (end (save-excursion
  6107. (and (org-get-next-sibling)
  6108. (org-get-next-sibling)
  6109. (org-get-next-sibling))
  6110. (if (org-at-heading-p)
  6111. (line-end-position)
  6112. (point))))
  6113. (level (looking-at "\\*+"))
  6114. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  6115. (save-excursion
  6116. (save-restriction
  6117. (narrow-to-region beg end)
  6118. (when re
  6119. ;; Properly fold already folded siblings
  6120. (goto-char (point-min))
  6121. (while (re-search-forward re nil t)
  6122. (when (and (not (org-invisible-p))
  6123. (org-invisible-p (line-end-position)))
  6124. (org-fold-heading nil))))
  6125. (org-cycle-hide-drawers 'all)
  6126. (org-cycle-show-empty-lines 'overview)))))
  6127. (defun org-move-subtree-down (&optional arg)
  6128. "Move the current subtree down past ARG headlines of the same level."
  6129. (interactive "p")
  6130. (setq arg (prefix-numeric-value arg))
  6131. (org-preserve-local-variables
  6132. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  6133. 'org-get-previous-sibling))
  6134. (ins-point (make-marker))
  6135. (cnt (abs arg))
  6136. (col (current-column))
  6137. beg end txt folded)
  6138. ;; Select the tree
  6139. (org-back-to-heading)
  6140. (setq beg (point))
  6141. (save-match-data
  6142. (save-excursion (outline-end-of-heading)
  6143. (setq folded (org-invisible-p)))
  6144. (progn (org-end-of-subtree nil t)
  6145. (unless (eobp) (backward-char))))
  6146. (outline-next-heading)
  6147. (setq end (point))
  6148. (goto-char beg)
  6149. ;; Find insertion point, with error handling
  6150. (while (> cnt 0)
  6151. (unless (and (funcall movfunc) (looking-at org-outline-regexp))
  6152. (goto-char beg)
  6153. (user-error "Cannot move past superior level or buffer limit"))
  6154. (setq cnt (1- cnt)))
  6155. (when (> arg 0)
  6156. ;; Moving forward - still need to move over subtree
  6157. (org-end-of-subtree t t)
  6158. (save-excursion
  6159. (org-back-over-empty-lines)
  6160. (or (bolp) (newline))))
  6161. (move-marker ins-point (point))
  6162. (setq txt (buffer-substring beg end))
  6163. (org-save-markers-in-region beg end)
  6164. (delete-region beg end)
  6165. (when (eq org-fold-core-style 'overlays) (org-remove-empty-overlays-at beg))
  6166. (unless (= beg (point-min)) (org-fold-region (1- beg) beg nil 'outline))
  6167. (unless (bobp) (org-fold-region (1- (point)) (point) nil 'outline))
  6168. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  6169. (let ((bbb (point)))
  6170. (insert-before-markers txt)
  6171. (org-reinstall-markers-in-region bbb)
  6172. (move-marker ins-point bbb))
  6173. (or (bolp) (insert "\n"))
  6174. (goto-char ins-point)
  6175. (org-skip-whitespace)
  6176. (move-marker ins-point nil)
  6177. (if folded
  6178. (org-fold-subtree t)
  6179. (org-fold-show-entry 'hide-drawers)
  6180. (org-fold-show-children))
  6181. (org-clean-visibility-after-subtree-move)
  6182. ;; move back to the initial column we were at
  6183. (move-to-column col))))
  6184. (defvar org-subtree-clip ""
  6185. "Clipboard for cut and paste of subtrees.
  6186. This is actually only a copy of the kill, because we use the normal kill
  6187. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  6188. (defvar org-subtree-clip-folded nil
  6189. "Was the last copied subtree folded?
  6190. This is used to fold the tree back after pasting.")
  6191. (defun org-cut-subtree (&optional n)
  6192. "Cut the current subtree into the clipboard.
  6193. With prefix arg N, cut this many sequential subtrees.
  6194. This is a short-hand for marking the subtree and then cutting it."
  6195. (interactive "p")
  6196. (org-copy-subtree n 'cut))
  6197. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  6198. "Copy the current subtree into the clipboard.
  6199. With prefix arg N, copy this many sequential subtrees.
  6200. This is a short-hand for marking the subtree and then copying it.
  6201. If CUT is non-nil, actually cut the subtree.
  6202. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  6203. of some markers in the region, even if CUT is non-nil. This is
  6204. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  6205. (interactive "p")
  6206. (org-preserve-local-variables
  6207. (let (beg end folded (beg0 (point)))
  6208. (if (called-interactively-p 'any)
  6209. (org-back-to-heading nil) ; take what looks like a subtree
  6210. (org-back-to-heading t)) ; take what is really there
  6211. (setq beg (point))
  6212. (skip-chars-forward " \t\r\n")
  6213. (save-match-data
  6214. (if nosubtrees
  6215. (outline-next-heading)
  6216. (save-excursion (outline-end-of-heading)
  6217. (setq folded (org-invisible-p)))
  6218. (ignore-errors (org-forward-heading-same-level (1- n) t))
  6219. (org-end-of-subtree t t)))
  6220. ;; Include the end of an inlinetask
  6221. (when (and (featurep 'org-inlinetask)
  6222. (looking-at-p (concat (org-inlinetask-outline-regexp)
  6223. "END[ \t]*$")))
  6224. (end-of-line))
  6225. (setq end (point))
  6226. (goto-char beg0)
  6227. (when (> end beg)
  6228. (setq org-subtree-clip-folded folded)
  6229. (when (or cut force-store-markers)
  6230. (org-save-markers-in-region beg end))
  6231. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  6232. (setq org-subtree-clip (current-kill 0))
  6233. (message "%s: Subtree(s) with %d characters"
  6234. (if cut "Cut" "Copied")
  6235. (length org-subtree-clip))))))
  6236. (defun org-paste-subtree (&optional level tree for-yank remove)
  6237. "Paste the clipboard as a subtree, with modification of headline level.
  6238. The entire subtree is promoted or demoted in order to match a new headline
  6239. level.
  6240. If the cursor is at the beginning of a headline, the same level as
  6241. that headline is used to paste the tree.
  6242. If not, the new level is derived from the *visible* headings
  6243. before and after the insertion point, and taken to be the inferior headline
  6244. level of the two. So if the previous visible heading is level 3 and the
  6245. next is level 4 (or vice versa), level 4 will be used for insertion.
  6246. This makes sure that the subtree remains an independent subtree and does
  6247. not swallow low level entries.
  6248. You can also force a different level, either by using a numeric prefix
  6249. argument, or by inserting the heading marker by hand. For example, if the
  6250. cursor is after \"*****\", then the tree will be shifted to level 5.
  6251. If optional TREE is given, use this text instead of the kill ring.
  6252. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  6253. move back over whitespace before inserting, and move point to the end of
  6254. the inserted text when done.
  6255. When REMOVE is non-nil, remove the subtree from the clipboard."
  6256. (interactive "P")
  6257. (setq tree (or tree (and kill-ring (current-kill 0))))
  6258. (unless (org-kill-is-subtree-p tree)
  6259. (user-error
  6260. (substitute-command-keys
  6261. "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
  6262. (org-with-limited-levels
  6263. (org-fold-core-ignore-fragility-checks
  6264. (let* ((visp (not (org-invisible-p)))
  6265. (txt tree)
  6266. (old-level (if (string-match org-outline-regexp-bol txt)
  6267. (- (match-end 0) (match-beginning 0) 1)
  6268. -1))
  6269. (force-level
  6270. (cond
  6271. (level (prefix-numeric-value level))
  6272. ;; When point is after the stars in an otherwise empty
  6273. ;; headline, use the number of stars as the forced level.
  6274. ((and (org-match-line "^\\*+[ \t]*$")
  6275. (not (eq ?* (char-after))))
  6276. (org-outline-level))
  6277. ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
  6278. (previous-level
  6279. (save-excursion
  6280. (org-previous-visible-heading 1)
  6281. (if (org-at-heading-p) (org-outline-level) 1)))
  6282. (next-level
  6283. (save-excursion
  6284. (if (org-at-heading-p) (org-outline-level)
  6285. (org-next-visible-heading 1)
  6286. (if (org-at-heading-p) (org-outline-level) 1))))
  6287. (new-level (or force-level (max previous-level next-level)))
  6288. (shift (if (or (= old-level -1)
  6289. (= new-level -1)
  6290. (= old-level new-level))
  6291. 0
  6292. (- new-level old-level)))
  6293. (delta (if (> shift 0) -1 1))
  6294. (func (if (> shift 0) #'org-demote #'org-promote))
  6295. (org-odd-levels-only nil)
  6296. beg end newend)
  6297. ;; Remove the forced level indicator.
  6298. (when (and force-level (not level))
  6299. (delete-region (line-beginning-position) (point)))
  6300. ;; Paste before the next visible heading or at end of buffer,
  6301. ;; unless point is at the beginning of a headline.
  6302. (unless (and (bolp) (org-at-heading-p))
  6303. (org-next-visible-heading 1)
  6304. (unless (bolp) (insert "\n")))
  6305. (setq beg (point))
  6306. ;; Avoid re-parsing cache elements when i.e. level 1 heading
  6307. ;; is inserted and then promoted.
  6308. (combine-change-calls beg beg
  6309. (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  6310. (insert txt)
  6311. (unless (string-suffix-p "\n" txt) (insert "\n"))
  6312. (setq newend (point))
  6313. (org-reinstall-markers-in-region beg)
  6314. (setq end (point))
  6315. (goto-char beg)
  6316. (skip-chars-forward " \t\n\r")
  6317. (setq beg (point))
  6318. (when (and (org-invisible-p) visp)
  6319. (save-excursion (org-fold-heading nil)))
  6320. ;; Shift if necessary.
  6321. (unless (= shift 0)
  6322. (save-restriction
  6323. (narrow-to-region beg end)
  6324. (while (not (= shift 0))
  6325. (org-map-region func (point-min) (point-max))
  6326. (setq shift (+ delta shift)))
  6327. (goto-char (point-min))
  6328. (setq newend (point-max)))))
  6329. (when (or for-yank (called-interactively-p 'interactive))
  6330. (message "Clipboard pasted as level %d subtree" new-level))
  6331. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  6332. kill-ring
  6333. (equal org-subtree-clip (current-kill 0))
  6334. org-subtree-clip-folded)
  6335. ;; The tree was folded before it was killed/copied
  6336. (org-fold-subtree t))
  6337. (when for-yank (goto-char newend))
  6338. (when remove (pop kill-ring))))))
  6339. (defun org-kill-is-subtree-p (&optional txt)
  6340. "Check if the current kill is an outline subtree, or a set of trees.
  6341. Returns nil if kill does not start with a headline, or if the first
  6342. headline level is not the largest headline level in the tree.
  6343. So this will actually accept several entries of equal levels as well,
  6344. which is OK for `org-paste-subtree'.
  6345. If optional TXT is given, check this string instead of the current kill."
  6346. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  6347. (re (org-get-limited-outline-regexp))
  6348. (^re (concat "^" re))
  6349. (start-level (and kill
  6350. (string-match
  6351. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  6352. kill)
  6353. (- (match-end 2) (match-beginning 2) 1)))
  6354. (start (1+ (or (match-beginning 2) -1))))
  6355. (if (not start-level)
  6356. (progn
  6357. nil) ;; does not even start with a heading
  6358. (catch 'exit
  6359. (while (setq start (string-match ^re kill (1+ start)))
  6360. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  6361. (throw 'exit nil)))
  6362. t))))
  6363. (defvar org-markers-to-move nil
  6364. "Markers that should be moved with a cut-and-paste operation.
  6365. Those markers are stored together with their positions relative to
  6366. the start of the region.")
  6367. (defun org-save-markers-in-region (beg end)
  6368. "Check markers in region.
  6369. If these markers are between BEG and END, record their position relative
  6370. to BEG, so that after moving the block of text, we can put the markers back
  6371. into place.
  6372. This function gets called just before an entry or tree gets cut from the
  6373. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  6374. called immediately, to move the markers with the entries."
  6375. (setq org-markers-to-move nil)
  6376. (when (featurep 'org-clock)
  6377. (org-clock-save-markers-for-cut-and-paste beg end))
  6378. (when (featurep 'org-agenda)
  6379. (org-agenda-save-markers-for-cut-and-paste beg end)))
  6380. (defun org-check-and-save-marker (marker beg end)
  6381. "Check if MARKER is between BEG and END.
  6382. If yes, remember the marker and the distance to BEG."
  6383. (when (and (marker-buffer marker)
  6384. (or (equal (marker-buffer marker) (current-buffer))
  6385. (equal (marker-buffer marker) (buffer-base-buffer (current-buffer))))
  6386. (>= marker beg) (< marker end))
  6387. (push (cons marker (- marker beg)) org-markers-to-move)))
  6388. (defun org-reinstall-markers-in-region (beg)
  6389. "Move all remembered markers to their position relative to BEG."
  6390. (dolist (x org-markers-to-move)
  6391. (move-marker (car x) (+ beg (cdr x))))
  6392. (setq org-markers-to-move nil))
  6393. (defun org-narrow-to-subtree (&optional element)
  6394. "Narrow buffer to the current subtree."
  6395. (interactive)
  6396. (if (org-element--cache-active-p)
  6397. (let* ((heading (org-element-lineage
  6398. (or element (org-element-at-point))
  6399. '(headline) t))
  6400. (end (org-element-property :end heading)))
  6401. (if (and heading end)
  6402. (narrow-to-region (org-element-property :begin heading)
  6403. (if (= end (point-max))
  6404. end (1- end)))
  6405. (signal 'outline-before-first-heading nil)))
  6406. (save-excursion
  6407. (save-match-data
  6408. (org-with-limited-levels
  6409. (narrow-to-region
  6410. (progn (org-back-to-heading t) (point))
  6411. (progn (org-end-of-subtree t t)
  6412. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  6413. (point))))))))
  6414. (defun org-toggle-narrow-to-subtree ()
  6415. "Narrow to the subtree at point or widen a narrowed buffer."
  6416. (interactive)
  6417. (if (buffer-narrowed-p)
  6418. (progn (widen) (message "Buffer widen"))
  6419. (org-narrow-to-subtree)
  6420. (message "Buffer narrowed to current subtree")))
  6421. (defun org-narrow-to-block ()
  6422. "Narrow buffer to the current block."
  6423. (interactive)
  6424. (let* ((case-fold-search t)
  6425. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  6426. "^[ \t]*#\\+end_.*")))
  6427. (if blockp
  6428. (narrow-to-region (car blockp) (cdr blockp))
  6429. (user-error "Not in a block"))))
  6430. (defun org-clone-subtree-with-time-shift (n &optional shift)
  6431. "Clone the task (subtree) at point N times.
  6432. The clones will be inserted as siblings.
  6433. In interactive use, the user will be prompted for the number of
  6434. clones to be produced. If the entry has a timestamp, the user
  6435. will also be prompted for a time shift, which may be a repeater
  6436. as used in time stamps, for example `+3d'. To disable this,
  6437. you can call the function with a universal prefix argument.
  6438. When a valid repeater is given and the entry contains any time
  6439. stamps, the clones will become a sequence in time, with time
  6440. stamps in the subtree shifted for each clone produced. If SHIFT
  6441. is nil or the empty string, time stamps will be left alone. The
  6442. ID property of the original subtree is removed.
  6443. In each clone, all the CLOCK entries will be removed. This
  6444. prevents Org from considering that the clocked times overlap.
  6445. If the original subtree did contain time stamps with a repeater,
  6446. the following will happen:
  6447. - the repeater will be removed in each clone
  6448. - an additional clone will be produced, with the current, unshifted
  6449. date(s) in the entry.
  6450. - the original entry will be placed *after* all the clones, with
  6451. repeater intact.
  6452. - the start days in the repeater in the original entry will be shifted
  6453. to past the last clone.
  6454. In this way you can spell out a number of instances of a repeating task,
  6455. and still retain the repeater to cover future instances of the task.
  6456. As described above, N+1 clones are produced when the original
  6457. subtree has a repeater. Setting N to 0, then, can be used to
  6458. remove the repeater from a subtree and create a shifted clone
  6459. with the original repeater."
  6460. (interactive "nNumber of clones to produce: ")
  6461. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  6462. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  6463. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  6464. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  6465. (shift
  6466. (or shift
  6467. (if (and (not (equal current-prefix-arg '(4)))
  6468. (save-excursion
  6469. (goto-char beg)
  6470. (re-search-forward org-ts-regexp-both end-of-tree t)))
  6471. (read-from-minibuffer
  6472. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  6473. ""))) ;No time shift
  6474. (doshift
  6475. (and (org-string-nw-p shift)
  6476. (or (string-match "\\`[ \t]*\\([+-]?[0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
  6477. shift)
  6478. (user-error "Invalid shift specification %s" shift)))))
  6479. (goto-char end-of-tree)
  6480. (unless (bolp) (insert "\n"))
  6481. (let* ((end (point))
  6482. (template (buffer-substring beg end))
  6483. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  6484. (shift-what (pcase (and doshift (match-string 2 shift))
  6485. (`nil nil)
  6486. ("h" 'hour)
  6487. ("d" 'day)
  6488. ("w" (setq shift-n (* 7 shift-n)) 'day)
  6489. ("m" 'month)
  6490. ("y" 'year)
  6491. (_ (error "Unsupported time unit"))))
  6492. (nmin 1)
  6493. (nmax n)
  6494. (n-no-remove -1)
  6495. (org-id-overriding-file-name (buffer-file-name (buffer-base-buffer)))
  6496. (idprop (org-entry-get beg "ID")))
  6497. (when (and doshift
  6498. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  6499. template))
  6500. (delete-region beg end)
  6501. (setq end beg)
  6502. (setq nmin 0)
  6503. (setq nmax (1+ nmax))
  6504. (setq n-no-remove nmax))
  6505. (goto-char end)
  6506. (cl-loop for n from nmin to nmax do
  6507. (insert
  6508. ;; Prepare clone.
  6509. (with-temp-buffer
  6510. (insert template)
  6511. (org-mode)
  6512. (goto-char (point-min))
  6513. (org-fold-show-subtree)
  6514. (and idprop (if org-clone-delete-id
  6515. (org-entry-delete nil "ID")
  6516. (org-id-get-create t)))
  6517. (unless (= n 0)
  6518. (while (re-search-forward org-clock-line-re nil t)
  6519. (delete-region (line-beginning-position)
  6520. (line-beginning-position 2)))
  6521. (goto-char (point-min))
  6522. (while (re-search-forward org-drawer-regexp nil t)
  6523. (org-remove-empty-drawer-at (point))))
  6524. (goto-char (point-min))
  6525. (when doshift
  6526. (while (re-search-forward org-ts-regexp-both nil t)
  6527. (org-timestamp-change (* n shift-n) shift-what))
  6528. (unless (= n n-no-remove)
  6529. (goto-char (point-min))
  6530. (while (re-search-forward org-ts-regexp nil t)
  6531. (save-excursion
  6532. (goto-char (match-beginning 0))
  6533. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  6534. (delete-region (match-beginning 1) (match-end 1)))))))
  6535. (buffer-string)))))
  6536. (goto-char beg)))
  6537. ;;; Outline path
  6538. (defvar org-outline-path-cache nil
  6539. "Alist between buffer positions and outline paths.
  6540. It value is an alist (POSITION . PATH) where POSITION is the
  6541. buffer position at the beginning of an entry and PATH is a list
  6542. of strings describing the outline path for that entry, in reverse
  6543. order.")
  6544. (defun org--get-outline-path-1 (&optional use-cache)
  6545. "Return outline path to current headline.
  6546. Outline path is a list of strings, in reverse order. When
  6547. optional argument USE-CACHE is non-nil, make use of a cache. See
  6548. `org-get-outline-path' for details.
  6549. Assume buffer is widened and point is on a headline."
  6550. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  6551. (let ((p (point))
  6552. (heading (let ((case-fold-search nil))
  6553. (looking-at org-complex-heading-regexp)
  6554. (if (not (match-end 4)) ""
  6555. ;; Remove statistics cookies.
  6556. (org-trim
  6557. (org-link-display-format
  6558. (replace-regexp-in-string
  6559. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  6560. (match-string-no-properties 4))))))))
  6561. (if (org-up-heading-safe)
  6562. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  6563. (when use-cache
  6564. (push (cons p path) org-outline-path-cache))
  6565. path)
  6566. ;; This is a new root node. Since we assume we are moving
  6567. ;; forward, we can drop previous cache so as to limit number
  6568. ;; of associations there.
  6569. (let ((path (list heading)))
  6570. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  6571. path)))))
  6572. (defun org-get-outline-path (&optional with-self use-cache)
  6573. "Return the outline path to the current entry.
  6574. An outline path is a list of ancestors for current headline, as
  6575. a list of strings. Statistics cookies are removed and links are
  6576. replaced with their description, if any, or their path otherwise.
  6577. When optional argument WITH-SELF is non-nil, the path also
  6578. includes the current headline.
  6579. When optional argument USE-CACHE is non-nil, cache outline paths
  6580. between calls to this function so as to avoid backtracking. This
  6581. argument is useful when planning to find more than one outline
  6582. path in the same document. In that case, there are two
  6583. conditions to satisfy:
  6584. - `org-outline-path-cache' is set to nil before starting the
  6585. process;
  6586. - outline paths are computed by increasing buffer positions."
  6587. (org-with-wide-buffer
  6588. (and (or (and with-self (org-back-to-heading t))
  6589. (org-up-heading-safe))
  6590. (reverse (org--get-outline-path-1 use-cache)))))
  6591. (defun org-format-outline-path (path &optional width prefix separator)
  6592. "Format the outline path PATH for display.
  6593. WIDTH is the maximum number of characters that is available.
  6594. PREFIX is a prefix to be included in the returned string,
  6595. such as the file name.
  6596. SEPARATOR is inserted between the different parts of the path,
  6597. the default is \"/\"."
  6598. (setq width (or width 79))
  6599. (setq path (delq nil path))
  6600. (unless (> width 0)
  6601. (user-error "Argument `width' must be positive"))
  6602. (setq separator (or separator "/"))
  6603. (let* ((org-odd-levels-only nil)
  6604. (fpath (concat
  6605. prefix (and prefix path separator)
  6606. (mapconcat
  6607. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  6608. (cl-loop for head in path
  6609. for n from 0
  6610. collect (org-add-props
  6611. head nil 'face
  6612. (nth (% n org-n-level-faces) org-level-faces)))
  6613. separator))))
  6614. (when (> (length fpath) width)
  6615. (if (< width 7)
  6616. ;; It's unlikely that `width' will be this small, but don't
  6617. ;; waste characters by adding ".." if it is.
  6618. (setq fpath (substring fpath 0 width))
  6619. (setf (substring fpath (- width 2)) "..")))
  6620. fpath))
  6621. (defun org-display-outline-path (&optional file current separator just-return-string)
  6622. "Display the current outline path in the echo area.
  6623. If FILE is non-nil, prepend the output with the file name.
  6624. If CURRENT is non-nil, append the current heading to the output.
  6625. SEPARATOR is passed through to `org-format-outline-path'. It separates
  6626. the different parts of the path and defaults to \"/\".
  6627. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  6628. (interactive "P")
  6629. (let* (case-fold-search
  6630. (bfn (buffer-file-name (buffer-base-buffer)))
  6631. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  6632. res)
  6633. (when current (setq path (append path
  6634. (save-excursion
  6635. (org-back-to-heading t)
  6636. (when (looking-at org-complex-heading-regexp)
  6637. (list (match-string 4)))))))
  6638. (setq res
  6639. (org-format-outline-path
  6640. path
  6641. (1- (frame-width))
  6642. (and file bfn (concat (file-name-nondirectory bfn) separator))
  6643. separator))
  6644. (add-face-text-property 0 (length res)
  6645. `(:height ,(face-attribute 'default :height))
  6646. nil res)
  6647. (if just-return-string
  6648. res
  6649. (org-unlogged-message "%s" res))))
  6650. ;;; Outline Sorting
  6651. (defun org-sort (&optional with-case)
  6652. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  6653. Optional argument WITH-CASE means sort case-sensitively."
  6654. (interactive "P")
  6655. (org-call-with-arg
  6656. (cond ((org-at-table-p) #'org-table-sort-lines)
  6657. ((org-at-item-p) #'org-sort-list)
  6658. (t #'org-sort-entries))
  6659. with-case))
  6660. (defun org-sort-remove-invisible (s)
  6661. "Remove emphasis markers and any invisible property from string S.
  6662. Assume S may contain only objects."
  6663. ;; org-element-interpret-data clears any text property, including
  6664. ;; invisible part.
  6665. (org-element-interpret-data
  6666. (let ((tree (org-element-parse-secondary-string
  6667. s (org-element-restriction 'paragraph))))
  6668. (org-element-map tree '(bold code italic link strike-through underline verbatim)
  6669. (lambda (o)
  6670. (pcase (org-element-type o)
  6671. ;; Terminal object. Replace it with its value.
  6672. ((or `code `verbatim)
  6673. (let ((new (org-element-property :value o)))
  6674. (org-element-insert-before new o)
  6675. (org-element-put-property
  6676. new :post-blank (org-element-property :post-blank o))))
  6677. ;; Non-terminal objects. Splice contents.
  6678. (type
  6679. (let ((contents
  6680. (or (org-element-contents o)
  6681. (and (eq type 'link)
  6682. (list (org-element-property :raw-link o)))))
  6683. (c nil))
  6684. (while contents
  6685. (setq c (pop contents))
  6686. (org-element-insert-before c o))
  6687. (org-element-put-property
  6688. c :post-blank (org-element-property :post-blank o)))))
  6689. (org-element-extract-element o)))
  6690. ;; Return modified tree.
  6691. tree)))
  6692. (defvar org-after-sorting-entries-or-items-hook nil
  6693. "Hook that is run after a bunch of entries or items have been sorted.
  6694. When children are sorted, the cursor is in the parent line when this
  6695. hook gets called. When a region or a plain list is sorted, the cursor
  6696. will be in the first entry of the sorted region/list.")
  6697. (defun org-sort-entries
  6698. (&optional with-case sorting-type getkey-func compare-func property
  6699. interactive?)
  6700. "Sort entries on a certain level of an outline tree.
  6701. If there is an active region, the entries in the region are sorted.
  6702. Else, if the cursor is before the first entry, sort the top-level items.
  6703. Else, the children of the entry at point are sorted.
  6704. Sorting can be alphabetically, numerically, by date/time as given by
  6705. a time stamp, by a property, by priority order, or by a custom function.
  6706. The command prompts for the sorting type unless it has been given to the
  6707. function through the SORTING-TYPE argument, which needs to be a character,
  6708. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  6709. the precise meaning of each character:
  6710. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  6711. c By creation time, which is assumed to be the first inactive time stamp
  6712. at the beginning of a line.
  6713. d By deadline date/time.
  6714. k By clocking time.
  6715. n Numerically, by converting the beginning of the entry/item to a number.
  6716. o By order of TODO keywords.
  6717. p By priority according to the cookie.
  6718. r By the value of a property.
  6719. s By scheduled date/time.
  6720. t By date/time, either the first active time stamp in the entry, or, if
  6721. none exist, by the first inactive one.
  6722. Capital letters will reverse the sort order.
  6723. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  6724. called with point at the beginning of the record. It must return a
  6725. value that is compatible with COMPARE-FUNC, the function used to
  6726. compare entries.
  6727. Comparing entries ignores case by default. However, with an optional argument
  6728. WITH-CASE, the sorting considers case as well.
  6729. Sorting is done against the visible part of the headlines, it ignores hidden
  6730. links.
  6731. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  6732. A non-nil value for INTERACTIVE? is used to signal that this
  6733. function is being called interactively."
  6734. (interactive (list current-prefix-arg nil nil nil nil t))
  6735. (let ((case-func (if with-case 'identity 'downcase))
  6736. start beg end stars re re2
  6737. txt what tmp)
  6738. ;; Find beginning and end of region to sort
  6739. (cond
  6740. ((org-region-active-p)
  6741. ;; we will sort the region
  6742. (setq end (region-end)
  6743. what "region")
  6744. (goto-char (region-beginning))
  6745. (unless (org-at-heading-p) (outline-next-heading))
  6746. (setq start (point)))
  6747. ((or (org-at-heading-p)
  6748. (ignore-errors (progn (org-back-to-heading) t)))
  6749. ;; we will sort the children of the current headline
  6750. (org-back-to-heading)
  6751. (setq start (point)
  6752. end (progn (org-end-of-subtree t t)
  6753. (or (bolp) (insert "\n"))
  6754. (when (>= (org-back-over-empty-lines) 1)
  6755. (forward-line 1))
  6756. (point))
  6757. what "children")
  6758. (goto-char start)
  6759. (org-fold-show-subtree)
  6760. (outline-next-heading))
  6761. (t
  6762. ;; we will sort the top-level entries in this file
  6763. (goto-char (point-min))
  6764. (or (org-at-heading-p) (outline-next-heading))
  6765. (setq start (point))
  6766. (goto-char (point-max))
  6767. (beginning-of-line 1)
  6768. (when (looking-at ".*?\\S-")
  6769. ;; File ends in a non-white line
  6770. (end-of-line 1)
  6771. (insert "\n"))
  6772. (setq end (point-max))
  6773. (setq what "top-level")
  6774. (goto-char start)
  6775. (org-fold-show-all '(headings drawers blocks))))
  6776. (setq beg (point))
  6777. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  6778. (looking-at "\\(\\*+\\)")
  6779. (setq stars (match-string 1)
  6780. re (concat "^" (regexp-quote stars) " +")
  6781. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  6782. txt (buffer-substring beg end))
  6783. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  6784. (when (and (not (equal stars "*")) (string-match re2 txt))
  6785. (user-error "Region to sort contains a level above the first entry"))
  6786. (unless sorting-type
  6787. (message
  6788. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  6789. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  6790. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  6791. what)
  6792. (setq sorting-type (read-char-exclusive)))
  6793. (unless getkey-func
  6794. (and (= (downcase sorting-type) ?f)
  6795. (setq getkey-func
  6796. (or (and interactive?
  6797. (org-read-function
  6798. "Function for extracting keys: "))
  6799. (error "Missing key extractor")))))
  6800. (and (= (downcase sorting-type) ?r)
  6801. (not property)
  6802. (setq property
  6803. (completing-read "Property: "
  6804. (mapcar #'list (org-buffer-property-keys t))
  6805. nil t)))
  6806. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  6807. (message "Sorting entries...")
  6808. (save-restriction
  6809. (narrow-to-region start end)
  6810. (let ((restore-clock?
  6811. ;; The clock marker is lost when using `sort-subr'; mark
  6812. ;; the clock with temporary `:org-clock-marker-backup'
  6813. ;; text property.
  6814. (when (and (eq (org-clocking-buffer) (current-buffer))
  6815. (<= start (marker-position org-clock-marker))
  6816. (>= end (marker-position org-clock-marker)))
  6817. (with-silent-modifications
  6818. (put-text-property (1- org-clock-marker) org-clock-marker
  6819. :org-clock-marker-backup t))
  6820. t))
  6821. (dcst (downcase sorting-type))
  6822. (case-fold-search nil)
  6823. (now (current-time)))
  6824. (org-preserve-local-variables
  6825. (sort-subr
  6826. (/= dcst sorting-type)
  6827. ;; This function moves to the beginning character of the
  6828. ;; "record" to be sorted.
  6829. (lambda nil
  6830. (if (re-search-forward re nil t)
  6831. (goto-char (match-beginning 0))
  6832. (goto-char (point-max))))
  6833. ;; This function moves to the last character of the "record" being
  6834. ;; sorted.
  6835. (lambda nil
  6836. (save-match-data
  6837. (condition-case nil
  6838. (outline-forward-same-level 1)
  6839. (error
  6840. (goto-char (point-max))))))
  6841. ;; This function returns the value that gets sorted against.
  6842. (lambda ()
  6843. (cond
  6844. ((= dcst ?n)
  6845. (string-to-number
  6846. (org-sort-remove-invisible (org-get-heading t t t t))))
  6847. ((= dcst ?a)
  6848. (funcall case-func
  6849. (org-sort-remove-invisible (org-get-heading t t t t))))
  6850. ((= dcst ?k)
  6851. (or (get-text-property (point) :org-clock-minutes) 0))
  6852. ((= dcst ?t)
  6853. (let ((end (save-excursion (outline-next-heading) (point))))
  6854. (if (or (re-search-forward org-ts-regexp end t)
  6855. (re-search-forward org-ts-regexp-both end t))
  6856. (org-time-string-to-seconds (match-string 0))
  6857. (float-time now))))
  6858. ((= dcst ?c)
  6859. (let ((end (save-excursion (outline-next-heading) (point))))
  6860. (if (re-search-forward
  6861. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  6862. end t)
  6863. (org-time-string-to-seconds (match-string 0))
  6864. (float-time now))))
  6865. ((= dcst ?s)
  6866. (let ((end (save-excursion (outline-next-heading) (point))))
  6867. (if (re-search-forward org-scheduled-time-regexp end t)
  6868. (org-time-string-to-seconds (match-string 1))
  6869. (float-time now))))
  6870. ((= dcst ?d)
  6871. (let ((end (save-excursion (outline-next-heading) (point))))
  6872. (if (re-search-forward org-deadline-time-regexp end t)
  6873. (org-time-string-to-seconds (match-string 1))
  6874. (float-time now))))
  6875. ((= dcst ?p)
  6876. (if (re-search-forward org-priority-regexp (line-end-position) t)
  6877. (string-to-char (match-string 2))
  6878. org-priority-default))
  6879. ((= dcst ?r)
  6880. (or (org-entry-get nil property) ""))
  6881. ((= dcst ?o)
  6882. (when (looking-at org-complex-heading-regexp)
  6883. (let* ((m (match-string 2))
  6884. (s (if (member m org-done-keywords) '- '+)))
  6885. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  6886. ((= dcst ?f)
  6887. (if getkey-func
  6888. (progn
  6889. (setq tmp (funcall getkey-func))
  6890. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  6891. tmp)
  6892. (error "Invalid key function `%s'" getkey-func)))
  6893. (t (error "Invalid sorting type `%c'" sorting-type))))
  6894. nil
  6895. (cond
  6896. ((= dcst ?a) 'string-collate-lessp)
  6897. ((= dcst ?f)
  6898. (or compare-func
  6899. (and interactive?
  6900. (org-read-function
  6901. (concat "Function for comparing keys "
  6902. "(empty for default `sort-subr' predicate): ")
  6903. 'allow-empty))))
  6904. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
  6905. (org-cycle-hide-drawers 'all)
  6906. (when restore-clock?
  6907. (move-marker org-clock-marker
  6908. (1+ (next-single-property-change
  6909. start :org-clock-marker-backup)))
  6910. (remove-text-properties (1- org-clock-marker) org-clock-marker
  6911. '(:org-clock-marker-backup t)))))
  6912. (run-hooks 'org-after-sorting-entries-or-items-hook)
  6913. (message "Sorting entries...done")))
  6914. (defun org-contextualize-keys (alist contexts)
  6915. "Return valid elements in ALIST depending on CONTEXTS.
  6916. `org-agenda-custom-commands' or `org-capture-templates' are the
  6917. values used for ALIST, and `org-agenda-custom-commands-contexts'
  6918. or `org-capture-templates-contexts' are the associated contexts
  6919. definitions."
  6920. (let ((contexts
  6921. ;; normalize contexts
  6922. (mapcar
  6923. (lambda(c) (cond ((listp (cadr c))
  6924. (list (car c) (car c) (nth 1 c)))
  6925. ((string= "" (cadr c))
  6926. (list (car c) (car c) (nth 2 c)))
  6927. (t c)))
  6928. contexts))
  6929. (a alist) r s)
  6930. ;; loop over all commands or templates
  6931. (dolist (c a)
  6932. (let (vrules repl)
  6933. (cond
  6934. ((not (assoc (car c) contexts))
  6935. (push c r))
  6936. ((and (assoc (car c) contexts)
  6937. (setq vrules (org-contextualize-validate-key
  6938. (car c) contexts)))
  6939. (mapc (lambda (vr)
  6940. (unless (equal (car vr) (cadr vr))
  6941. (setq repl vr)))
  6942. vrules)
  6943. (if (not repl) (push c r)
  6944. (push (cadr repl) s)
  6945. (push
  6946. (cons (car c)
  6947. (cdr (or (assoc (cadr repl) alist)
  6948. (error "Undefined key `%s' as contextual replacement for `%s'"
  6949. (cadr repl) (car c)))))
  6950. r))))))
  6951. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  6952. (delq
  6953. nil
  6954. (delete-dups
  6955. (mapcar (lambda (x)
  6956. (let ((tpl (car x)))
  6957. (unless (delq
  6958. nil
  6959. (mapcar (lambda (y)
  6960. (equal y tpl))
  6961. s))
  6962. x)))
  6963. (reverse r))))))
  6964. (defun org-contextualize-validate-key (key contexts)
  6965. "Check CONTEXTS for agenda or capture KEY."
  6966. (let (res)
  6967. (dolist (r contexts)
  6968. (dolist (rr (car (last r)))
  6969. (when
  6970. (and (equal key (car r))
  6971. (if (functionp rr) (funcall rr)
  6972. (or (and (eq (car rr) 'in-file)
  6973. (buffer-file-name)
  6974. (string-match (cdr rr) (buffer-file-name)))
  6975. (and (eq (car rr) 'in-mode)
  6976. (string-match (cdr rr) (symbol-name major-mode)))
  6977. (and (eq (car rr) 'in-buffer)
  6978. (string-match (cdr rr) (buffer-name)))
  6979. (when (and (eq (car rr) 'not-in-file)
  6980. (buffer-file-name))
  6981. (not (string-match (cdr rr) (buffer-file-name))))
  6982. (when (eq (car rr) 'not-in-mode)
  6983. (not (string-match (cdr rr) (symbol-name major-mode))))
  6984. (when (eq (car rr) 'not-in-buffer)
  6985. (not (string-match (cdr rr) (buffer-name)))))))
  6986. (push r res))))
  6987. (delete-dups (delq nil res))))
  6988. ;; Defined to provide a value for defcustom, since there is no
  6989. ;; string-collate-greaterp in Emacs.
  6990. (defun org-string-collate-greaterp (s1 s2)
  6991. "Return non-nil if S1 is greater than S2 in collation order."
  6992. (not (string-collate-lessp s1 s2)))
  6993. ;;;###autoload
  6994. (defun org-run-like-in-org-mode (cmd)
  6995. "Run a command, pretending that the current buffer is in Org mode.
  6996. This will temporarily bind local variables that are typically bound in
  6997. Org mode to the values they have in Org mode, and then interactively
  6998. call CMD."
  6999. (org-load-modules-maybe)
  7000. (let (vars vals)
  7001. (dolist (var (org-get-local-variables))
  7002. (when (or (not (boundp (car var)))
  7003. (eq (symbol-value (car var))
  7004. (default-value (car var))))
  7005. (push (car var) vars)
  7006. (push (cadr var) vals)))
  7007. (cl-progv vars vals
  7008. (call-interactively cmd))))
  7009. (defun org-get-category (&optional pos force-refresh)
  7010. "Get the category applying to position POS."
  7011. (save-match-data
  7012. (when force-refresh (org-refresh-category-properties))
  7013. (let ((pos (or pos (point))))
  7014. (if (org-element--cache-active-p)
  7015. ;; Sync cache.
  7016. (org-with-point-at (org-element-property :begin (org-element-at-point pos))
  7017. (or (org-entry-get-with-inheritance "CATEGORY")
  7018. "???"))
  7019. (or (get-text-property pos 'org-category)
  7020. (progn
  7021. (org-refresh-category-properties)
  7022. (get-text-property pos 'org-category)))))))
  7023. ;;; Refresh properties
  7024. (defun org-refresh-properties (dprop tprop)
  7025. "Refresh buffer text properties.
  7026. DPROP is the drawer property and TPROP is either the
  7027. corresponding text property to set, or an alist with each element
  7028. being a text property (as a symbol) and a function to apply to
  7029. the value of the drawer property."
  7030. (let* ((case-fold-search t)
  7031. (inhibit-read-only t)
  7032. (inherit? (org-property-inherit-p dprop))
  7033. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  7034. (global-or-keyword (and inherit?
  7035. (org--property-global-or-keyword-value dprop nil))))
  7036. (with-silent-modifications
  7037. (org-with-point-at 1
  7038. ;; Set global and keyword based values to the whole buffer.
  7039. (when global-or-keyword
  7040. (put-text-property (point-min) (point-max) tprop global-or-keyword))
  7041. ;; Set values based on property-drawers throughout the document.
  7042. (while (re-search-forward property-re nil t)
  7043. (when (org-at-property-p)
  7044. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  7045. (outline-next-heading))))))
  7046. (defun org-refresh-property (tprop p &optional inherit)
  7047. "Refresh the buffer text property TPROP from the drawer property P.
  7048. The refresh happens only for the current entry, or the whole
  7049. sub-tree if optional argument INHERIT is non-nil.
  7050. If point is before first headline, the function applies to the
  7051. part before the first headline. In that particular case, when
  7052. optional argument INHERIT is non-nil, it refreshes properties for
  7053. the whole buffer."
  7054. (save-excursion
  7055. (org-back-to-heading-or-point-min t)
  7056. (let ((start (point))
  7057. (end (save-excursion
  7058. (cond ((and inherit (org-before-first-heading-p))
  7059. (point-max))
  7060. (inherit
  7061. (org-end-of-subtree t t))
  7062. ((outline-next-heading))
  7063. ((point-max))))))
  7064. (with-silent-modifications
  7065. (if (symbolp tprop)
  7066. ;; TPROP is a text property symbol.
  7067. (put-text-property start end tprop p)
  7068. ;; TPROP is an alist with (property . function) elements.
  7069. (pcase-dolist (`(,prop . ,f) tprop)
  7070. (put-text-property start end prop (funcall f p))))))))
  7071. (defun org-refresh-category-properties ()
  7072. "Refresh category text properties in the buffer."
  7073. (unless (org-element--cache-active-p)
  7074. (let ((case-fold-search t)
  7075. (inhibit-read-only t)
  7076. (default-category
  7077. (cond ((null org-category)
  7078. (if buffer-file-name
  7079. (file-name-sans-extension
  7080. (file-name-nondirectory buffer-file-name))
  7081. "???"))
  7082. ((symbolp org-category) (symbol-name org-category))
  7083. (t org-category))))
  7084. (let ((category (catch 'buffer-category
  7085. (org-with-wide-buffer
  7086. (goto-char (point-max))
  7087. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  7088. (let ((element (org-element-at-point-no-context)))
  7089. (when (eq (org-element-type element) 'keyword)
  7090. (throw 'buffer-category
  7091. (org-element-property :value element))))))
  7092. default-category)))
  7093. (with-silent-modifications
  7094. (org-with-wide-buffer
  7095. ;; Set buffer-wide property from keyword. Search last #+CATEGORY
  7096. ;; keyword. If none is found, fall-back to `org-category' or
  7097. ;; buffer file name, or set it by the document property drawer.
  7098. (put-text-property (point-min) (point-max)
  7099. 'org-category category)
  7100. ;; Set categories from the document property drawer or
  7101. ;; property drawers in the outline. If category is found in
  7102. ;; the property drawer for the whole buffer that value
  7103. ;; overrides the keyword-based value set above.
  7104. (goto-char (point-min))
  7105. (let ((regexp (org-re-property "CATEGORY")))
  7106. (while (re-search-forward regexp nil t)
  7107. (let ((value (match-string-no-properties 3)))
  7108. (when (org-at-property-p)
  7109. (put-text-property
  7110. (save-excursion (org-back-to-heading-or-point-min t))
  7111. (save-excursion (if (org-before-first-heading-p)
  7112. (point-max)
  7113. (org-end-of-subtree t t)))
  7114. 'org-category
  7115. value)))))))))))
  7116. (defun org-refresh-stats-properties ()
  7117. "Refresh stats text properties in the buffer."
  7118. (with-silent-modifications
  7119. (org-with-point-at 1
  7120. (let ((regexp (concat org-outline-regexp-bol
  7121. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  7122. (while (re-search-forward regexp nil t)
  7123. (let* ((numerator (string-to-number (match-string 1)))
  7124. (denominator (and (match-end 2)
  7125. (string-to-number (match-string 2))))
  7126. (stats (cond ((not denominator) numerator) ;percent
  7127. ((= denominator 0) 0)
  7128. (t (/ (* numerator 100) denominator)))))
  7129. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  7130. 'org-stats stats)))))))
  7131. (defun org-refresh-effort-properties ()
  7132. "Refresh effort properties."
  7133. (org-refresh-properties
  7134. org-effort-property
  7135. '((effort . identity)
  7136. (effort-minutes . org-duration-to-minutes))))
  7137. (defun org-find-file-at-mouse (ev)
  7138. "Open file link or URL at mouse."
  7139. (interactive "e")
  7140. (mouse-set-point ev)
  7141. (org-open-at-point 'in-emacs))
  7142. (defun org-open-at-mouse (ev)
  7143. "Open file link or URL at mouse.
  7144. See the docstring of `org-open-file' for details."
  7145. (interactive "e")
  7146. (mouse-set-point ev)
  7147. (when (eq major-mode 'org-agenda-mode)
  7148. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  7149. (org-open-at-point))
  7150. (defvar org-window-config-before-follow-link nil
  7151. "The window configuration before following a link.
  7152. This is saved in case the need arises to restore it.")
  7153. (defun org--file-default-apps ()
  7154. "Return the default applications for this operating system."
  7155. (pcase system-type
  7156. (`darwin org-file-apps-macos)
  7157. (`windows-nt org-file-apps-windowsnt)
  7158. (_ org-file-apps-gnu)))
  7159. (defun org--file-apps-entry-locator-p (entry)
  7160. "Non-nil if ENTRY should be matched against the link by `org-open-file'.
  7161. It assumes that is the case when the entry uses a regular
  7162. expression which has at least one grouping construct and the
  7163. action is either a Lisp form or a command string containing
  7164. \"%1\", i.e., using at least one subexpression match as
  7165. a parameter."
  7166. (pcase entry
  7167. (`(,selector . ,action)
  7168. (and (stringp selector)
  7169. (> (regexp-opt-depth selector) 0)
  7170. (or (and (stringp action)
  7171. (string-match "%[0-9]" action))
  7172. (functionp action))))
  7173. (_ nil)))
  7174. (defun org--file-apps-regexp-alist (list &optional add-auto-mode)
  7175. "Convert extensions to regular expressions in the cars of LIST.
  7176. Also, weed out any non-string entries, because the return value
  7177. is used only for regexp matching.
  7178. When ADD-AUTO-MODE is non-nil, make all matches in `auto-mode-alist'
  7179. point to the symbol `emacs', indicating that the file should be
  7180. opened in Emacs."
  7181. (append
  7182. (delq nil
  7183. (mapcar (lambda (x)
  7184. (unless (not (stringp (car x)))
  7185. (if (string-match "\\W" (car x))
  7186. x
  7187. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  7188. list))
  7189. (when add-auto-mode
  7190. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  7191. (defun org--open-file-format-command
  7192. (mailcap-command file link match-data)
  7193. "Format MAILCAP-COMMAND to launch viewer for the FILE.
  7194. MAILCAP-COMMAND may be an entry from the `org-file-apps' list or viewer
  7195. field from mailcap file loaded to `mailcap-mime-data'. See \"RFC
  7196. 1524. A User Agent Configuration Mechanism For Multimedia Mail Format
  7197. Information\" (URL `https://www.rfc-editor.org/rfc/rfc1524.html') for
  7198. details, man page `mailcap(5)' for brief summary, and Info node
  7199. `(emacs-mime) mailcap' for specific related to Emacs. Only a part of
  7200. mailcap specification is supported.
  7201. The following substitutions are interpolated in the MAILCAP-COMMAND
  7202. string:
  7203. - \"%s\" to FILE name passed through
  7204. `convert-standard-filename', so it must be absolute path.
  7205. - \"%1\" to \"%9\" groups from MATCH-DATA found in the LINK string by
  7206. the regular expression in the key part of the `org-file-apps' entry.
  7207. (performed by caller). Not recommended, consider a lisp function
  7208. instead of a shell command. For example, the following link in an
  7209. Org file
  7210. <file:///usr/share/doc/bash/bashref.pdf::#Redirections::allocate a file>
  7211. may be handled by an `org-file-apps' entry like
  7212. (\"\\\\.pdf\\\\(?:\\\\.[gx]z\\\\|\\\\.bz2\\\\)?::\\\\(#[^:]+\\\\)::\\\\(.+\\\\)\\\\\\='\"
  7213. . \"okular --find %2 %s%1\")
  7214. Use backslash \"\\\" to quote percent \"%\" or any other character
  7215. including backslash itself.
  7216. In addition, each argument is passed through `shell-quote-argument',
  7217. so quotes around substitutions should not be used. For compliance
  7218. with mailcap files shipped e.g. in Debian GNU/Linux, single or double
  7219. quotes around substitutions are stripped. It deviates from mailcap
  7220. specification that requires file name to be safe for shell and for the
  7221. application."
  7222. (let ((spec (list (cons ?s (convert-standard-filename file))))
  7223. (ngroups (min 9 (- (/ (length match-data) 2) 1))))
  7224. (when (> ngroups 0)
  7225. (set-match-data match-data)
  7226. (dolist (i (number-sequence 1 ngroups))
  7227. (push (cons (+ ?0 i) (match-string-no-properties i link)) spec)))
  7228. (replace-regexp-in-string
  7229. (rx (or (and "\\" (or (group anything) string-end))
  7230. (and (optional (group (any "'\"")))
  7231. "%"
  7232. (or (group anything) string-end)
  7233. (optional (group (backref 2))))))
  7234. (lambda (fmt)
  7235. (let* ((backslash (match-string-no-properties 1 fmt))
  7236. (key (match-string 3 fmt))
  7237. (value (and key (alist-get (string-to-char key) spec))))
  7238. (cond
  7239. (backslash)
  7240. (value (let ((quot (match-string 2 fmt))
  7241. (subst (shell-quote-argument value)))
  7242. ;; Remove quotes around the file name - we use
  7243. ;; `shell-quote-argument'.
  7244. (if (match-string 4 fmt)
  7245. subst
  7246. (concat quot subst))))
  7247. (t (error "Invalid format `%s'" fmt)))))
  7248. mailcap-command nil 'literal)))
  7249. ;;;###autoload
  7250. (defun org-open-file (path &optional in-emacs line search)
  7251. "Open the file at PATH.
  7252. First, this expands any special file name abbreviations. Then the
  7253. configuration variable `org-file-apps' is checked if it contains an
  7254. entry for this file type, and if yes, the corresponding command is launched.
  7255. If no application is found, Emacs simply visits the file.
  7256. With optional prefix argument IN-EMACS, Emacs will visit the file.
  7257. With a double \\[universal-argument] \\[universal-argument] \
  7258. prefix arg, Org tries to avoid opening in Emacs
  7259. and to use an external application to visit the file.
  7260. Optional LINE specifies a line to go to, optional SEARCH a string
  7261. to search for. If LINE or SEARCH is given, the file will be
  7262. opened in Emacs, unless an entry from `org-file-apps' that makes
  7263. use of groups in a regexp matches.
  7264. If you want to change the way frames are used when following a
  7265. link, please customize `org-link-frame-setup'.
  7266. If the file does not exist, throw an error."
  7267. (let* ((file (if (equal path "") buffer-file-name
  7268. (substitute-in-file-name (expand-file-name path))))
  7269. (file-apps (append org-file-apps (org--file-default-apps)))
  7270. (apps (cl-remove-if #'org--file-apps-entry-locator-p file-apps))
  7271. (apps-locator (cl-remove-if-not #'org--file-apps-entry-locator-p
  7272. file-apps))
  7273. (remp (and (assq 'remote apps) (file-remote-p file)))
  7274. (dirp (unless remp (file-directory-p file)))
  7275. (file (if (and dirp org-open-directory-means-index-dot-org)
  7276. (concat (file-name-as-directory file) "index.org")
  7277. file))
  7278. (a-m-a-p (assq 'auto-mode apps))
  7279. (dfile (downcase file))
  7280. ;; Reconstruct the original link from the PATH, LINE and
  7281. ;; SEARCH args.
  7282. (link (cond (line (concat file "::" (number-to-string line)))
  7283. (search (concat file "::" search))
  7284. (t file)))
  7285. (ext
  7286. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  7287. (match-string 1 dfile)))
  7288. (save-position-maybe
  7289. (let ((old-buffer (current-buffer))
  7290. (old-pos (point))
  7291. (old-mode major-mode))
  7292. (lambda ()
  7293. (and (derived-mode-p 'org-mode)
  7294. (eq old-mode 'org-mode)
  7295. (or (not (eq old-buffer (current-buffer)))
  7296. (not (eq old-pos (point))))
  7297. (org-mark-ring-push old-pos old-buffer)))))
  7298. cmd link-match-data)
  7299. (cond
  7300. ((member in-emacs '((16) system))
  7301. (setq cmd (cdr (assq 'system apps))))
  7302. (in-emacs (setq cmd 'emacs))
  7303. (t
  7304. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  7305. (and dirp (cdr (assq 'directory apps)))
  7306. ;; First, try matching against apps-locator if we
  7307. ;; get a match here, store the match data for
  7308. ;; later.
  7309. (let* ((case-fold-search t)
  7310. (match (assoc-default link apps-locator
  7311. 'string-match)))
  7312. (if match
  7313. (progn (setq link-match-data (match-data))
  7314. match)
  7315. (progn (setq in-emacs (or in-emacs line search))
  7316. nil))) ; if we have no match in apps-locator,
  7317. ; always open the file in emacs if line or search
  7318. ; is given (for backwards compatibility)
  7319. (assoc-default dfile
  7320. (org--file-apps-regexp-alist apps a-m-a-p)
  7321. 'string-match)
  7322. (cdr (assoc ext apps))
  7323. (cdr (assq t apps))))))
  7324. (when (eq cmd 'system)
  7325. (setq cmd (cdr (assq 'system apps))))
  7326. (when (eq cmd 'default)
  7327. (setq cmd (cdr (assoc t apps))))
  7328. (when (eq cmd 'mailcap)
  7329. (require 'mailcap)
  7330. (mailcap-parse-mailcaps)
  7331. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  7332. (command (mailcap-mime-info mime-type)))
  7333. (if (stringp command)
  7334. (setq cmd command)
  7335. (setq cmd 'emacs))))
  7336. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  7337. (not (file-exists-p file))
  7338. (not org-open-non-existing-files))
  7339. (user-error "No such file: %s" file))
  7340. (cond
  7341. ((org-string-nw-p cmd)
  7342. (setq cmd (org--open-file-format-command cmd file link link-match-data))
  7343. (save-window-excursion
  7344. (message "Running %s...done" cmd)
  7345. ;; Handlers such as "gio open" and kde-open5 start viewer in background
  7346. ;; and exit immediately. Use pipe connection type instead of pty to
  7347. ;; avoid killing children processes with SIGHUP when temporary terminal
  7348. ;; session is finished.
  7349. ;;
  7350. ;; TODO: Once minimum Emacs version is 25.1 or above, consider using
  7351. ;; the `make-process' invocation from 5db61eb0f929 to get more helpful
  7352. ;; error messages.
  7353. (let ((process-connection-type nil))
  7354. (start-process-shell-command cmd nil cmd))
  7355. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  7356. ((or (stringp cmd)
  7357. (eq cmd 'emacs))
  7358. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  7359. (widen)
  7360. (cond (line (org-goto-line line)
  7361. (when (derived-mode-p 'org-mode) (org-fold-reveal)))
  7362. (search (condition-case err
  7363. (org-link-search search)
  7364. ;; Save position before error-ing out so user
  7365. ;; can easily move back to the original buffer.
  7366. (error (funcall save-position-maybe)
  7367. (error (nth 1 err)))))))
  7368. ((functionp cmd)
  7369. (save-match-data
  7370. (set-match-data link-match-data)
  7371. (condition-case nil
  7372. (funcall cmd file link)
  7373. ;; FIXME: Remove this check when most default installations
  7374. ;; of Emacs have at least Org 9.0.
  7375. ((debug wrong-number-of-arguments wrong-type-argument
  7376. invalid-function)
  7377. (user-error "Please see Org News for version 9.0 about \
  7378. `org-file-apps'--Lisp error: %S" cmd)))))
  7379. ((consp cmd)
  7380. ;; FIXME: Remove this check when most default installations of
  7381. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  7382. ;; fall back to `org-link-frame-setup' for an old usage of
  7383. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  7384. (user-error "Please see Org News for version 9.0 about \
  7385. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  7386. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  7387. (funcall save-position-maybe)))
  7388. ;;;###autoload
  7389. (defun org-open-at-point-global ()
  7390. "Follow a link or a time-stamp like Org mode does.
  7391. Also follow links and emails as seen by `thing-at-point'.
  7392. This command can be called in any mode to follow an external
  7393. link or a time-stamp that has Org mode syntax. Its behavior
  7394. is undefined when called on internal links like fuzzy links.
  7395. Raise a user error when there is nothing to follow."
  7396. (interactive)
  7397. (let ((tap-url (thing-at-point 'url))
  7398. (tap-email (thing-at-point 'email)))
  7399. (cond ((org-in-regexp org-link-any-re)
  7400. (org-link-open-from-string (match-string-no-properties 0)))
  7401. ((or (org-in-regexp org-ts-regexp-both nil t)
  7402. (org-in-regexp org-tsr-regexp-both nil t))
  7403. (org-follow-timestamp-link))
  7404. (tap-url (org-link-open-from-string tap-url))
  7405. (tap-email (org-link-open-from-string
  7406. (concat "mailto:" tap-email)))
  7407. (t (user-error "No link found")))))
  7408. (defvar org-open-at-point-functions nil
  7409. "Hook that is run when following a link at point.
  7410. Functions in this hook must return t if they identify and follow
  7411. a link at point. If they don't find anything interesting at point,
  7412. they must return nil.")
  7413. (defun org-open-at-point (&optional arg)
  7414. "Open thing at point.
  7415. The thing can be a link, citation, timestamp, footnote, src-block or
  7416. tags.
  7417. When point is on a link, follow it. Normally, files will be
  7418. opened by an appropriate application. If the optional prefix
  7419. argument ARG is non-nil, Emacs will visit the file. With
  7420. a double prefix argument, try to open outside of Emacs, in the
  7421. application the system uses for this file type.
  7422. When point is on a timestamp, open the agenda at the day
  7423. specified.
  7424. When point is a footnote definition, move to the first reference
  7425. found. If it is on a reference, move to the associated
  7426. definition.
  7427. When point is on a src-block of inline src-block, open its result.
  7428. When point is on a citation, follow it.
  7429. When point is on a headline, display a list of every link in the
  7430. entry, so it is possible to pick one, or all, of them. If point
  7431. is on a tag, call `org-tags-view' instead.
  7432. On top of syntactically correct links, this function also tries
  7433. to open links and time-stamps in comments, node properties, and
  7434. keywords if point is on something looking like a timestamp or
  7435. a link."
  7436. (interactive "P")
  7437. (org-load-modules-maybe)
  7438. (setq org-window-config-before-follow-link (current-window-configuration))
  7439. (org-remove-occur-highlights nil nil t)
  7440. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  7441. (let* ((context
  7442. ;; Only consider supported types, even if they are not the
  7443. ;; closest one.
  7444. (org-element-lineage
  7445. (org-element-context)
  7446. '(citation citation-reference clock comment comment-block
  7447. footnote-definition footnote-reference headline
  7448. inline-src-block inlinetask keyword link node-property
  7449. planning src-block timestamp)
  7450. t))
  7451. (type (org-element-type context))
  7452. (value (org-element-property :value context)))
  7453. (cond
  7454. ((not type) (user-error "No link found"))
  7455. ;; No valid link at point. For convenience, look if something
  7456. ;; looks like a link under point in some specific places.
  7457. ((memq type '(comment comment-block node-property keyword))
  7458. (call-interactively #'org-open-at-point-global))
  7459. ;; On a headline or an inlinetask, but not on a timestamp,
  7460. ;; a link, a footnote reference or a citation.
  7461. ((memq type '(headline inlinetask))
  7462. (org-match-line org-complex-heading-regexp)
  7463. (let ((tags-beg (match-beginning 5))
  7464. (tags-end (match-end 5)))
  7465. (if (and tags-beg (>= (point) tags-beg) (< (point) tags-end))
  7466. ;; On tags.
  7467. (org-tags-view
  7468. arg
  7469. (save-excursion
  7470. (let* ((beg-tag (or (search-backward ":" tags-beg 'at-limit) (point)))
  7471. (end-tag (search-forward ":" tags-end nil 2)))
  7472. (buffer-substring (1+ beg-tag) (1- end-tag)))))
  7473. ;; Not on tags.
  7474. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  7475. (`(nil . ,_)
  7476. (require 'org-attach)
  7477. (when (org-attach-dir)
  7478. (message "Opening attachment")
  7479. (if (equal arg '(4))
  7480. (org-attach-reveal-in-emacs)
  7481. (org-attach-reveal))))
  7482. (`(,links . ,links-end)
  7483. (dolist (link (if (stringp links) (list links) links))
  7484. (search-forward link nil links-end)
  7485. (goto-char (match-beginning 0))
  7486. (org-open-at-point arg)))))))
  7487. ;; On a footnote reference or at definition's label.
  7488. ((or (eq type 'footnote-reference)
  7489. (and (eq type 'footnote-definition)
  7490. (save-excursion
  7491. ;; Do not validate action when point is on the
  7492. ;; spaces right after the footnote label, in order
  7493. ;; to be on par with behavior on links.
  7494. (skip-chars-forward " \t")
  7495. (let ((begin
  7496. (org-element-property :contents-begin context)))
  7497. (if begin (< (point) begin)
  7498. (= (org-element-property :post-affiliated context)
  7499. (line-beginning-position)))))))
  7500. (org-footnote-action))
  7501. ;; On a planning line. Check if we are really on a timestamp.
  7502. ((and (eq type 'planning)
  7503. (org-in-regexp org-ts-regexp-both nil t))
  7504. (org-follow-timestamp-link))
  7505. ;; On a clock line, make sure point is on the timestamp
  7506. ;; before opening it.
  7507. ((and (eq type 'clock)
  7508. value
  7509. (>= (point) (org-element-property :begin value))
  7510. (<= (point) (org-element-property :end value)))
  7511. (org-follow-timestamp-link))
  7512. ((eq type 'src-block) (org-babel-open-src-block-result))
  7513. ;; Do nothing on white spaces after an object.
  7514. ((>= (point)
  7515. (save-excursion
  7516. (goto-char (org-element-property :end context))
  7517. (skip-chars-backward " \t")
  7518. (point)))
  7519. (user-error "No link found"))
  7520. ((eq type 'inline-src-block) (org-babel-open-src-block-result))
  7521. ((eq type 'timestamp) (org-follow-timestamp-link))
  7522. ((eq type 'link) (org-link-open context arg))
  7523. ((memq type '(citation citation-reference)) (org-cite-follow context arg))
  7524. (t (user-error "No link found")))))
  7525. (run-hook-with-args 'org-follow-link-hook))
  7526. ;;;###autoload
  7527. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  7528. "Offer links in the current entry and return the selected link.
  7529. If there is only one link, return it.
  7530. If NTH is an integer, return the NTH link found.
  7531. If ZERO is a string, check also this string for a link, and if
  7532. there is one, return it."
  7533. (with-current-buffer buffer
  7534. (org-with-wide-buffer
  7535. (goto-char marker)
  7536. (let ((cnt ?0)
  7537. have-zero end links link c)
  7538. (when (and (stringp zero) (string-match org-link-bracket-re zero))
  7539. (push (match-string 0 zero) links)
  7540. (setq cnt (1- cnt) have-zero t))
  7541. (save-excursion
  7542. (org-back-to-heading t)
  7543. (setq end (save-excursion (outline-next-heading) (point)))
  7544. (while (re-search-forward org-link-any-re end t)
  7545. ;; Only consider valid links or links openable via
  7546. ;; `org-open-at-point'.
  7547. (when (memq (org-element-type (org-element-context)) '(link comment comment-block node-property keyword))
  7548. (push (match-string 0) links)))
  7549. (setq links (org-uniquify (reverse links))))
  7550. (cond
  7551. ((null links)
  7552. (message "No links"))
  7553. ((equal (length links) 1)
  7554. (setq link (car links)))
  7555. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  7556. (setq link (nth (if have-zero nth (1- nth)) links)))
  7557. (t ; we have to select a link
  7558. (save-excursion
  7559. (save-window-excursion
  7560. (delete-other-windows)
  7561. (with-output-to-temp-buffer "*Select Link*"
  7562. (dolist (l links)
  7563. (cond
  7564. ((not (string-match org-link-bracket-re l))
  7565. (princ (format "[%c] %s\n" (cl-incf cnt)
  7566. (org-unbracket-string "<" ">" l))))
  7567. ((match-end 2)
  7568. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  7569. (match-string 2 l) (match-string 1 l))))
  7570. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  7571. (match-string 1 l)))))))
  7572. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  7573. (message "Select link to open, RET to open all:")
  7574. (setq c (read-char-exclusive))
  7575. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  7576. (when (equal c ?q) (user-error "Abort"))
  7577. (if (equal c ?\C-m)
  7578. (setq link links)
  7579. (setq nth (- c ?0))
  7580. (when have-zero (setq nth (1+ nth)))
  7581. (unless (and (integerp nth) (>= (length links) nth))
  7582. (user-error "Invalid link selection"))
  7583. (setq link (nth (1- nth) links)))))
  7584. (cons link end)))))
  7585. ;;; File search
  7586. (defun org-do-occur (regexp &optional cleanup)
  7587. "Call the Emacs command `occur'.
  7588. If CLEANUP is non-nil, remove the printout of the regular expression
  7589. in the *Occur* buffer. This is useful if the regex is long and not useful
  7590. to read."
  7591. (occur regexp)
  7592. (when cleanup
  7593. (let ((cwin (selected-window)) win beg end)
  7594. (when (setq win (get-buffer-window "*Occur*"))
  7595. (select-window win))
  7596. (goto-char (point-min))
  7597. (when (re-search-forward "match[a-z]+" nil t)
  7598. (setq beg (match-end 0))
  7599. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  7600. (setq end (1- (match-beginning 0)))))
  7601. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  7602. (goto-char (point-min))
  7603. (select-window cwin))))
  7604. ;;; The Mark Ring
  7605. (defvar org-mark-ring nil
  7606. "Mark ring for positions before jumps in Org mode.")
  7607. (defvar org-mark-ring-last-goto nil
  7608. "Last position in the mark ring used to go back.")
  7609. ;; Fill and close the ring
  7610. (setq org-mark-ring nil)
  7611. (setq org-mark-ring-last-goto nil) ;in case file is reloaded
  7612. (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
  7613. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  7614. org-mark-ring)
  7615. (defun org-mark-ring-push (&optional pos buffer)
  7616. "Put the current position into the mark ring and rotate it.
  7617. Also push position into the Emacs mark ring. If optional
  7618. argument POS and BUFFER are not nil, mark this location instead."
  7619. (interactive)
  7620. (let ((pos (or pos (point)))
  7621. (buffer (or buffer (current-buffer))))
  7622. (with-current-buffer buffer
  7623. (org-with-point-at pos (push-mark nil t)))
  7624. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  7625. (move-marker (car org-mark-ring) pos buffer))
  7626. (message
  7627. (substitute-command-keys
  7628. "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
  7629. (defun org-mark-ring-goto (&optional n)
  7630. "Jump to the previous position in the mark ring.
  7631. With prefix arg N, jump back that many stored positions. When
  7632. called several times in succession, walk through the entire ring.
  7633. Org mode commands jumping to a different position in the current file,
  7634. or to another Org file, automatically push the old position onto the ring."
  7635. (interactive "p")
  7636. (let (p m)
  7637. (if (eq last-command this-command)
  7638. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  7639. (setq p org-mark-ring))
  7640. (setq org-mark-ring-last-goto p)
  7641. (setq m (car p))
  7642. (pop-to-buffer-same-window (marker-buffer m))
  7643. (goto-char m)
  7644. (when (or (org-invisible-p) (org-invisible-p2)) (org-fold-show-context 'mark-goto))))
  7645. ;;; Following specific links
  7646. (defvar org-agenda-buffer-tmp-name)
  7647. (defvar org-agenda-start-on-weekday)
  7648. (defvar org-agenda-buffer-name)
  7649. (defun org-follow-timestamp-link ()
  7650. "Open an agenda view for the time-stamp date/range at point."
  7651. ;; Avoid changing the global value.
  7652. (let ((org-agenda-buffer-name org-agenda-buffer-name))
  7653. (cond
  7654. ((org-at-date-range-p t)
  7655. (let ((org-agenda-start-on-weekday)
  7656. (t1 (match-string 1))
  7657. (t2 (match-string 2)) tt1 tt2)
  7658. (setq tt1 (time-to-days (org-time-string-to-time t1))
  7659. tt2 (time-to-days (org-time-string-to-time t2)))
  7660. (let ((org-agenda-buffer-tmp-name
  7661. (format "*Org Agenda(a:%s)"
  7662. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  7663. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  7664. ((org-at-timestamp-p 'lax)
  7665. (let ((org-agenda-buffer-tmp-name
  7666. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  7667. (org-agenda-list nil (time-to-days (org-time-string-to-time
  7668. (substring (match-string 1) 0 10)))
  7669. 1)))
  7670. (t (error "This should not happen")))))
  7671. ;;; Following file links
  7672. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  7673. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  7674. (declare-function mailcap-mime-info
  7675. "mailcap" (string &optional request no-decode))
  7676. (defvar org-wait nil)
  7677. ;;;; Refiling
  7678. (defun org-get-org-file ()
  7679. "Read a filename, with default directory `org-directory'."
  7680. (let ((default (or org-default-notes-file remember-data-file)))
  7681. (read-file-name (format "File name [%s]: " default)
  7682. (file-name-as-directory org-directory)
  7683. default)))
  7684. (defun org-notes-order-reversed-p ()
  7685. "Check if the current file should receive notes in reversed order."
  7686. (cond
  7687. ((not org-reverse-note-order) nil)
  7688. ((eq t org-reverse-note-order) t)
  7689. ((not (listp org-reverse-note-order)) nil)
  7690. (t (catch 'exit
  7691. (dolist (entry org-reverse-note-order)
  7692. (when (string-match (car entry) buffer-file-name)
  7693. (throw 'exit (cdr entry))))))))
  7694. (defvar org-agenda-new-buffers nil
  7695. "Buffers created to visit agenda files.")
  7696. (declare-function org-string-nw-p "org-macs" (s))
  7697. ;;;; Dynamic blocks
  7698. (defun org-find-dblock (name)
  7699. "Find the first dynamic block with name NAME in the buffer.
  7700. If not found, stay at current position and return nil."
  7701. (let ((case-fold-search t) pos)
  7702. (save-excursion
  7703. (goto-char (point-min))
  7704. (setq pos (and (re-search-forward
  7705. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  7706. (match-beginning 0))))
  7707. (when pos (goto-char pos))
  7708. pos))
  7709. (defun org-create-dblock (plist)
  7710. "Create a dynamic block section, with parameters taken from PLIST.
  7711. PLIST must contain a :name entry which is used as the name of the block."
  7712. (when (string-match "\\S-" (buffer-substring (line-beginning-position)
  7713. (line-end-position)))
  7714. (end-of-line 1)
  7715. (newline))
  7716. (let ((col (current-column))
  7717. (name (plist-get plist :name)))
  7718. (insert "#+BEGIN: " name)
  7719. (while plist
  7720. (if (eq (car plist) :name)
  7721. (setq plist (cddr plist))
  7722. (insert " " (prin1-to-string (pop plist)))))
  7723. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  7724. (beginning-of-line -2)))
  7725. (defun org-prepare-dblock ()
  7726. "Prepare dynamic block for refresh.
  7727. This empties the block, puts the cursor at the insert position and returns
  7728. the property list including an extra property :name with the block name."
  7729. (unless (looking-at org-dblock-start-re)
  7730. (user-error "Not at a dynamic block"))
  7731. (let* ((begdel (1+ (match-end 0)))
  7732. (name (org-no-properties (match-string 1)))
  7733. (params (append (list :name name)
  7734. (read (concat "(" (match-string 3) ")")))))
  7735. (save-excursion
  7736. (beginning-of-line 1)
  7737. (skip-chars-forward " \t")
  7738. (setq params (plist-put params :indentation-column (current-column))))
  7739. (unless (re-search-forward org-dblock-end-re nil t)
  7740. (error "Dynamic block not terminated"))
  7741. (setq params
  7742. (append params
  7743. (list :content (buffer-substring
  7744. begdel (match-beginning 0)))))
  7745. (delete-region begdel (match-beginning 0))
  7746. (goto-char begdel)
  7747. (open-line 1)
  7748. params))
  7749. (defun org-map-dblocks (&optional command)
  7750. "Apply COMMAND to all dynamic blocks in the current buffer.
  7751. If COMMAND is not given, use `org-update-dblock'."
  7752. (let ((cmd (or command 'org-update-dblock)))
  7753. (save-excursion
  7754. (goto-char (point-min))
  7755. (while (re-search-forward org-dblock-start-re nil t)
  7756. (goto-char (match-beginning 0))
  7757. (save-excursion
  7758. (condition-case nil
  7759. (funcall cmd)
  7760. (error (message "Error during update of dynamic block"))))
  7761. (unless (re-search-forward org-dblock-end-re nil t)
  7762. (error "Dynamic block not terminated"))))))
  7763. (defvar org-dynamic-block-alist nil
  7764. "Alist defining all the Org dynamic blocks.
  7765. The key is the dynamic block type name, as a string. The value
  7766. is the function used to insert the dynamic block.
  7767. Use `org-dynamic-block-define' to populate it.")
  7768. (defun org-dynamic-block-function (type)
  7769. "Return function associated to a given dynamic block type.
  7770. TYPE is the dynamic block type, as a string."
  7771. (cdr (assoc type org-dynamic-block-alist)))
  7772. (defun org-dynamic-block-types ()
  7773. "List all defined dynamic block types."
  7774. (mapcar #'car org-dynamic-block-alist))
  7775. ;;;###org-autoload
  7776. (defun org-dynamic-block-define (type func)
  7777. "Define dynamic block TYPE with FUNC.
  7778. TYPE is a string. FUNC is the function creating the dynamic
  7779. block of such type."
  7780. (pcase (assoc type org-dynamic-block-alist)
  7781. (`nil (push (cons type func) org-dynamic-block-alist))
  7782. (def (setcdr def func))))
  7783. (defun org-dynamic-block-insert-dblock (type &optional interactive-p)
  7784. "Insert a dynamic block of type TYPE.
  7785. When used interactively, select the dynamic block types among
  7786. defined types, per `org-dynamic-block-define'. If INTERACTIVE-P
  7787. is non-nil, call the dynamic block function interactively."
  7788. (interactive (list (completing-read "Dynamic block: "
  7789. (org-dynamic-block-types))
  7790. t))
  7791. (pcase (org-dynamic-block-function type)
  7792. (`nil (error "No such dynamic block: %S" type))
  7793. ((and f (pred functionp))
  7794. (if interactive-p (call-interactively f) (funcall f)))
  7795. (_ (error "Invalid function for dynamic block %S" type))))
  7796. (defun org-dblock-update (&optional arg)
  7797. "User command for updating dynamic blocks.
  7798. Update the dynamic block at point. With prefix ARG, update all dynamic
  7799. blocks in the buffer."
  7800. (interactive "P")
  7801. (if arg
  7802. (org-update-all-dblocks)
  7803. (or (looking-at org-dblock-start-re)
  7804. (org-beginning-of-dblock))
  7805. (org-update-dblock)))
  7806. (defun org-update-dblock ()
  7807. "Update the dynamic block at point.
  7808. This means to empty the block, parse for parameters and then call
  7809. the correct writing function."
  7810. (interactive)
  7811. (save-excursion
  7812. (let* ((win (selected-window))
  7813. (pos (point))
  7814. (line (org-current-line))
  7815. (params (org-prepare-dblock))
  7816. (name (plist-get params :name))
  7817. (indent (plist-get params :indentation-column))
  7818. (cmd (intern (concat "org-dblock-write:" name))))
  7819. (message "Updating dynamic block `%s' at line %d..." name line)
  7820. (funcall cmd params)
  7821. (message "Updating dynamic block `%s' at line %d...done" name line)
  7822. (goto-char pos)
  7823. (when (and indent (> indent 0))
  7824. (setq indent (make-string indent ?\ ))
  7825. (save-excursion
  7826. (select-window win)
  7827. (org-beginning-of-dblock)
  7828. (forward-line 1)
  7829. (while (not (looking-at org-dblock-end-re))
  7830. (insert indent)
  7831. (beginning-of-line 2))
  7832. (when (looking-at org-dblock-end-re)
  7833. (and (looking-at "[ \t]+")
  7834. (replace-match ""))
  7835. (insert indent)))))))
  7836. (defun org-beginning-of-dblock ()
  7837. "Find the beginning of the dynamic block at point.
  7838. Error if there is no such block at point."
  7839. (let ((pos (point))
  7840. beg)
  7841. (end-of-line 1)
  7842. (if (and (re-search-backward org-dblock-start-re nil t)
  7843. (setq beg (match-beginning 0))
  7844. (re-search-forward org-dblock-end-re nil t)
  7845. (> (match-end 0) pos))
  7846. (goto-char beg)
  7847. (goto-char pos)
  7848. (error "Not in a dynamic block"))))
  7849. (defun org-update-all-dblocks ()
  7850. "Update all dynamic blocks in the buffer.
  7851. This function can be used in a hook."
  7852. (interactive)
  7853. (when (derived-mode-p 'org-mode)
  7854. (org-map-dblocks 'org-update-dblock)))
  7855. ;;;; Completion
  7856. (declare-function org-export-backend-options "ox" (cl-x) t)
  7857. (defun org-get-export-keywords ()
  7858. "Return a list of all currently understood export keywords.
  7859. Export keywords include options, block names, attributes and
  7860. keywords relative to each registered export back-end."
  7861. (let (keywords)
  7862. (dolist (backend
  7863. (bound-and-true-p org-export-registered-backends)
  7864. (delq nil keywords))
  7865. ;; Back-end name (for keywords, like #+LATEX:)
  7866. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  7867. (dolist (option-entry (org-export-backend-options backend))
  7868. ;; Back-end options.
  7869. (push (nth 1 option-entry) keywords)))))
  7870. (defconst org-options-keywords
  7871. '("ARCHIVE:" "AUTHOR:" "BIBLIOGRAPHY:" "BIND:" "CATEGORY:" "CITE_EXPORT:"
  7872. "COLUMNS:" "CREATOR:" "DATE:" "DESCRIPTION:" "DRAWERS:" "EMAIL:"
  7873. "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:" "INDEX:" "KEYWORDS:" "LANGUAGE:"
  7874. "MACRO:" "OPTIONS:" "PROPERTY:" "PRINT_BIBLIOGRAPHY" "PRIORITIES:"
  7875. "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:" "TITLE:" "TODO:"
  7876. "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  7877. (defcustom org-structure-template-alist
  7878. '(("a" . "export ascii")
  7879. ("c" . "center")
  7880. ("C" . "comment")
  7881. ("e" . "example")
  7882. ("E" . "export")
  7883. ("h" . "export html")
  7884. ("l" . "export latex")
  7885. ("q" . "quote")
  7886. ("s" . "src")
  7887. ("v" . "verse"))
  7888. "An alist of keys and block types.
  7889. `org-insert-structure-template' will display a menu with this list of
  7890. templates to choose from. The block type is inserted, with
  7891. \"#+begin_\" and \"#+end_\" added automatically. If the block type
  7892. consists of just uppercase letters, \"#+BEGIN_\" and \"#+END_\" are
  7893. added instead.
  7894. The menu keys are defined by the car of each entry in this alist.
  7895. If two entries have the keys \"a\" and \"aa\" respectively, the
  7896. former will be inserted by typing \"a TAB/RET/SPC\" and the
  7897. latter will be inserted by typing \"aa\". If an entry with the
  7898. key \"aab\" is later added, it can be inserted by typing \"ab\".
  7899. If loaded, Org Tempo also uses `org-structure-template-alist'. A
  7900. block can be inserted by pressing TAB after the string \"<KEY\"."
  7901. :group 'org-edit-structure
  7902. :type '(repeat
  7903. (cons (string :tag "Key")
  7904. (string :tag "Template")))
  7905. :package-version '(Org . "9.2"))
  7906. (defun org--check-org-structure-template-alist (&optional checklist)
  7907. "Check whether `org-structure-template-alist' is set up correctly.
  7908. In particular, check if the Org 9.2 format is used as opposed to
  7909. previous format."
  7910. (let ((elm (cl-remove-if-not (lambda (x) (listp (cdr x)))
  7911. (or (symbol-value checklist)
  7912. org-structure-template-alist))))
  7913. (when elm
  7914. (org-display-warning
  7915. (format "
  7916. Please update the entries of `%s'.
  7917. In Org 9.2 the format was changed from something like
  7918. (\"s\" \"#+BEGIN_SRC ?\\n#+END_SRC\")
  7919. to something like
  7920. (\"s\" . \"src\")
  7921. Please refer to the documentation of `org-structure-template-alist'.
  7922. The following entries must be updated:
  7923. %s"
  7924. (or checklist 'org-structure-template-alist)
  7925. (pp-to-string elm))))))
  7926. (defun org--insert-structure-template-mks ()
  7927. "Present `org-structure-template-alist' with `org-mks'.
  7928. Menus are added if keys require more than one keystroke. Tabs
  7929. are added to single key entries when more than one stroke is
  7930. needed. Keys longer than two characters are reduced to two
  7931. characters."
  7932. (org--check-org-structure-template-alist)
  7933. (let* (case-fold-search
  7934. (templates (append org-structure-template-alist
  7935. '(("\t" . "Press TAB, RET or SPC to write block name"))))
  7936. (keys (mapcar #'car templates))
  7937. (start-letters
  7938. (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
  7939. ;; Sort each element of `org-structure-template-alist' into
  7940. ;; sublists according to the first letter.
  7941. (superlist
  7942. (mapcar (lambda (letter)
  7943. (list letter
  7944. (cl-remove-if-not
  7945. (apply-partially #'string-match-p (concat "^" letter))
  7946. templates :key #'car)))
  7947. start-letters)))
  7948. (org-mks
  7949. (apply #'append
  7950. ;; Make an `org-mks' table. If only one element is
  7951. ;; present in a sublist, make it part of the top-menu,
  7952. ;; otherwise make a submenu according to the starting
  7953. ;; letter and populate it.
  7954. (mapcar (lambda (sublist)
  7955. (if (eq 1 (length (cadr sublist)))
  7956. (mapcar (lambda (elm)
  7957. (list (substring (car elm) 0 1)
  7958. (cdr elm) ""))
  7959. (cadr sublist))
  7960. ;; Create submenu.
  7961. (let* ((topkey (car sublist))
  7962. (elms (cadr sublist))
  7963. (keys (mapcar #'car elms))
  7964. (long (> (length elms) 3)))
  7965. (append
  7966. (list
  7967. ;; Make a description of the submenu.
  7968. (list topkey
  7969. (concat
  7970. (mapconcat #'cdr
  7971. (cl-subseq elms 0 (if long 3 (length elms)))
  7972. ", ")
  7973. (when long ", ..."))))
  7974. ;; List of entries in submenu.
  7975. (cl-mapcar #'list
  7976. (org--insert-structure-template-unique-keys keys)
  7977. (mapcar #'cdr elms)
  7978. (make-list (length elms) ""))))))
  7979. superlist))
  7980. "Select a key\n============"
  7981. "Key: ")))
  7982. (defun org--insert-structure-template-unique-keys (keys)
  7983. "Make a list of unique, two characters long elements from KEYS.
  7984. Elements of length one have a tab appended. Elements of length
  7985. two are kept as is. Longer elements are truncated to length two.
  7986. If an element cannot be made unique, an error is raised."
  7987. (let ((ordered-keys (cl-sort (copy-sequence keys) #'< :key #'length))
  7988. menu-keys)
  7989. (dolist (key ordered-keys)
  7990. (let ((potential-key
  7991. (cl-case (length key)
  7992. (1 (concat key "\t"))
  7993. (2 key)
  7994. (otherwise
  7995. (cl-find-if-not (lambda (k) (assoc k menu-keys))
  7996. (mapcar (apply-partially #'concat (substring key 0 1))
  7997. (split-string (substring key 1) "" t)))))))
  7998. (if (or (not potential-key) (assoc potential-key menu-keys))
  7999. (user-error "Could not make unique key for `%s'" key)
  8000. (push (cons potential-key key) menu-keys))))
  8001. (mapcar #'car
  8002. (cl-sort menu-keys #'<
  8003. :key (lambda (elm) (cl-position (cdr elm) keys))))))
  8004. (defun org-insert-structure-template (type)
  8005. "Insert a block structure of the type #+begin_foo/#+end_foo.
  8006. Select a block from `org-structure-template-alist' then type
  8007. either RET, TAB or SPC to write the block type. With an active
  8008. region, wrap the region in the block. Otherwise, insert an empty
  8009. block.
  8010. When foo is written as FOO, upcase the #+BEGIN/END as well."
  8011. (interactive
  8012. (list (pcase (org--insert-structure-template-mks)
  8013. (`("\t" . ,_) (read-string "Structure type: "))
  8014. (`(,_ ,choice . ,_) choice))))
  8015. (let* ((case-fold-search t) ; Make sure that matches are case-insensitive.
  8016. (region? (use-region-p))
  8017. (region-start (and region? (region-beginning)))
  8018. (region-end (and region? (copy-marker (region-end))))
  8019. (extended? (string-match-p "\\`\\(src\\|export\\)\\'" type))
  8020. (verbatim? (string-match-p
  8021. (concat "\\`" (regexp-opt '("example" "export"
  8022. "src" "comment")))
  8023. type))
  8024. (upcase? (string= (car (split-string type))
  8025. (upcase (car (split-string type))))))
  8026. (when region? (goto-char region-start))
  8027. (let ((column (current-indentation)))
  8028. (if (save-excursion (skip-chars-backward " \t") (bolp))
  8029. (beginning-of-line)
  8030. (insert "\n"))
  8031. (save-excursion
  8032. (indent-to column)
  8033. (insert (format "#+%s_%s%s\n" (if upcase? "BEGIN" "begin") type (if extended? " " "")))
  8034. (when region?
  8035. (when verbatim? (org-escape-code-in-region (point) region-end))
  8036. (goto-char region-end)
  8037. ;; Ignore empty lines at the end of the region.
  8038. (skip-chars-backward " \r\t\n")
  8039. (end-of-line))
  8040. (unless (bolp) (insert "\n"))
  8041. (indent-to column)
  8042. (insert (format "#+%s_%s" (if upcase? "END" "end") (car (split-string type))))
  8043. (if (looking-at "[ \t]*$") (replace-match "")
  8044. (insert "\n"))
  8045. (when (and (eobp) (not (bolp))) (insert "\n")))
  8046. (if extended? (end-of-line)
  8047. (forward-line)
  8048. (skip-chars-forward " \t")))))
  8049. ;;;; TODO, DEADLINE, Comments
  8050. (defun org-toggle-comment ()
  8051. "Change the COMMENT state of an entry."
  8052. (interactive)
  8053. (save-excursion
  8054. (org-back-to-heading)
  8055. (let ((case-fold-search nil))
  8056. (looking-at org-complex-heading-regexp))
  8057. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  8058. (skip-chars-forward " \t")
  8059. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  8060. (if (org-in-commented-heading-p t)
  8061. (delete-region (point)
  8062. (progn (search-forward " " (line-end-position) 'move)
  8063. (skip-chars-forward " \t")
  8064. (point)))
  8065. (insert org-comment-string)
  8066. (unless (eolp) (insert " ")))))
  8067. (defvar org-last-todo-state-is-todo nil
  8068. "This is non-nil when the last TODO state change led to a TODO state.
  8069. If the last change removed the TODO tag or switched to DONE, then
  8070. this is nil.")
  8071. (defvar org-todo-setup-filter-hook nil
  8072. "Hook for functions that pre-filter todo specs.
  8073. Each function takes a todo spec and returns either nil or the spec
  8074. transformed into canonical form." )
  8075. (defvar org-todo-get-default-hook nil
  8076. "Hook for functions that get a default item for todo.
  8077. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  8078. nil or a string to be used for the todo mark." )
  8079. (defvar org-agenda-headline-snapshot-before-repeat)
  8080. (defun org-current-effective-time ()
  8081. "Return current time adjusted for `org-extend-today-until' variable."
  8082. (let* ((ct (org-current-time))
  8083. (dct (decode-time ct))
  8084. (ct1
  8085. (cond
  8086. (org-use-last-clock-out-time-as-effective-time
  8087. (or (org-clock-get-last-clock-out-time) ct))
  8088. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  8089. (org-encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  8090. (t ct))))
  8091. ct1))
  8092. (defun org-todo-yesterday (&optional arg)
  8093. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  8094. (interactive "P")
  8095. (if (eq major-mode 'org-agenda-mode)
  8096. (org-agenda-todo-yesterday arg)
  8097. (let* ((org-use-effective-time t)
  8098. (hour (nth 2 (decode-time (org-current-time))))
  8099. (org-extend-today-until (1+ hour)))
  8100. (org-todo arg))))
  8101. (defvar org-block-entry-blocking ""
  8102. "First entry preventing the TODO state change.")
  8103. (defun org-cancel-repeater ()
  8104. "Cancel a repeater by setting its numeric value to zero."
  8105. (interactive)
  8106. (save-excursion
  8107. (org-back-to-heading t)
  8108. (let ((bound1 (point))
  8109. (bound0 (save-excursion (outline-next-heading) (point))))
  8110. (when (and (re-search-forward
  8111. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  8112. org-deadline-time-regexp "\\)\\|\\("
  8113. org-ts-regexp "\\)")
  8114. bound0 t)
  8115. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  8116. bound1 t))
  8117. (replace-match "0" t nil nil 1)))))
  8118. (defvar org-state)
  8119. (defvar org-blocked-by-checkboxes)
  8120. (defun org-todo (&optional arg)
  8121. "Change the TODO state of an item.
  8122. The state of an item is given by a keyword at the start of the heading,
  8123. like
  8124. *** TODO Write paper
  8125. *** DONE Call mom
  8126. The different keywords are specified in the variable `org-todo-keywords'.
  8127. By default the available states are \"TODO\" and \"DONE\". So, for this
  8128. example: when the item starts with TODO, it is changed to DONE.
  8129. When it starts with DONE, the DONE is removed. And when neither TODO nor
  8130. DONE are present, add TODO at the beginning of the heading.
  8131. You can set up single-character keys to fast-select the new state. See the
  8132. `org-todo-keywords' and `org-use-fast-todo-selection' for details.
  8133. With `\\[universal-argument]' prefix ARG, force logging the state change \
  8134. and take a
  8135. logging note.
  8136. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  8137. next set of TODO \
  8138. keywords (nextset).
  8139. Another way to achieve this is `S-C-<right>'.
  8140. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8141. prefix, circumvent any state blocking.
  8142. With numeric prefix arg, switch to the Nth state.
  8143. With a numeric prefix arg of 0, inhibit note taking for the change.
  8144. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  8145. When called through ELisp, arg is also interpreted in the following way:
  8146. `none' -> empty state
  8147. \"\" -> switch to empty state
  8148. `done' -> switch to DONE
  8149. `nextset' -> switch to the next set of keywords
  8150. `previousset' -> switch to the previous set of keywords
  8151. \"WAITING\" -> switch to the specified keyword, but only if it
  8152. really is a member of `org-todo-keywords'."
  8153. (interactive "P")
  8154. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  8155. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  8156. 'region-start-level 'region))
  8157. org-loop-over-headlines-in-active-region)
  8158. (org-map-entries
  8159. (lambda () (org-todo arg))
  8160. nil cl
  8161. (when (org-invisible-p) (org-end-of-subtree nil t))))
  8162. (when (equal arg '(16)) (setq arg 'nextset))
  8163. (when (equal (prefix-numeric-value arg) -1) (org-cancel-repeater) (setq arg nil))
  8164. (when (< (prefix-numeric-value arg) -1) (user-error "Prefix argument %d not supported" arg))
  8165. (let ((org-blocker-hook org-blocker-hook)
  8166. commentp
  8167. case-fold-search)
  8168. (when (equal arg '(64))
  8169. (setq arg nil org-blocker-hook nil))
  8170. (when (and org-blocker-hook
  8171. (or org-inhibit-blocking
  8172. (org-entry-get nil "NOBLOCKING")))
  8173. (setq org-blocker-hook nil))
  8174. (save-excursion
  8175. (catch 'exit
  8176. (org-back-to-heading t)
  8177. (when (org-in-commented-heading-p t)
  8178. (org-toggle-comment)
  8179. (setq commentp t))
  8180. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  8181. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  8182. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  8183. (let* ((match-data (match-data))
  8184. (startpos (copy-marker (line-beginning-position)))
  8185. (force-log (and (equal arg '(4)) (prog1 t (setq arg nil))))
  8186. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  8187. (org-log-done org-log-done)
  8188. (org-log-repeat org-log-repeat)
  8189. (org-todo-log-states org-todo-log-states)
  8190. (org-inhibit-logging
  8191. (if (equal arg 0)
  8192. (progn (setq arg nil) 'note) org-inhibit-logging))
  8193. (this (match-string 1))
  8194. (hl-pos (match-beginning 0))
  8195. (head (org-get-todo-sequence-head this))
  8196. (ass (assoc head org-todo-kwd-alist))
  8197. (interpret (nth 1 ass))
  8198. (done-word (nth 3 ass))
  8199. (final-done-word (nth 4 ass))
  8200. (org-last-state (or this ""))
  8201. (completion-ignore-case t)
  8202. (member (member this org-todo-keywords-1))
  8203. (tail (cdr member))
  8204. (org-state (cond
  8205. ((eq arg 'right)
  8206. ;; Next state
  8207. (if this
  8208. (if tail (car tail) nil)
  8209. (car org-todo-keywords-1)))
  8210. ((eq arg 'left)
  8211. ;; Previous state
  8212. (unless (equal member org-todo-keywords-1)
  8213. (if this
  8214. (nth (- (length org-todo-keywords-1)
  8215. (length tail) 2)
  8216. org-todo-keywords-1)
  8217. (org-last org-todo-keywords-1))))
  8218. (arg
  8219. ;; User or caller requests a specific state.
  8220. (cond
  8221. ((equal arg "") nil)
  8222. ((eq arg 'none) nil)
  8223. ((eq arg 'done) (or done-word (car org-done-keywords)))
  8224. ((eq arg 'nextset)
  8225. (or (car (cdr (member head org-todo-heads)))
  8226. (car org-todo-heads)))
  8227. ((eq arg 'previousset)
  8228. (let ((org-todo-heads (reverse org-todo-heads)))
  8229. (or (car (cdr (member head org-todo-heads)))
  8230. (car org-todo-heads))))
  8231. ((car (member arg org-todo-keywords-1)))
  8232. ((stringp arg)
  8233. (user-error "State `%s' not valid in this file" arg))
  8234. ((nth (1- (prefix-numeric-value arg))
  8235. org-todo-keywords-1))))
  8236. ((and org-todo-key-trigger org-use-fast-todo-selection)
  8237. ;; Use fast selection.
  8238. (org-fast-todo-selection this))
  8239. ((null member) (or head (car org-todo-keywords-1)))
  8240. ((equal this final-done-word) nil) ;-> make empty
  8241. ((null tail) nil) ;-> first entry
  8242. ((memq interpret '(type priority))
  8243. (if (eq this-command last-command)
  8244. (car tail)
  8245. (if (> (length tail) 0)
  8246. (or done-word (car org-done-keywords))
  8247. nil)))
  8248. (t
  8249. (car tail))))
  8250. (org-state (or
  8251. (run-hook-with-args-until-success
  8252. 'org-todo-get-default-hook org-state org-last-state)
  8253. org-state))
  8254. (next (if (org-string-nw-p org-state) (concat " " org-state " ") " "))
  8255. (change-plist (list :type 'todo-state-change :from this :to org-state
  8256. :position startpos))
  8257. dolog now-done-p)
  8258. (when org-blocker-hook
  8259. (let (org-blocked-by-checkboxes block-reason)
  8260. (setq org-last-todo-state-is-todo
  8261. (not (member this org-done-keywords)))
  8262. (unless (save-excursion
  8263. (save-match-data
  8264. (org-with-wide-buffer
  8265. (run-hook-with-args-until-failure
  8266. 'org-blocker-hook change-plist))))
  8267. (setq block-reason (if org-blocked-by-checkboxes
  8268. "contained checkboxes"
  8269. (format "\"%s\"" org-block-entry-blocking)))
  8270. (if (called-interactively-p 'interactive)
  8271. (user-error "TODO state change from %s to %s blocked (by %s)"
  8272. this org-state block-reason)
  8273. ;; Fail silently.
  8274. (message "TODO state change from %s to %s blocked (by %s)"
  8275. this org-state block-reason)
  8276. (throw 'exit nil)))))
  8277. (store-match-data match-data)
  8278. (org-fold-core-ignore-modifications
  8279. (goto-char (match-beginning 0))
  8280. (replace-match "")
  8281. ;; We need to use `insert-before-markers-and-inherit'
  8282. ;; because: (1) We want to preserve the folding state
  8283. ;; text properties; (2) We do not want to make point
  8284. ;; move before new todo state when inserting a new todo
  8285. ;; into an empty heading. In (2), the above
  8286. ;; `save-excursion' is relying on markers saved before.
  8287. (insert-before-markers-and-inherit next)
  8288. (unless (org-invisible-p (line-beginning-position))
  8289. (org-fold-region (line-beginning-position)
  8290. (line-end-position)
  8291. nil)))
  8292. (cond ((and org-state (equal this org-state))
  8293. (message "TODO state was already %s" (org-trim next)))
  8294. ((not (pos-visible-in-window-p hl-pos))
  8295. (message "TODO state changed to %s" (org-trim next))))
  8296. (unless head
  8297. (setq head (org-get-todo-sequence-head org-state)
  8298. ass (assoc head org-todo-kwd-alist)
  8299. interpret (nth 1 ass)
  8300. done-word (nth 3 ass)
  8301. final-done-word (nth 4 ass)))
  8302. (when (memq arg '(nextset previousset))
  8303. (message "Keyword-Set %d/%d: %s"
  8304. (- (length org-todo-sets) -1
  8305. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  8306. (length org-todo-sets)
  8307. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  8308. (setq org-last-todo-state-is-todo
  8309. (not (member org-state org-done-keywords)))
  8310. (setq now-done-p (and (member org-state org-done-keywords)
  8311. (not (member this org-done-keywords))))
  8312. (and logging (org-local-logging logging))
  8313. (when (or (and (or org-todo-log-states org-log-done)
  8314. (not (eq org-inhibit-logging t))
  8315. (not (memq arg '(nextset previousset))))
  8316. force-log)
  8317. ;; We need to look at recording a time and note.
  8318. (setq dolog (or (if force-log 'note)
  8319. (nth 1 (assoc org-state org-todo-log-states))
  8320. (nth 2 (assoc this org-todo-log-states))))
  8321. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  8322. (setq dolog 'time))
  8323. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  8324. (and org-state
  8325. (member org-state org-not-done-keywords)
  8326. (not (member this org-not-done-keywords))))
  8327. ;; This is now a todo state and was not one before
  8328. ;; If there was a CLOSED time stamp, get rid of it.
  8329. (org-add-planning-info nil nil 'closed))
  8330. (when (and now-done-p org-log-done)
  8331. ;; It is now done, and it was not done before.
  8332. (org-add-planning-info 'closed (org-current-effective-time))
  8333. (when (and (not dolog) (eq 'note org-log-done))
  8334. (org-add-log-setup 'done org-state this 'note)))
  8335. (when (and org-state dolog)
  8336. ;; This is a non-nil state, and we need to log it.
  8337. (org-add-log-setup 'state org-state this dolog)))
  8338. ;; Fixup tag positioning.
  8339. (org-todo-trigger-tag-changes org-state)
  8340. (when org-auto-align-tags (org-align-tags))
  8341. (when org-provide-todo-statistics
  8342. (org-update-parent-todo-statistics))
  8343. (when (bound-and-true-p org-clock-out-when-done)
  8344. (org-clock-out-if-current))
  8345. (run-hooks 'org-after-todo-state-change-hook)
  8346. (when (and arg (not (member org-state org-done-keywords)))
  8347. (setq head (org-get-todo-sequence-head org-state)))
  8348. (put-text-property (line-beginning-position)
  8349. (line-end-position) 'org-todo-head head)
  8350. ;; Do we need to trigger a repeat?
  8351. (when now-done-p
  8352. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  8353. ;; This is for the agenda, take a snapshot of the headline.
  8354. (save-match-data
  8355. (setq org-agenda-headline-snapshot-before-repeat
  8356. (org-get-heading))))
  8357. (org-auto-repeat-maybe org-state))
  8358. ;; Fixup cursor location if close to the keyword.
  8359. (when (and (outline-on-heading-p)
  8360. (not (bolp))
  8361. (save-excursion (beginning-of-line 1)
  8362. (looking-at org-todo-line-regexp))
  8363. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  8364. (goto-char (or (match-end 2) (match-end 1)))
  8365. (and (looking-at " ")
  8366. (not (looking-at " *:"))
  8367. (just-one-space)))
  8368. (when org-trigger-hook
  8369. (save-excursion
  8370. (run-hook-with-args 'org-trigger-hook change-plist)))
  8371. (when commentp (org-toggle-comment))))))))
  8372. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  8373. "Block turning an entry into a TODO, using the hierarchy.
  8374. This checks whether the current task should be blocked from state
  8375. changes. Such blocking occurs when:
  8376. 1. The task has children which are not all in a completed state.
  8377. 2. A task has a parent with the property :ORDERED:, and there
  8378. are siblings prior to the current task with incomplete
  8379. status.
  8380. 3. The parent of the task is blocked because it has siblings that should
  8381. be done first, or is child of a block grandparent TODO entry."
  8382. (if (not org-enforce-todo-dependencies)
  8383. t ; if locally turned off don't block
  8384. (catch 'dont-block
  8385. ;; If this is not a todo state change, or if this entry is already DONE,
  8386. ;; do not block
  8387. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  8388. (member (plist-get change-plist :from)
  8389. (cons 'done org-done-keywords))
  8390. (member (plist-get change-plist :to)
  8391. (cons 'todo org-not-done-keywords))
  8392. (not (plist-get change-plist :to)))
  8393. (throw 'dont-block t))
  8394. ;; If this task has children, and any are undone, it's blocked
  8395. (save-excursion
  8396. (org-back-to-heading t)
  8397. (let ((this-level (funcall outline-level)))
  8398. (outline-next-heading)
  8399. (let ((child-level (funcall outline-level)))
  8400. (while (and (not (eobp))
  8401. (> child-level this-level))
  8402. ;; this todo has children, check whether they are all
  8403. ;; completed
  8404. (when (and (not (org-entry-is-done-p))
  8405. (org-entry-is-todo-p))
  8406. (setq org-block-entry-blocking (org-get-heading))
  8407. (throw 'dont-block nil))
  8408. (outline-next-heading)
  8409. (setq child-level (funcall outline-level))))))
  8410. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  8411. ;; any previous siblings are undone, it's blocked
  8412. (save-excursion
  8413. (org-back-to-heading t)
  8414. (let* ((pos (point))
  8415. (parent-pos (and (org-up-heading-safe) (point)))
  8416. (case-fold-search nil))
  8417. (unless parent-pos (throw 'dont-block t)) ; no parent
  8418. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  8419. (forward-line 1)
  8420. (re-search-forward org-not-done-heading-regexp pos t))
  8421. (setq org-block-entry-blocking (match-string 0))
  8422. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  8423. ;; Search further up the hierarchy, to see if an ancestor is blocked
  8424. (while t
  8425. (goto-char parent-pos)
  8426. (unless (looking-at org-not-done-heading-regexp)
  8427. (throw 'dont-block t)) ; do not block, parent is not a TODO
  8428. (setq pos (point))
  8429. (setq parent-pos (and (org-up-heading-safe) (point)))
  8430. (unless parent-pos (throw 'dont-block t)) ; no parent
  8431. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  8432. (forward-line 1)
  8433. (re-search-forward org-not-done-heading-regexp pos t)
  8434. (setq org-block-entry-blocking (org-get-heading)))
  8435. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  8436. (defcustom org-track-ordered-property-with-tag nil
  8437. "Should the ORDERED property also be shown as a tag?
  8438. The ORDERED property decides if an entry should require subtasks to be
  8439. completed in sequence. Since a property is not very visible, setting
  8440. this option means that toggling the ORDERED property with the command
  8441. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  8442. not relevant for the behavior, but it makes things more visible.
  8443. Note that toggling the tag with tags commands will not change the property
  8444. and therefore not influence behavior!
  8445. This can be t, meaning the tag ORDERED should be used. It can also be a
  8446. string to select a different tag for this task."
  8447. :group 'org-todo
  8448. :type '(choice
  8449. (const :tag "No tracking" nil)
  8450. (const :tag "Track with ORDERED tag" t)
  8451. (string :tag "Use other tag")))
  8452. (defun org-toggle-ordered-property ()
  8453. "Toggle the ORDERED property of the current entry.
  8454. For better visibility, you can track the value of this property with a tag.
  8455. See variable `org-track-ordered-property-with-tag'."
  8456. (interactive)
  8457. (let* ((t1 org-track-ordered-property-with-tag)
  8458. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  8459. (save-excursion
  8460. (org-back-to-heading)
  8461. (if (org-entry-get nil "ORDERED")
  8462. (progn
  8463. (org-delete-property "ORDERED")
  8464. (and tag (org-toggle-tag tag 'off))
  8465. (message "Subtasks can be completed in arbitrary order"))
  8466. (org-entry-put nil "ORDERED" "t")
  8467. (and tag (org-toggle-tag tag 'on))
  8468. (message "Subtasks must be completed in sequence")))))
  8469. (defun org-block-todo-from-checkboxes (change-plist)
  8470. "Block turning an entry into a TODO, using checkboxes.
  8471. This checks whether the current task should be blocked from state
  8472. changes because there are unchecked boxes in this entry."
  8473. (if (not org-enforce-todo-checkbox-dependencies)
  8474. t ; if locally turned off don't block
  8475. (catch 'dont-block
  8476. ;; If this is not a todo state change, or if this entry is already DONE,
  8477. ;; do not block
  8478. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  8479. (member (plist-get change-plist :from)
  8480. (cons 'done org-done-keywords))
  8481. (member (plist-get change-plist :to)
  8482. (cons 'todo org-not-done-keywords))
  8483. (not (plist-get change-plist :to)))
  8484. (throw 'dont-block t))
  8485. ;; If this task has checkboxes that are not checked, it's blocked
  8486. (save-excursion
  8487. (org-back-to-heading t)
  8488. (let ((beg (point)) end)
  8489. (outline-next-heading)
  8490. (setq end (point))
  8491. (goto-char beg)
  8492. (when (org-list-search-forward
  8493. (concat (org-item-beginning-re)
  8494. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  8495. "\\[[- ]\\]")
  8496. end t)
  8497. (when (boundp 'org-blocked-by-checkboxes)
  8498. (setq org-blocked-by-checkboxes t))
  8499. (throw 'dont-block nil))))
  8500. t))) ; do not block
  8501. (defun org-entry-blocked-p ()
  8502. "Non-nil if entry at point is blocked."
  8503. (and (not (org-entry-get nil "NOBLOCKING"))
  8504. (member (org-entry-get nil "TODO") org-not-done-keywords)
  8505. (not (run-hook-with-args-until-failure
  8506. 'org-blocker-hook
  8507. (list :type 'todo-state-change
  8508. :position (point)
  8509. :from 'todo
  8510. :to 'done)))))
  8511. (defun org-update-statistics-cookies (all)
  8512. "Update the statistics cookie, either from TODO or from checkboxes.
  8513. This should be called with the cursor in a line with a statistics
  8514. cookie. When called with a \\[universal-argument] prefix, update
  8515. all statistics cookies in the buffer."
  8516. (interactive "P")
  8517. (if all
  8518. (progn
  8519. (org-update-checkbox-count 'all)
  8520. (org-map-region 'org-update-parent-todo-statistics
  8521. (point-min) (point-max)))
  8522. (if (not (org-at-heading-p))
  8523. (org-update-checkbox-count)
  8524. (let ((pos (point-marker))
  8525. end l1 l2)
  8526. (ignore-errors (org-back-to-heading t))
  8527. (if (not (org-at-heading-p))
  8528. (org-update-checkbox-count)
  8529. (setq l1 (org-outline-level))
  8530. (setq end
  8531. (save-excursion
  8532. (outline-next-heading)
  8533. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  8534. (point)))
  8535. (if (and (save-excursion
  8536. (re-search-forward
  8537. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  8538. (not (save-excursion
  8539. (re-search-forward
  8540. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  8541. (org-update-checkbox-count)
  8542. (if (and l2 (> l2 l1))
  8543. (progn
  8544. (goto-char end)
  8545. (org-update-parent-todo-statistics))
  8546. (goto-char pos)
  8547. (beginning-of-line 1)
  8548. (while (re-search-forward
  8549. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  8550. (line-end-position) t)
  8551. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  8552. (goto-char pos)
  8553. (move-marker pos nil)))))
  8554. (defvar org-entry-property-inherited-from) ;; defined below
  8555. (defun org-update-parent-todo-statistics ()
  8556. "Update any statistics cookie in the parent of the current headline.
  8557. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  8558. the entire subtree and this will travel up the hierarchy and update
  8559. statistics everywhere."
  8560. (let* ((prop (save-excursion
  8561. (org-up-heading-safe)
  8562. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  8563. (recursive (or (not org-hierarchical-todo-statistics)
  8564. (and prop (string-match "\\<recursive\\>" prop))))
  8565. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  8566. 0))
  8567. (first t)
  8568. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  8569. level ltoggle l1 new ndel
  8570. (cnt-all 0) (cnt-done 0) is-percent kwd
  8571. checkbox-beg cookie-present)
  8572. (catch 'exit
  8573. (save-excursion
  8574. (beginning-of-line 1)
  8575. (setq ltoggle (funcall outline-level))
  8576. ;; Three situations are to consider:
  8577. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  8578. ;; to the top-level ancestor on the headline;
  8579. ;; 2. If parent has "recursive" property, repeat up to the
  8580. ;; headline setting that property, taking inheritance into
  8581. ;; account;
  8582. ;; 3. Else, move up to direct parent and proceed only once.
  8583. (while (and (setq level (org-up-heading-safe))
  8584. (or recursive first)
  8585. (>= (point) lim))
  8586. (setq first nil cookie-present nil)
  8587. (unless (and level
  8588. (not (string-match
  8589. "\\<checkbox\\>"
  8590. (downcase (or (org-entry-get nil "COOKIE_DATA")
  8591. "")))))
  8592. (throw 'exit nil))
  8593. (while (re-search-forward box-re (line-end-position) t)
  8594. (setq cnt-all 0 cnt-done 0 cookie-present t)
  8595. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  8596. (save-match-data
  8597. (unless (outline-next-heading) (throw 'exit nil))
  8598. (while (and (looking-at org-complex-heading-regexp)
  8599. (> (setq l1 (length (match-string 1))) level))
  8600. (setq kwd (and (or recursive (= l1 ltoggle))
  8601. (match-string 2)))
  8602. (if (or (eq org-provide-todo-statistics 'all-headlines)
  8603. (and (eq org-provide-todo-statistics t)
  8604. (or (member kwd org-done-keywords)))
  8605. (and (listp org-provide-todo-statistics)
  8606. (stringp (car org-provide-todo-statistics))
  8607. (or (member kwd org-provide-todo-statistics)
  8608. (member kwd org-done-keywords)))
  8609. (and (listp org-provide-todo-statistics)
  8610. (listp (car org-provide-todo-statistics))
  8611. (or (member kwd (car org-provide-todo-statistics))
  8612. (and (member kwd org-done-keywords)
  8613. (member kwd (cadr org-provide-todo-statistics))))))
  8614. (setq cnt-all (1+ cnt-all))
  8615. (and (eq org-provide-todo-statistics t)
  8616. kwd
  8617. (setq cnt-all (1+ cnt-all))))
  8618. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  8619. (member kwd org-done-keywords))
  8620. (and (listp org-provide-todo-statistics)
  8621. (listp (car org-provide-todo-statistics))
  8622. (member kwd org-done-keywords)
  8623. (member kwd (cadr org-provide-todo-statistics)))
  8624. (and (listp org-provide-todo-statistics)
  8625. (stringp (car org-provide-todo-statistics))
  8626. (member kwd org-done-keywords)))
  8627. (setq cnt-done (1+ cnt-done)))
  8628. (outline-next-heading)))
  8629. (setq new
  8630. (if is-percent
  8631. (format "[%d%%]" (floor (* 100.0 cnt-done)
  8632. (max 1 cnt-all)))
  8633. (format "[%d/%d]" cnt-done cnt-all))
  8634. ndel (- (match-end 0) checkbox-beg))
  8635. (goto-char checkbox-beg)
  8636. (insert new)
  8637. (delete-region (point) (+ (point) ndel))
  8638. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  8639. (when cookie-present
  8640. (run-hook-with-args 'org-after-todo-statistics-hook
  8641. cnt-done (- cnt-all cnt-done))))))
  8642. (run-hooks 'org-todo-statistics-hook)))
  8643. (defvar org-after-todo-statistics-hook nil
  8644. "Hook that is called after a TODO statistics cookie has been updated.
  8645. Each function is called with two arguments: the number of not-done entries
  8646. and the number of done entries.
  8647. For example, the following function, when added to this hook, will switch
  8648. an entry to DONE when all children are done, and back to TODO when new
  8649. entries are set to a TODO status. Note that this hook is only called
  8650. when there is a statistics cookie in the headline!
  8651. (defun org-summary-todo (n-done n-not-done)
  8652. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  8653. (let (org-log-done org-log-states) ; turn off logging
  8654. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))")
  8655. (defvar org-todo-statistics-hook nil
  8656. "Hook that is run whenever Org thinks TODO statistics should be updated.
  8657. This hook runs even if there is no statistics cookie present, in which case
  8658. `org-after-todo-statistics-hook' would not run.")
  8659. (defun org-todo-trigger-tag-changes (state)
  8660. "Apply the changes defined in `org-todo-state-tags-triggers'."
  8661. (let ((l org-todo-state-tags-triggers)
  8662. changes)
  8663. (when (or (not state) (equal state ""))
  8664. (setq changes (append changes (cdr (assoc "" l)))))
  8665. (when (and (stringp state) (> (length state) 0))
  8666. (setq changes (append changes (cdr (assoc state l)))))
  8667. (when (member state org-not-done-keywords)
  8668. (setq changes (append changes (cdr (assq 'todo l)))))
  8669. (when (member state org-done-keywords)
  8670. (setq changes (append changes (cdr (assq 'done l)))))
  8671. (dolist (c changes)
  8672. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  8673. (defun org-local-logging (value)
  8674. "Get logging settings from a property VALUE."
  8675. ;; Directly set the variables, they are already local.
  8676. (setq org-log-done nil
  8677. org-log-repeat nil
  8678. org-todo-log-states nil)
  8679. (dolist (w (split-string value))
  8680. (let (a)
  8681. (cond
  8682. ((setq a (assoc w org-startup-options))
  8683. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  8684. (set (nth 1 a) (nth 2 a))))
  8685. ((setq a (org-extract-log-state-settings w))
  8686. (and (member (car a) org-todo-keywords-1)
  8687. (push a org-todo-log-states)))))))
  8688. (defun org-get-todo-sequence-head (kwd)
  8689. "Return the head of the TODO sequence to which KWD belongs.
  8690. If KWD is not set, check if there is a text property remembering the
  8691. right sequence."
  8692. (let (p)
  8693. (cond
  8694. ((not kwd)
  8695. (or (get-text-property (line-beginning-position) 'org-todo-head)
  8696. (progn
  8697. (setq p (next-single-property-change (line-beginning-position)
  8698. 'org-todo-head
  8699. nil (line-end-position)))
  8700. (get-text-property p 'org-todo-head))))
  8701. ((not (member kwd org-todo-keywords-1))
  8702. (car org-todo-keywords-1))
  8703. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  8704. (defun org-fast-todo-selection (&optional current-state)
  8705. "Fast TODO keyword selection with single keys.
  8706. Returns the new TODO keyword, or nil if no state change should occur.
  8707. When CURRENT-STATE is given and selection letters are not unique globally,
  8708. prefer a state in the current sequence over on in another sequence."
  8709. (let* ((fulltable org-todo-key-alist)
  8710. (head (org-get-todo-sequence-head current-state))
  8711. (done-keywords org-done-keywords) ;; needed for the faces.
  8712. (maxlen (apply 'max (mapcar
  8713. (lambda (x)
  8714. (if (stringp (car x)) (string-width (car x)) 0))
  8715. fulltable)))
  8716. (expert (equal org-use-fast-todo-selection 'expert))
  8717. (prompt "")
  8718. (fwidth (+ maxlen 3 1 3))
  8719. (ncol (/ (- (window-width) 4) fwidth))
  8720. tg cnt e c tbl subtable
  8721. groups ingroup in-current-sequence)
  8722. (save-excursion
  8723. (save-window-excursion
  8724. (if expert
  8725. (set-buffer (get-buffer-create " *Org todo*"))
  8726. (delete-other-windows)
  8727. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org todo*"))
  8728. (org-switch-to-buffer-other-window " *Org todo*"))
  8729. (erase-buffer)
  8730. (setq-local org-done-keywords done-keywords)
  8731. (setq tbl fulltable cnt 0)
  8732. (while (setq e (pop tbl))
  8733. (cond
  8734. ((equal e '(:startgroup))
  8735. (push '() groups) (setq ingroup t)
  8736. (unless (= cnt 0)
  8737. (setq cnt 0)
  8738. (insert "\n"))
  8739. (setq prompt (concat prompt "{"))
  8740. (insert "{ "))
  8741. ((equal e '(:endgroup))
  8742. (setq ingroup nil cnt 0 in-current-sequence nil)
  8743. (setq prompt (concat prompt "}"))
  8744. (insert "}\n"))
  8745. ((equal e '(:newline))
  8746. (unless (= cnt 0)
  8747. (setq cnt 0)
  8748. (insert "\n")
  8749. (setq e (car tbl))
  8750. (while (equal (car tbl) '(:newline))
  8751. (insert "\n")
  8752. (setq tbl (cdr tbl)))))
  8753. (t
  8754. (setq tg (car e) c (cdr e))
  8755. (if (equal tg head) (setq in-current-sequence t))
  8756. (when ingroup (push tg (car groups)))
  8757. (when in-current-sequence (push e subtable))
  8758. (setq tg (org-add-props tg nil 'face
  8759. (org-get-todo-face tg)))
  8760. (when (and (= cnt 0) (not ingroup)) (insert " "))
  8761. (setq prompt (concat prompt "[" (char-to-string c) "] " tg " "))
  8762. (insert "[" c "] " tg (make-string
  8763. (- fwidth 4 (length tg)) ?\ ))
  8764. (when (and (= (setq cnt (1+ cnt)) ncol)
  8765. ;; Avoid lines with just a closing delimiter.
  8766. (not (equal (car tbl) '(:endgroup))))
  8767. (insert "\n")
  8768. (when ingroup (insert " "))
  8769. (setq cnt 0)))))
  8770. (insert "\n")
  8771. (goto-char (point-min))
  8772. (unless expert (org-fit-window-to-buffer))
  8773. (message (concat "[a-z..]:Set [SPC]:clear"
  8774. (if expert (concat "\n" prompt) "")))
  8775. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  8776. (setq subtable (nreverse subtable))
  8777. (cond
  8778. ((or (= c ?\C-g)
  8779. (and (= c ?q) (not (rassoc c fulltable))))
  8780. (setq quit-flag t))
  8781. ((= c ?\ ) nil)
  8782. ((setq e (or (rassoc c subtable) (rassoc c fulltable))
  8783. tg (car e))
  8784. tg)
  8785. (t (setq quit-flag t)))))))
  8786. (defun org-entry-is-todo-p ()
  8787. (member (org-get-todo-state) org-not-done-keywords))
  8788. (defun org-entry-is-done-p ()
  8789. (member (org-get-todo-state) org-done-keywords))
  8790. (defun org-get-todo-state ()
  8791. "Return the TODO keyword of the current subtree."
  8792. (save-excursion
  8793. (org-back-to-heading t)
  8794. (and (let ((case-fold-search nil))
  8795. (looking-at org-todo-line-regexp))
  8796. (match-end 2)
  8797. (match-string 2))))
  8798. (defun org-at-date-range-p (&optional inactive-ok)
  8799. "Non-nil if point is inside a date range.
  8800. When optional argument INACTIVE-OK is non-nil, also consider
  8801. inactive time ranges.
  8802. When this function returns a non-nil value, match data is set
  8803. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  8804. on INACTIVE-OK."
  8805. (interactive)
  8806. (save-excursion
  8807. (catch 'exit
  8808. (let ((pos (point)))
  8809. (skip-chars-backward "^[<\r\n")
  8810. (skip-chars-backward "<[")
  8811. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  8812. (>= (match-end 0) pos)
  8813. (throw 'exit t))
  8814. (skip-chars-backward "^<[\r\n")
  8815. (skip-chars-backward "<[")
  8816. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  8817. (>= (match-end 0) pos)
  8818. (throw 'exit t)))
  8819. nil)))
  8820. (defun org-get-repeat (&optional timestamp)
  8821. "Check if there is a time-stamp with repeater in this entry.
  8822. Return the repeater, as a string, or nil. Also return nil when
  8823. this function is called before first heading.
  8824. When optional argument TIMESTAMP is a string, extract the
  8825. repeater from there instead."
  8826. (save-match-data
  8827. (cond
  8828. (timestamp
  8829. (and (string-match org-repeat-re timestamp)
  8830. (match-string-no-properties 1 timestamp)))
  8831. ((org-before-first-heading-p) nil)
  8832. (t
  8833. (save-excursion
  8834. (org-back-to-heading t)
  8835. (let ((end (org-entry-end-position)))
  8836. (catch :repeat
  8837. (while (re-search-forward org-repeat-re end t)
  8838. (when (save-match-data (org-at-timestamp-p 'agenda))
  8839. (throw :repeat (match-string-no-properties 1)))))))))))
  8840. (defvar org-last-changed-timestamp)
  8841. (defvar org-last-inserted-timestamp)
  8842. (defvar org-log-post-message)
  8843. (defvar org-log-note-purpose)
  8844. (defvar org-log-note-how nil)
  8845. (defvar org-log-note-extra)
  8846. (defvar org-log-setup nil)
  8847. (defun org-auto-repeat-maybe (done-word)
  8848. "Check if the current headline contains a repeated time-stamp.
  8849. If yes, set TODO state back to what it was and change the base date
  8850. of repeating deadline/scheduled time stamps to new date.
  8851. This function is run automatically after each state change to a DONE state."
  8852. (let* ((repeat (org-get-repeat))
  8853. (aa (assoc org-last-state org-todo-kwd-alist))
  8854. (interpret (nth 1 aa))
  8855. (head (nth 2 aa))
  8856. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  8857. (msg "Entry repeats: ")
  8858. (org-log-done nil)
  8859. (org-todo-log-states nil)
  8860. (end (copy-marker (org-entry-end-position))))
  8861. (when (and repeat (not (= 0 (string-to-number (substring repeat 1)))))
  8862. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  8863. (let ((to-state
  8864. (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  8865. (and (stringp org-todo-repeat-to-state)
  8866. org-todo-repeat-to-state)
  8867. (and org-todo-repeat-to-state org-last-state))))
  8868. (org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
  8869. to-state)
  8870. ((eq interpret 'type) org-last-state)
  8871. (head)
  8872. (t 'none))))
  8873. (org-back-to-heading t)
  8874. (org-add-planning-info nil nil 'closed)
  8875. ;; When `org-log-repeat' is non-nil or entry contains
  8876. ;; a clock, set LAST_REPEAT property.
  8877. (when (or org-log-repeat
  8878. (catch :clock
  8879. (save-excursion
  8880. (while (re-search-forward org-clock-line-re end t)
  8881. (when (org-at-clock-log-p) (throw :clock t))))))
  8882. (org-entry-put nil "LAST_REPEAT" (format-time-string
  8883. (org-time-stamp-format t t)
  8884. (org-current-effective-time))))
  8885. (when org-log-repeat
  8886. (if org-log-setup
  8887. ;; We are already setup for some record.
  8888. (when (eq org-log-repeat 'note)
  8889. ;; Make sure we take a note, not only a time stamp.
  8890. (setq org-log-note-how 'note))
  8891. ;; Set up for taking a record.
  8892. (org-add-log-setup 'state
  8893. (or done-word (car org-done-keywords))
  8894. org-last-state
  8895. org-log-repeat)))
  8896. ;; Time-stamps without a repeater are usually skipped. However,
  8897. ;; a SCHEDULED time-stamp without one is removed, as they are no
  8898. ;; longer relevant.
  8899. (save-excursion
  8900. (let ((scheduled (org-entry-get (point) "SCHEDULED")))
  8901. (when (and scheduled (not (string-match-p org-repeat-re scheduled)))
  8902. (org-remove-timestamp-with-keyword org-scheduled-string))))
  8903. ;; Update every time-stamp with a repeater in the entry.
  8904. (let ((planning-re (regexp-opt
  8905. (list org-scheduled-string org-deadline-string))))
  8906. (while (re-search-forward org-repeat-re end t)
  8907. (let* ((ts (match-string 0))
  8908. (type (if (not (org-at-planning-p)) "Plain:"
  8909. (save-excursion
  8910. (re-search-backward
  8911. planning-re (line-beginning-position) t)
  8912. (match-string 0)))))
  8913. (when (and (org-at-timestamp-p 'agenda)
  8914. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  8915. (let ((n (string-to-number (match-string 2 ts)))
  8916. (what (match-string 3 ts)))
  8917. (when (equal what "w") (setq n (* n 7) what "d"))
  8918. (when (and (equal what "h")
  8919. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  8920. ts)))
  8921. (user-error
  8922. "Cannot repeat in %d hour(s) because no hour has been set"
  8923. n))
  8924. ;; Preparation, see if we need to modify the start
  8925. ;; date for the change.
  8926. (when (match-end 1)
  8927. (let ((time (save-match-data (org-time-string-to-time ts)))
  8928. (repeater-type (match-string 1 ts)))
  8929. (cond
  8930. ((equal "." repeater-type)
  8931. ;; Shift starting date to today, or now if
  8932. ;; repeater is by hours.
  8933. (if (equal what "h")
  8934. (org-timestamp-change
  8935. (floor (- (org-time-stamp-to-now ts t)) 60) 'minute)
  8936. (org-timestamp-change
  8937. (- (org-today) (time-to-days time)) 'day)))
  8938. ((equal "+" repeater-type)
  8939. (let ((nshiftmax 10)
  8940. (nshift 0))
  8941. (while (or (= nshift 0)
  8942. (not (time-less-p nil time)))
  8943. (when (= nshiftmax (cl-incf nshift))
  8944. (or (y-or-n-p
  8945. (format "%d repeater intervals were not \
  8946. enough to shift date past today. Continue? "
  8947. nshift))
  8948. (user-error "Abort")))
  8949. (org-timestamp-change n (cdr (assoc what whata)))
  8950. (org-in-regexp org-ts-regexp3)
  8951. (setq ts (match-string 1))
  8952. (setq time
  8953. (save-match-data
  8954. (org-time-string-to-time ts)))))
  8955. (org-timestamp-change (- n) (cdr (assoc what whata)))
  8956. ;; Rematch, so that we have everything in place
  8957. ;; for the real shift.
  8958. (org-in-regexp org-ts-regexp3)
  8959. (setq ts (match-string 1))
  8960. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  8961. ts)))))
  8962. (save-excursion
  8963. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  8964. (setq msg
  8965. (concat msg type " " org-last-changed-timestamp " ")))))))
  8966. (run-hooks 'org-todo-repeat-hook)
  8967. (setq org-log-post-message msg)
  8968. (message msg))))
  8969. (defun org-show-todo-tree (arg)
  8970. "Make a compact tree which shows all headlines marked with TODO.
  8971. The tree will show the lines where the regexp matches, and all higher
  8972. headlines above the match.
  8973. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  8974. With a numeric prefix N, construct a sparse tree for the Nth element
  8975. of `org-todo-keywords-1'."
  8976. (interactive "P")
  8977. (let ((case-fold-search nil)
  8978. (kwd-re
  8979. (cond ((null arg) (concat org-not-done-regexp "\\s-"))
  8980. ((equal arg '(4))
  8981. (let ((kwd
  8982. (completing-read "Keyword (or KWD1|KWD2|...): "
  8983. (mapcar #'list org-todo-keywords-1))))
  8984. (concat "\\("
  8985. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  8986. "\\)\\>")))
  8987. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  8988. (regexp-quote (nth (1- (prefix-numeric-value arg))
  8989. org-todo-keywords-1)))
  8990. (t (user-error "Invalid prefix argument: %s" arg)))))
  8991. (message "%d TODO entries found"
  8992. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  8993. (defun org--deadline-or-schedule (arg type time)
  8994. "Insert DEADLINE or SCHEDULE information in current entry.
  8995. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  8996. `org-schedule' for information about ARG and TIME arguments."
  8997. (org-fold-core-ignore-modifications
  8998. (let* ((deadline? (eq type 'deadline))
  8999. (keyword (if deadline? org-deadline-string org-scheduled-string))
  9000. (log (if deadline? org-log-redeadline org-log-reschedule))
  9001. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  9002. (old-date-time (and old-date (org-time-string-to-time old-date)))
  9003. ;; Save repeater cookie from either TIME or current scheduled
  9004. ;; time stamp. We are going to insert it back at the end of
  9005. ;; the process.
  9006. (repeater (or (and (org-string-nw-p time)
  9007. ;; We use `org-ts-regexp-both' because we
  9008. ;; need to tell the difference between a
  9009. ;; real repeater and a time delta, e.g.
  9010. ;; "+2d".
  9011. (string-match-p org-ts-regexp-both time)
  9012. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  9013. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  9014. time)
  9015. (match-string 1 time))
  9016. (and (org-string-nw-p old-date)
  9017. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  9018. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  9019. old-date)
  9020. (match-string 1 old-date)))))
  9021. (pcase arg
  9022. (`(4)
  9023. (if (not old-date)
  9024. (message (if deadline? "Entry had no deadline to remove"
  9025. "Entry was not scheduled"))
  9026. (when (and old-date log)
  9027. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  9028. nil old-date log))
  9029. (org-remove-timestamp-with-keyword keyword)
  9030. (message (if deadline? "Entry no longer has a deadline."
  9031. "Entry is no longer scheduled."))))
  9032. (`(16)
  9033. (save-excursion
  9034. (org-back-to-heading t)
  9035. (let ((regexp (if deadline? org-deadline-time-regexp
  9036. org-scheduled-time-regexp)))
  9037. (if (not (re-search-forward regexp (line-end-position 2) t))
  9038. (user-error (if deadline? "No deadline information to update"
  9039. "No scheduled information to update"))
  9040. (let* ((rpl0 (match-string 1))
  9041. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  9042. (msg (if deadline? "Warn starting from" "Delay until")))
  9043. (replace-match
  9044. (concat keyword
  9045. " <" rpl
  9046. (format " -%dd"
  9047. (abs (- (time-to-days
  9048. (save-match-data
  9049. (org-read-date
  9050. nil t nil msg old-date-time)))
  9051. (time-to-days old-date-time))))
  9052. ">") t t))))))
  9053. (_
  9054. (org-add-planning-info type time 'closed)
  9055. (when (and old-date
  9056. log
  9057. (not (equal old-date org-last-inserted-timestamp)))
  9058. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  9059. org-last-inserted-timestamp
  9060. old-date
  9061. log))
  9062. (when repeater
  9063. (save-excursion
  9064. (org-back-to-heading t)
  9065. (when (re-search-forward
  9066. (concat keyword " " org-last-inserted-timestamp)
  9067. (line-end-position 2)
  9068. t)
  9069. (goto-char (1- (match-end 0)))
  9070. (insert-and-inherit " " repeater)
  9071. (setq org-last-inserted-timestamp
  9072. (concat (substring org-last-inserted-timestamp 0 -1)
  9073. " " repeater
  9074. (substring org-last-inserted-timestamp -1))))))
  9075. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  9076. org-last-inserted-timestamp))))))
  9077. (defun org-deadline (arg &optional time)
  9078. "Insert a \"DEADLINE:\" string with a timestamp to make a deadline.
  9079. When called interactively, this command pops up the Emacs calendar to let
  9080. the user select a date.
  9081. With one universal prefix argument, remove any deadline from the item.
  9082. With two universal prefix arguments, prompt for a warning delay.
  9083. With argument TIME, set the deadline at the corresponding date. TIME
  9084. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9085. (interactive "P")
  9086. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9087. (org-map-entries
  9088. (lambda () (org--deadline-or-schedule arg 'deadline time))
  9089. nil
  9090. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9091. 'region-start-level
  9092. 'region)
  9093. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9094. (org--deadline-or-schedule arg 'deadline time)))
  9095. (defun org-schedule (arg &optional time)
  9096. "Insert a \"SCHEDULED:\" string with a timestamp to schedule an item.
  9097. When called interactively, this command pops up the Emacs calendar to let
  9098. the user select a date.
  9099. With one universal prefix argument, remove any scheduling date from the item.
  9100. With two universal prefix arguments, prompt for a delay cookie.
  9101. With argument TIME, scheduled at the corresponding date. TIME can
  9102. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9103. (interactive "P")
  9104. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9105. (org-map-entries
  9106. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  9107. nil
  9108. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9109. 'region-start-level
  9110. 'region)
  9111. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9112. (org--deadline-or-schedule arg 'scheduled time)))
  9113. (defun org-get-scheduled-time (pom &optional inherit)
  9114. "Get the scheduled time as a time tuple, of a format suitable
  9115. for calling org-schedule with, or if there is no scheduling,
  9116. returns nil."
  9117. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  9118. (when time
  9119. (org-time-string-to-time time))))
  9120. (defun org-get-deadline-time (pom &optional inherit)
  9121. "Get the deadline as a time tuple, of a format suitable for
  9122. calling org-deadline with, or if there is no scheduling, returns
  9123. nil."
  9124. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  9125. (when time
  9126. (org-time-string-to-time time))))
  9127. (defun org-remove-timestamp-with-keyword (keyword)
  9128. "Remove all time stamps with KEYWORD in the current entry."
  9129. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  9130. beg)
  9131. (save-excursion
  9132. (org-back-to-heading t)
  9133. (setq beg (point))
  9134. (outline-next-heading)
  9135. (while (re-search-backward re beg t)
  9136. (replace-match "")
  9137. (if (and (string-match "\\S-" (buffer-substring (line-beginning-position) (point)))
  9138. (equal (char-before) ?\ ))
  9139. (backward-delete-char 1)
  9140. (when (string-match "^[ \t]*$" (buffer-substring
  9141. (line-beginning-position) (line-end-position)))
  9142. (delete-region (line-beginning-position)
  9143. (min (point-max) (1+ (line-end-position))))))))))
  9144. (defvar org-time-was-given) ; dynamically scoped parameter
  9145. (defvar org-end-time-was-given) ; dynamically scoped parameter
  9146. (defun org-at-planning-p ()
  9147. "Non-nil when point is on a planning info line."
  9148. ;; This is as accurate and faster than `org-element-at-point' since
  9149. ;; planning info location is fixed in the section.
  9150. (or (let ((cached (org-element-at-point nil 'cached)))
  9151. (and cached
  9152. (eq 'planning (org-element-type cached))))
  9153. (org-with-wide-buffer
  9154. (beginning-of-line)
  9155. (and (looking-at-p org-planning-line-re)
  9156. (eq (point)
  9157. (ignore-errors
  9158. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  9159. (org-back-to-heading t)
  9160. (org-with-limited-levels (org-back-to-heading t)))
  9161. (line-beginning-position 2)))))))
  9162. (defun org-add-planning-info (what &optional time &rest remove)
  9163. "Insert new timestamp with keyword in the planning line.
  9164. WHAT indicates what kind of time stamp to add. It is a symbol
  9165. among `closed', `deadline', `scheduled' and nil. TIME indicates
  9166. the time to use. If none is given, the user is prompted for
  9167. a date. REMOVE indicates what kind of entries to remove. An old
  9168. WHAT entry will also be removed."
  9169. (org-fold-core-ignore-modifications
  9170. (let (org-time-was-given org-end-time-was-given default-time default-input)
  9171. (when (and (memq what '(scheduled deadline))
  9172. (or (not time)
  9173. (and (stringp time)
  9174. (string-match "^[-+]+[0-9]" time))))
  9175. ;; Try to get a default date/time from existing timestamp
  9176. (save-excursion
  9177. (org-back-to-heading t)
  9178. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  9179. (when (re-search-forward (if (eq what 'scheduled)
  9180. org-scheduled-time-regexp
  9181. org-deadline-time-regexp)
  9182. end t)
  9183. (setq ts (match-string 1)
  9184. default-time (org-time-string-to-time ts)
  9185. default-input (and ts (org-get-compact-tod ts)))))))
  9186. (when what
  9187. (setq time
  9188. (if (stringp time)
  9189. ;; This is a string (relative or absolute), set
  9190. ;; proper date.
  9191. (org-encode-time
  9192. (org-read-date-analyze
  9193. time default-time (decode-time default-time)))
  9194. ;; If necessary, get the time from the user
  9195. (or time (org-read-date nil 'to-time nil
  9196. (cl-case what
  9197. (deadline "DEADLINE")
  9198. (scheduled "SCHEDULED")
  9199. (otherwise nil))
  9200. default-time default-input)))))
  9201. (org-with-wide-buffer
  9202. (org-back-to-heading t)
  9203. (let ((planning? (save-excursion
  9204. (forward-line)
  9205. (looking-at-p org-planning-line-re))))
  9206. (cond
  9207. (planning?
  9208. (forward-line)
  9209. ;; Move to current indentation.
  9210. (skip-chars-forward " \t")
  9211. ;; Check if we have to remove something.
  9212. (dolist (type (if what (cons what remove) remove))
  9213. (save-excursion
  9214. (when (re-search-forward
  9215. (cl-case type
  9216. (closed org-closed-time-regexp)
  9217. (deadline org-deadline-time-regexp)
  9218. (scheduled org-scheduled-time-regexp)
  9219. (otherwise (error "Invalid planning type: %s" type)))
  9220. (line-end-position)
  9221. t)
  9222. ;; Delete until next keyword or end of line.
  9223. (delete-region
  9224. (match-beginning 0)
  9225. (if (re-search-forward org-keyword-time-not-clock-regexp
  9226. (line-end-position)
  9227. t)
  9228. (match-beginning 0)
  9229. (line-end-position))))))
  9230. ;; If there is nothing more to add and no more keyword is
  9231. ;; left, remove the line completely.
  9232. (if (and (looking-at-p "[ \t]*$") (not what))
  9233. (delete-region (line-end-position 0)
  9234. (line-end-position))
  9235. ;; If we removed last keyword, do not leave trailing white
  9236. ;; space at the end of line.
  9237. (let ((p (point)))
  9238. (save-excursion
  9239. (end-of-line)
  9240. (unless (= (skip-chars-backward " \t" p) 0)
  9241. (delete-region (point) (line-end-position)))))))
  9242. (what
  9243. (end-of-line)
  9244. (insert-and-inherit "\n")
  9245. (when org-adapt-indentation
  9246. (indent-to-column (1+ (org-outline-level)))))
  9247. (t nil)))
  9248. (when what
  9249. ;; Insert planning keyword.
  9250. (insert-and-inherit (cl-case what
  9251. (closed org-closed-string)
  9252. (deadline org-deadline-string)
  9253. (scheduled org-scheduled-string)
  9254. (otherwise (error "Invalid planning type: %s" what)))
  9255. " ")
  9256. ;; Insert associated timestamp.
  9257. (let ((ts (org-insert-time-stamp
  9258. time
  9259. (or org-time-was-given
  9260. (and (eq what 'closed) org-log-done-with-time))
  9261. (eq what 'closed)
  9262. nil nil (list org-end-time-was-given))))
  9263. (unless (eolp) (insert " "))
  9264. ts))))))
  9265. (defvar org-log-note-marker (make-marker)
  9266. "Marker pointing at the entry where the note is to be inserted.")
  9267. (defvar org-log-note-purpose nil)
  9268. (defvar org-log-note-state nil)
  9269. (defvar org-log-note-previous-state nil)
  9270. (defvar org-log-note-extra nil)
  9271. (defvar org-log-note-window-configuration nil)
  9272. (defvar org-log-note-return-to (make-marker))
  9273. (defvar org-log-note-effective-time nil
  9274. "Remembered current time.
  9275. So that dynamically scoped `org-extend-today-until' affects
  9276. timestamps in state change log.")
  9277. (defvar org-log-note-this-command
  9278. "`this-command' when `org-add-log-setup' is called.")
  9279. (defvar org-log-note-recursion-depth
  9280. "`recursion-depth' when `org-add-log-setup' is called.")
  9281. (defvar org-log-post-message nil
  9282. "Message to be displayed after a log note has been stored.
  9283. The auto-repeater uses this.")
  9284. (defun org-add-note ()
  9285. "Add a note to the current entry.
  9286. This is done in the same way as adding a state change note."
  9287. (interactive)
  9288. (org-add-log-setup 'note))
  9289. (defun org-log-beginning (&optional create)
  9290. "Return expected start of log notes in current entry.
  9291. When optional argument CREATE is non-nil, the function creates
  9292. a drawer to store notes, if necessary. Returned position ignores
  9293. narrowing."
  9294. (org-with-wide-buffer
  9295. (let ((drawer (org-log-into-drawer)))
  9296. (cond
  9297. (drawer
  9298. (org-end-of-meta-data)
  9299. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  9300. (end (if (org-at-heading-p) (point)
  9301. (save-excursion (outline-next-heading) (point))))
  9302. (case-fold-search t))
  9303. (catch 'exit
  9304. ;; Try to find existing drawer.
  9305. (while (re-search-forward regexp end t)
  9306. (let ((element (org-element-at-point)))
  9307. (when (eq (org-element-type element) 'drawer)
  9308. (let ((cend (org-element-property :contents-end element)))
  9309. (when (and (not org-log-states-order-reversed) cend)
  9310. (goto-char cend)))
  9311. (throw 'exit nil))))
  9312. ;; No drawer found. Create one, if permitted.
  9313. (when create
  9314. ;; Unless current heading is the last heading in buffer
  9315. ;; and does not have a newline, `org-end-of-meta-data'
  9316. ;; should move us somewhere below the heading.
  9317. ;; Avoid situation when we insert drawer right before
  9318. ;; first "*". Otherwise, if the previous heading is
  9319. ;; folded, we are inserting after visible newline at
  9320. ;; the end of the fold, thus breaking the fold
  9321. ;; continuity.
  9322. (unless (eobp)
  9323. (when (org-at-heading-p) (backward-char)))
  9324. (org-fold-core-ignore-modifications
  9325. (unless (bolp) (insert-and-inherit "\n"))
  9326. (let ((beg (point)))
  9327. (insert-and-inherit ":" drawer ":\n:END:\n")
  9328. (org-indent-region beg (point))
  9329. (org-fold-region (line-end-position -1) (1- (point)) t (if (eq org-fold-core-style 'text-properties) 'drawer 'outline)))))
  9330. (end-of-line -1))))
  9331. (t
  9332. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  9333. (let ((endpos (point)))
  9334. (skip-chars-forward " \t\n")
  9335. (beginning-of-line)
  9336. (unless org-log-states-order-reversed
  9337. (org-skip-over-state-notes)
  9338. (skip-chars-backward " \t\n")
  9339. (beginning-of-line 2))
  9340. ;; When current headline is at the end of buffer and does not
  9341. ;; end with trailing newline the above can move to the
  9342. ;; beginning of the headline.
  9343. (when (< (point) endpos) (goto-char endpos))))))
  9344. (if (bolp) (point) (line-beginning-position 2))))
  9345. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  9346. "Set up the post command hook to take a note.
  9347. If this is about to TODO state change, the new state is expected in STATE.
  9348. HOW is an indicator what kind of note should be created.
  9349. EXTRA is additional text that will be inserted into the notes buffer."
  9350. (move-marker org-log-note-marker (point))
  9351. (setq org-log-note-purpose purpose
  9352. org-log-note-state state
  9353. org-log-note-previous-state prev-state
  9354. org-log-note-how how
  9355. org-log-note-extra extra
  9356. org-log-note-effective-time (org-current-effective-time)
  9357. org-log-note-this-command this-command
  9358. org-log-note-recursion-depth (recursion-depth)
  9359. org-log-setup t)
  9360. (add-hook 'post-command-hook 'org-add-log-note 'append))
  9361. (defun org-skip-over-state-notes ()
  9362. "Skip past the list of State notes in an entry."
  9363. (when (ignore-errors (goto-char (org-in-item-p)))
  9364. (let* ((struct (org-list-struct))
  9365. (prevs (org-list-prevs-alist struct))
  9366. (regexp
  9367. (concat "[ \t]*- +"
  9368. (replace-regexp-in-string
  9369. " +" " +"
  9370. (org-replace-escapes
  9371. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  9372. `(("%d" . ,org-ts-regexp-inactive)
  9373. ("%D" . ,org-ts-regexp)
  9374. ("%s" . "\\(?:\"\\S-+\"\\)?")
  9375. ("%S" . "\\(?:\"\\S-+\"\\)?")
  9376. ("%t" . ,org-ts-regexp-inactive)
  9377. ("%T" . ,org-ts-regexp)
  9378. ("%u" . ".*?")
  9379. ("%U" . ".*?")))))))
  9380. (while (looking-at-p regexp)
  9381. (goto-char (or (org-list-get-next-item (point) struct prevs)
  9382. (org-list-get-item-end (point) struct)))))))
  9383. (defun org-add-log-note (&optional _purpose)
  9384. "Pop up a window for taking a note, and add this note later."
  9385. (when (and (equal org-log-note-this-command this-command)
  9386. (= org-log-note-recursion-depth (recursion-depth)))
  9387. (remove-hook 'post-command-hook 'org-add-log-note)
  9388. (setq org-log-setup nil)
  9389. (setq org-log-note-window-configuration (current-window-configuration))
  9390. (delete-other-windows)
  9391. (move-marker org-log-note-return-to (point))
  9392. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  9393. (goto-char org-log-note-marker)
  9394. (org-switch-to-buffer-other-window "*Org Note*")
  9395. (erase-buffer)
  9396. (if (memq org-log-note-how '(time state))
  9397. (org-store-log-note)
  9398. (let ((org-inhibit-startup t)) (org-mode))
  9399. (insert (format "# Insert note for %s.
  9400. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  9401. (cl-case org-log-note-purpose
  9402. (clock-out "stopped clock")
  9403. (done "closed todo item")
  9404. (reschedule "rescheduling")
  9405. (delschedule "no longer scheduled")
  9406. (redeadline "changing deadline")
  9407. (deldeadline "removing deadline")
  9408. (refile "refiling")
  9409. (note "this entry")
  9410. (state
  9411. (format "state change from \"%s\" to \"%s\""
  9412. (or org-log-note-previous-state "")
  9413. (or org-log-note-state "")))
  9414. (t (error "This should not happen")))))
  9415. (when org-log-note-extra (insert org-log-note-extra))
  9416. (setq-local org-finish-function 'org-store-log-note)
  9417. (run-hooks 'org-log-buffer-setup-hook))))
  9418. (defvar org-note-abort nil) ; dynamically scoped
  9419. (defun org-store-log-note ()
  9420. "Finish taking a log note, and insert it to where it belongs."
  9421. (let ((txt (prog1 (buffer-string)
  9422. (kill-buffer)))
  9423. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  9424. lines)
  9425. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  9426. (setq txt (replace-match "" t t txt)))
  9427. (when (string-match "\\s-+\\'" txt)
  9428. (setq txt (replace-match "" t t txt)))
  9429. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  9430. (when (org-string-nw-p note)
  9431. (setq note
  9432. (org-replace-escapes
  9433. note
  9434. (list (cons "%u" (user-login-name))
  9435. (cons "%U" user-full-name)
  9436. (cons "%t" (format-time-string
  9437. (org-time-stamp-format 'long 'inactive)
  9438. org-log-note-effective-time))
  9439. (cons "%T" (format-time-string
  9440. (org-time-stamp-format 'long nil)
  9441. org-log-note-effective-time))
  9442. (cons "%d" (format-time-string
  9443. (org-time-stamp-format nil 'inactive)
  9444. org-log-note-effective-time))
  9445. (cons "%D" (format-time-string
  9446. (org-time-stamp-format nil nil)
  9447. org-log-note-effective-time))
  9448. (cons "%s" (cond
  9449. ((not org-log-note-state) "")
  9450. ((string-match-p org-ts-regexp
  9451. org-log-note-state)
  9452. (format "\"[%s]\""
  9453. (substring org-log-note-state 1 -1)))
  9454. (t (format "\"%s\"" org-log-note-state))))
  9455. (cons "%S"
  9456. (cond
  9457. ((not org-log-note-previous-state) "")
  9458. ((string-match-p org-ts-regexp
  9459. org-log-note-previous-state)
  9460. (format "\"[%s]\""
  9461. (substring
  9462. org-log-note-previous-state 1 -1)))
  9463. (t (format "\"%s\""
  9464. org-log-note-previous-state)))))))
  9465. (when lines (setq note (concat note " \\\\")))
  9466. (push note lines))
  9467. (when (and lines (not org-note-abort))
  9468. (with-current-buffer (marker-buffer org-log-note-marker)
  9469. (org-fold-core-ignore-modifications
  9470. (org-with-wide-buffer
  9471. ;; Find location for the new note.
  9472. (goto-char org-log-note-marker)
  9473. (set-marker org-log-note-marker nil)
  9474. ;; Note associated to a clock is to be located right after
  9475. ;; the clock. Do not move point.
  9476. (unless (eq org-log-note-purpose 'clock-out)
  9477. (goto-char (org-log-beginning t)))
  9478. ;; Make sure point is at the beginning of an empty line.
  9479. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert-and-inherit "\n")))
  9480. ((looking-at "[ \t]*\\S-") (save-excursion (insert-and-inherit "\n"))))
  9481. ;; In an existing list, add a new item at the top level.
  9482. ;; Otherwise, indent line like a regular one.
  9483. (let ((itemp (org-in-item-p)))
  9484. (if itemp
  9485. (indent-line-to
  9486. (let ((struct (save-excursion
  9487. (goto-char itemp) (org-list-struct))))
  9488. (org-list-get-ind (org-list-get-top-point struct) struct)))
  9489. (org-indent-line)))
  9490. (insert-and-inherit (org-list-bullet-string "-") (pop lines))
  9491. (let ((ind (org-list-item-body-column (line-beginning-position))))
  9492. (dolist (line lines)
  9493. (insert-and-inherit "\n")
  9494. (unless (string-empty-p line)
  9495. (indent-line-to ind)
  9496. (insert-and-inherit line))))
  9497. (message "Note stored")
  9498. (org-back-to-heading t))))))
  9499. ;; Don't add undo information when called from `org-agenda-todo'.
  9500. (set-window-configuration org-log-note-window-configuration)
  9501. (with-current-buffer (marker-buffer org-log-note-return-to)
  9502. (goto-char org-log-note-return-to))
  9503. (move-marker org-log-note-return-to nil)
  9504. (when org-log-post-message (message "%s" org-log-post-message)))
  9505. (defun org-remove-empty-drawer-at (pos)
  9506. "Remove an empty drawer at position POS.
  9507. POS may also be a marker."
  9508. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  9509. (org-with-wide-buffer
  9510. (goto-char pos)
  9511. (let ((drawer (org-element-at-point)))
  9512. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  9513. (not (org-element-property :contents-begin drawer)))
  9514. (delete-region (org-element-property :begin drawer)
  9515. (progn (goto-char (org-element-property :end drawer))
  9516. (skip-chars-backward " \r\t\n")
  9517. (forward-line)
  9518. (point))))))))
  9519. (defvar org-ts-type nil)
  9520. (defun org-sparse-tree (&optional arg type)
  9521. "Create a sparse tree, prompt for the details.
  9522. This command can create sparse trees. You first need to select the type
  9523. of match used to create the tree:
  9524. t Show all TODO entries.
  9525. T Show entries with a specific TODO keyword.
  9526. m Show entries selected by a tags/property match.
  9527. p Enter a property name and its value (both with completion on existing
  9528. names/values) and show entries with that property.
  9529. r Show entries matching a regular expression (`/' can be used as well).
  9530. b Show deadlines and scheduled items before a date.
  9531. a Show deadlines and scheduled items after a date.
  9532. d Show deadlines due within `org-deadline-warning-days'.
  9533. D Show deadlines and scheduled items between a date range."
  9534. (interactive "P")
  9535. (setq type (or type org-sparse-tree-default-date-type))
  9536. (setq org-ts-type type)
  9537. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  9538. [d]eadlines [b]efore-date [a]fter-date [D]ates range
  9539. [c]ycle through date types: %s"
  9540. (cl-case type
  9541. (all "all timestamps")
  9542. (scheduled "only scheduled")
  9543. (deadline "only deadline")
  9544. (active "only active timestamps")
  9545. (inactive "only inactive timestamps")
  9546. (closed "with a closed time-stamp")
  9547. (otherwise "scheduled/deadline")))
  9548. (let ((answer (read-char-exclusive)))
  9549. (cl-case answer
  9550. (?c
  9551. (org-sparse-tree
  9552. arg
  9553. (cadr
  9554. (memq type '(nil all scheduled deadline active inactive closed)))))
  9555. (?d (call-interactively 'org-check-deadlines))
  9556. (?b (call-interactively 'org-check-before-date))
  9557. (?a (call-interactively 'org-check-after-date))
  9558. (?D (call-interactively 'org-check-dates-range))
  9559. (?t (call-interactively 'org-show-todo-tree))
  9560. (?T (org-show-todo-tree '(4)))
  9561. (?m (call-interactively 'org-match-sparse-tree))
  9562. ((?p ?P)
  9563. (let* ((kwd (completing-read
  9564. "Property: " (mapcar #'list (org-buffer-property-keys))))
  9565. (value (completing-read
  9566. "Value: " (mapcar #'list (org-property-values kwd)))))
  9567. (unless (string-match "\\`{.*}\\'" value)
  9568. (setq value (concat "\"" value "\"")))
  9569. (org-match-sparse-tree arg (concat kwd "=" value))))
  9570. ((?r ?R ?/) (call-interactively 'org-occur))
  9571. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  9572. (defvar-local org-occur-highlights nil
  9573. "List of overlays used for occur matches.")
  9574. (defvar-local org-occur-parameters nil
  9575. "Parameters of the active org-occur calls.
  9576. This is a list, each call to org-occur pushes as cons cell,
  9577. containing the regular expression and the callback, onto the list.
  9578. The list can contain several entries if `org-occur' has been called
  9579. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  9580. will only contain one set of parameters. When the highlights are
  9581. removed (for example with `C-c C-c', or with the next edit (depending
  9582. on `org-remove-highlights-with-change'), this variable is emptied
  9583. as well.")
  9584. (defun org-occur (regexp &optional keep-previous callback)
  9585. "Make a compact tree showing all matches of REGEXP.
  9586. The tree will show the lines where the regexp matches, and any other context
  9587. defined in `org-fold-show-context-detail', which see.
  9588. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  9589. done by a previous call to `org-occur' will be kept, to allow stacking of
  9590. calls to this command.
  9591. Optional argument CALLBACK can be a function of no argument. In this case,
  9592. it is called with point at the end of the match, match data being set
  9593. accordingly. Current match is shown only if the return value is non-nil.
  9594. The function must neither move point nor alter narrowing."
  9595. (interactive "sRegexp: \nP")
  9596. (when (equal regexp "")
  9597. (user-error "Regexp cannot be empty"))
  9598. (unless keep-previous
  9599. (org-remove-occur-highlights nil nil t))
  9600. (push (cons regexp callback) org-occur-parameters)
  9601. (let ((cnt 0))
  9602. (save-excursion
  9603. (goto-char (point-min))
  9604. (when (or (not keep-previous) ; do not want to keep
  9605. (not org-occur-highlights)) ; no previous matches
  9606. ;; hide everything
  9607. (org-cycle-overview))
  9608. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  9609. (isearch-no-upper-case-p regexp t)
  9610. org-occur-case-fold-search)))
  9611. (while (re-search-forward regexp nil t)
  9612. (when (or (not callback)
  9613. (save-match-data (funcall callback)))
  9614. (setq cnt (1+ cnt))
  9615. (when org-highlight-sparse-tree-matches
  9616. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  9617. (org-fold-show-context 'occur-tree)))))
  9618. (when org-remove-highlights-with-change
  9619. (add-hook 'before-change-functions 'org-remove-occur-highlights
  9620. nil 'local))
  9621. (unless org-sparse-tree-open-archived-trees
  9622. (org-fold-hide-archived-subtrees (point-min) (point-max)))
  9623. (run-hooks 'org-occur-hook)
  9624. (when (called-interactively-p 'interactive)
  9625. (message "%d match(es) for regexp %s" cnt regexp))
  9626. cnt))
  9627. (defun org-occur-next-match (&optional n _reset)
  9628. "Function for `next-error-function' to find sparse tree matches.
  9629. N is the number of matches to move, when negative move backwards.
  9630. This function always goes back to the starting point when no
  9631. match is found."
  9632. (let* ((limit (if (< n 0) (point-min) (point-max)))
  9633. (search-func (if (< n 0)
  9634. 'previous-single-char-property-change
  9635. 'next-single-char-property-change))
  9636. (n (abs n))
  9637. (pos (point))
  9638. p1)
  9639. (catch 'exit
  9640. (while (setq p1 (funcall search-func (point) 'org-type))
  9641. (when (equal p1 limit)
  9642. (goto-char pos)
  9643. (user-error "No more matches"))
  9644. (when (equal (get-char-property p1 'org-type) 'org-occur)
  9645. (setq n (1- n))
  9646. (when (= n 0)
  9647. (goto-char p1)
  9648. (throw 'exit (point))))
  9649. (goto-char p1))
  9650. (goto-char p1)
  9651. (user-error "No more matches"))))
  9652. (defun org-highlight-new-match (beg end)
  9653. "Highlight from BEG to END and mark the highlight is an occur headline."
  9654. (let ((ov (make-overlay beg end)))
  9655. (overlay-put ov 'face 'secondary-selection)
  9656. (overlay-put ov 'org-type 'org-occur)
  9657. (push ov org-occur-highlights)))
  9658. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  9659. "Remove the occur highlights from the buffer.
  9660. BEG and END are ignored. If NOREMOVE is nil, remove this function
  9661. from the `before-change-functions' in the current buffer."
  9662. (interactive)
  9663. (unless org-inhibit-highlight-removal
  9664. (mapc #'delete-overlay org-occur-highlights)
  9665. (setq org-occur-highlights nil)
  9666. (setq org-occur-parameters nil)
  9667. (unless noremove
  9668. (remove-hook 'before-change-functions
  9669. 'org-remove-occur-highlights 'local))))
  9670. ;;;; Priorities
  9671. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]+\\)\\] ?\\)"
  9672. "Regular expression matching the priority indicator.
  9673. A priority indicator can be e.g. [#A] or [#1].
  9674. This regular expression matches these groups:
  9675. 0 : the whole match, e.g. \"TODO [#A] Hack\"
  9676. 1 : the priority cookie, e.g. \"[#A]\"
  9677. 2 : the value of the priority cookie, e.g. \"A\".")
  9678. (defun org-priority-up ()
  9679. "Increase the priority of the current item."
  9680. (interactive)
  9681. (org-priority 'up))
  9682. (defun org-priority-down ()
  9683. "Decrease the priority of the current item."
  9684. (interactive)
  9685. (org-priority 'down))
  9686. (defun org-priority (&optional action show)
  9687. "Change the priority of an item.
  9688. When called interactively with a `\\[universal-argument]' prefix,
  9689. show the priority in the minibuffer instead of changing it.
  9690. When called programmatically, ACTION can be `set', `up', `down',
  9691. or a character."
  9692. (interactive "P")
  9693. (when show
  9694. ;; Deprecation warning inserted for Org 9.2; once enough time has
  9695. ;; passed the SHOW argument should be removed.
  9696. (warn "`org-priority' called with deprecated SHOW argument"))
  9697. (if (equal action '(4))
  9698. (org-priority-show)
  9699. (unless org-priority-enable-commands
  9700. (user-error "Priority commands are disabled"))
  9701. (setq action (or action 'set))
  9702. (let ((nump (< org-priority-lowest 65))
  9703. current new news have remove)
  9704. (save-excursion
  9705. (org-back-to-heading t)
  9706. (when (looking-at org-priority-regexp)
  9707. (let ((ms (match-string 2)))
  9708. (setq current (org-priority-to-value ms)
  9709. have t)))
  9710. (cond
  9711. ((eq action 'remove)
  9712. (setq remove t new ?\ ))
  9713. ((or (eq action 'set)
  9714. (integerp action))
  9715. (if (not (eq action 'set))
  9716. (setq new action)
  9717. (setq
  9718. new
  9719. (if nump
  9720. (let* ((msg (format "Priority %s-%s, SPC to remove: "
  9721. (number-to-string org-priority-highest)
  9722. (number-to-string org-priority-lowest)))
  9723. (s (if (< 9 org-priority-lowest)
  9724. (read-string msg)
  9725. (message msg)
  9726. (char-to-string (read-char-exclusive)))))
  9727. (if (equal s " ") ?\s (string-to-number s)))
  9728. (progn (message "Priority %c-%c, SPC to remove: "
  9729. org-priority-highest org-priority-lowest)
  9730. (save-match-data
  9731. (setq new (read-char-exclusive)))))))
  9732. (when (and (= (upcase org-priority-highest) org-priority-highest)
  9733. (= (upcase org-priority-lowest) org-priority-lowest))
  9734. (setq new (upcase new)))
  9735. (cond ((equal new ?\s) (setq remove t))
  9736. ((or (< (upcase new) org-priority-highest) (> (upcase new) org-priority-lowest))
  9737. (user-error
  9738. (if nump
  9739. "Priority must be between `%s' and `%s'"
  9740. "Priority must be between `%c' and `%c'")
  9741. org-priority-highest org-priority-lowest))))
  9742. ((eq action 'up)
  9743. (setq new (if have
  9744. (1- current) ; normal cycling
  9745. ;; last priority was empty
  9746. (if (eq last-command this-command)
  9747. org-priority-lowest ; wrap around empty to lowest
  9748. ;; default
  9749. (if org-priority-start-cycle-with-default
  9750. org-priority-default
  9751. (1- org-priority-default))))))
  9752. ((eq action 'down)
  9753. (setq new (if have
  9754. (1+ current) ; normal cycling
  9755. ;; last priority was empty
  9756. (if (eq last-command this-command)
  9757. org-priority-highest ; wrap around empty to highest
  9758. ;; default
  9759. (if org-priority-start-cycle-with-default
  9760. org-priority-default
  9761. (1+ org-priority-default))))))
  9762. (t (user-error "Invalid action")))
  9763. (when (or (< (upcase new) org-priority-highest)
  9764. (> (upcase new) org-priority-lowest))
  9765. (if (and (memq action '(up down))
  9766. (not have) (not (eq last-command this-command)))
  9767. ;; `new' is from default priority
  9768. (error
  9769. "The default can not be set, see `org-priority-default' why")
  9770. ;; normal cycling: `new' is beyond highest/lowest priority
  9771. ;; and is wrapped around to the empty priority
  9772. (setq remove t)))
  9773. ;; Numerical priorities are limited to 64, beyond that number,
  9774. ;; assume the priority cookie is a character.
  9775. (setq news (if (> new 64) (format "%c" new) (format "%s" new)))
  9776. (if have
  9777. (if remove
  9778. (replace-match "" t t nil 1)
  9779. (replace-match news t t nil 2))
  9780. (if remove
  9781. (user-error "No priority cookie found in line")
  9782. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  9783. (if (match-end 2)
  9784. (progn
  9785. (goto-char (match-end 2))
  9786. (insert " [#" news "]"))
  9787. (goto-char (match-beginning 3))
  9788. (insert "[#" news "] "))))
  9789. (org-align-tags))
  9790. (if remove
  9791. (message "Priority removed")
  9792. (message "Priority of current item set to %s" news)))))
  9793. (defalias 'org-show-priority 'org-priority-show)
  9794. (defun org-priority-show ()
  9795. "Show the priority of the current item.
  9796. This priority is composed of the main priority given with the [#A] cookies,
  9797. and by additional input from the age of a schedules or deadline entry."
  9798. (interactive)
  9799. (let ((pri (if (eq major-mode 'org-agenda-mode)
  9800. (org-get-at-bol 'priority)
  9801. (save-excursion
  9802. (save-match-data
  9803. (beginning-of-line)
  9804. (and (looking-at org-heading-regexp)
  9805. (org-get-priority (match-string 0))))))))
  9806. (message "Priority is %d" (if pri pri -1000))))
  9807. (defun org-get-priority (s)
  9808. "Find priority cookie and return priority.
  9809. S is a string against which you can match `org-priority-regexp'.
  9810. If `org-priority-get-priority-function' is set to a custom
  9811. function, use it. Otherwise process S and output the priority
  9812. value, an integer."
  9813. (save-match-data
  9814. (if (functionp org-priority-get-priority-function)
  9815. (funcall org-priority-get-priority-function s)
  9816. (if (not (string-match org-priority-regexp s))
  9817. (* 1000 (- org-priority-lowest org-priority-default))
  9818. (* 1000 (- org-priority-lowest
  9819. (org-priority-to-value (match-string 2 s))))))))
  9820. ;;;; Tags
  9821. (defvar org-agenda-archives-mode)
  9822. (defvar org-map-continue-from nil
  9823. "Position from where mapping should continue.
  9824. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  9825. (defvar org-scanner-tags nil
  9826. "The current tag list while the tags scanner is running.")
  9827. (defvar org-trust-scanner-tags nil
  9828. "Should `org-get-tags' use the tags for the scanner.
  9829. This is for internal dynamical scoping only.
  9830. When this is non-nil, the function `org-get-tags' will return the value
  9831. of `org-scanner-tags' instead of building the list by itself. This
  9832. can lead to large speed-ups when the tags scanner is used in a file with
  9833. many entries, and when the list of tags is retrieved, for example to
  9834. obtain a list of properties. Building the tags list for each entry in such
  9835. a file becomes an N^2 operation - but with this variable set, it scales
  9836. as N.")
  9837. (defvar org--matcher-tags-todo-only nil)
  9838. (defun org-scan-tags (action matcher todo-only &optional start-level)
  9839. "Scan headline tags with inheritance and produce output ACTION.
  9840. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  9841. or `agenda' to produce an entry list for an agenda view. It can also be
  9842. a Lisp form or a function that should be called at each matched headline, in
  9843. this case the return value is a list of all return values from these calls.
  9844. MATCHER is a function accepting three arguments, returning
  9845. a non-nil value whenever a given set of tags qualifies a headline
  9846. for inclusion. See `org-make-tags-matcher' for more information.
  9847. As a special case, it can also be set to t (respectively nil) in
  9848. order to match all (respectively none) headline.
  9849. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  9850. included in the output.
  9851. START-LEVEL can be a string with asterisks, reducing the scope to
  9852. headlines matching this string."
  9853. (require 'org-agenda)
  9854. (let* ((re (concat "^"
  9855. (if start-level
  9856. ;; Get the correct level to match
  9857. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  9858. org-outline-regexp)
  9859. " *\\(?:\\(" (regexp-opt org-todo-keywords-1 t) "\\) \\)?"
  9860. " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
  9861. (props (list 'face 'default
  9862. 'done-face 'org-agenda-done
  9863. 'undone-face 'default
  9864. 'mouse-face 'highlight
  9865. 'org-not-done-regexp org-not-done-regexp
  9866. 'org-todo-regexp org-todo-regexp
  9867. 'org-complex-heading-regexp org-complex-heading-regexp
  9868. 'help-echo
  9869. (format "mouse-2 or RET jump to Org file %S"
  9870. (abbreviate-file-name
  9871. (or (buffer-file-name (buffer-base-buffer))
  9872. (buffer-name (buffer-base-buffer)))))))
  9873. (org-map-continue-from nil)
  9874. lspos tags tags-list
  9875. (tags-alist (list (cons 0 org-file-tags)))
  9876. (llast 0) rtn rtn1 level category i txt
  9877. todo marker entry priority
  9878. ts-date ts-date-type ts-date-pair)
  9879. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  9880. (setq action (list 'lambda nil action)))
  9881. (save-excursion
  9882. (goto-char (point-min))
  9883. (when (eq action 'sparse-tree)
  9884. (org-cycle-overview)
  9885. (org-remove-occur-highlights))
  9886. (if (org-element--cache-active-p)
  9887. (let ((fast-re (concat "^"
  9888. (if start-level
  9889. ;; Get the correct level to match
  9890. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  9891. org-outline-regexp))))
  9892. (org-element-cache-map
  9893. (lambda (el)
  9894. (goto-char (org-element-property :begin el))
  9895. (setq todo (org-element-property :todo-keyword el)
  9896. level (org-element-property :level el)
  9897. category (org-entry-get-with-inheritance "CATEGORY" nil el)
  9898. tags-list (org-get-tags el)
  9899. org-scanner-tags tags-list)
  9900. (when (eq action 'agenda)
  9901. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  9902. ts-date (car ts-date-pair)
  9903. ts-date-type (cdr ts-date-pair)))
  9904. (catch :skip
  9905. (when (and
  9906. ;; eval matcher only when the todo condition is OK
  9907. (and (or (not todo-only) (member todo org-todo-keywords-1))
  9908. (if (functionp matcher)
  9909. (let ((case-fold-search t) (org-trust-scanner-tags t))
  9910. (funcall matcher todo tags-list level))
  9911. matcher))
  9912. ;; Call the skipper, but return t if it does not
  9913. ;; skip, so that the `and' form continues evaluating.
  9914. (progn
  9915. (unless (eq action 'sparse-tree) (org-agenda-skip el))
  9916. t)
  9917. ;; Check if timestamps are deselecting this entry
  9918. (or (not todo-only)
  9919. (and (member todo org-todo-keywords-1)
  9920. (or (not org-agenda-tags-todo-honor-ignore-options)
  9921. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  9922. ;; select this headline
  9923. (cond
  9924. ((eq action 'sparse-tree)
  9925. (and org-highlight-sparse-tree-matches
  9926. (org-get-heading) (match-end 0)
  9927. (org-highlight-new-match
  9928. (match-beginning 1) (match-end 1)))
  9929. (org-fold-show-context 'tags-tree))
  9930. ((eq action 'agenda)
  9931. (let* ((effort (org-entry-get (point) org-effort-property))
  9932. (effort-minutes (when effort (save-match-data (org-duration-to-minutes effort)))))
  9933. (setq txt (org-agenda-format-item
  9934. ""
  9935. ;; Add `effort' and `effort-minutes'
  9936. ;; properties for prefix format.
  9937. (org-add-props
  9938. (concat
  9939. (if (eq org-tags-match-list-sublevels 'indented)
  9940. (make-string (1- level) ?.) "")
  9941. (org-get-heading))
  9942. nil
  9943. 'effort effort
  9944. 'effort-minutes effort-minutes)
  9945. (make-string level ?\s)
  9946. category
  9947. tags-list)
  9948. priority (org-get-priority txt))
  9949. ;; Now add `effort' and `effort-minutes' to
  9950. ;; full agenda line.
  9951. (setq txt (org-add-props txt nil
  9952. 'effort effort
  9953. 'effort-minutes effort-minutes)))
  9954. (goto-char (org-element-property :begin el))
  9955. (setq marker (org-agenda-new-marker))
  9956. (org-add-props txt props
  9957. 'org-marker marker 'org-hd-marker marker 'org-category category
  9958. 'todo-state todo
  9959. 'ts-date ts-date
  9960. 'priority priority
  9961. 'type (concat "tagsmatch" ts-date-type))
  9962. (push txt rtn))
  9963. ((functionp action)
  9964. (setq org-map-continue-from nil)
  9965. (save-excursion
  9966. (setq rtn1 (funcall action))
  9967. (push rtn1 rtn)))
  9968. (t (user-error "Invalid action")))
  9969. ;; if we are to skip sublevels, jump to end of subtree
  9970. (unless org-tags-match-list-sublevels
  9971. (goto-char (1- (org-element-property :end el))))))
  9972. ;; Get the correct position from where to continue
  9973. (when org-map-continue-from
  9974. (setq org-element-cache-map-continue-from org-map-continue-from)
  9975. (goto-char org-map-continue-from))
  9976. ;; Return nil.
  9977. nil)
  9978. :next-re fast-re
  9979. :fail-re fast-re
  9980. :narrow t))
  9981. (while (let (case-fold-search)
  9982. (re-search-forward re nil t))
  9983. (setq org-map-continue-from nil)
  9984. (catch :skip
  9985. ;; Ignore closing parts of inline tasks.
  9986. (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
  9987. (throw :skip t))
  9988. (setq todo (and (match-end 1) (match-string-no-properties 1)))
  9989. (setq tags (and (match-end 4) (org-trim (match-string-no-properties 4))))
  9990. (goto-char (setq lspos (match-beginning 0)))
  9991. (setq level (org-reduced-level (org-outline-level))
  9992. category (org-get-category))
  9993. (when (eq action 'agenda)
  9994. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  9995. ts-date (car ts-date-pair)
  9996. ts-date-type (cdr ts-date-pair)))
  9997. (setq i llast llast level)
  9998. ;; remove tag lists from same and sublevels
  9999. (while (>= i level)
  10000. (when (setq entry (assoc i tags-alist))
  10001. (setq tags-alist (delete entry tags-alist)))
  10002. (setq i (1- i)))
  10003. ;; add the next tags
  10004. (when tags
  10005. (setq tags (org-split-string tags ":")
  10006. tags-alist
  10007. (cons (cons level tags) tags-alist)))
  10008. ;; compile tags for current headline
  10009. (setq tags-list
  10010. (if org-use-tag-inheritance
  10011. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  10012. tags)
  10013. org-scanner-tags tags-list)
  10014. (when org-use-tag-inheritance
  10015. (setcdr (car tags-alist)
  10016. (mapcar (lambda (x)
  10017. (setq x (copy-sequence x))
  10018. (org-add-prop-inherited x))
  10019. (cdar tags-alist))))
  10020. (when (and tags org-use-tag-inheritance
  10021. (or (not (eq t org-use-tag-inheritance))
  10022. org-tags-exclude-from-inheritance))
  10023. ;; Selective inheritance, remove uninherited ones.
  10024. (setcdr (car tags-alist)
  10025. (org-remove-uninherited-tags (cdar tags-alist))))
  10026. (when (and
  10027. ;; eval matcher only when the todo condition is OK
  10028. (and (or (not todo-only) (member todo org-todo-keywords-1))
  10029. (if (functionp matcher)
  10030. (let ((case-fold-search t) (org-trust-scanner-tags t))
  10031. (funcall matcher todo tags-list level))
  10032. matcher))
  10033. ;; Call the skipper, but return t if it does not
  10034. ;; skip, so that the `and' form continues evaluating.
  10035. (progn
  10036. (unless (eq action 'sparse-tree) (org-agenda-skip))
  10037. t)
  10038. ;; Check if timestamps are deselecting this entry
  10039. (or (not todo-only)
  10040. (and (member todo org-todo-keywords-1)
  10041. (or (not org-agenda-tags-todo-honor-ignore-options)
  10042. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  10043. ;; select this headline
  10044. (cond
  10045. ((eq action 'sparse-tree)
  10046. (and org-highlight-sparse-tree-matches
  10047. (org-get-heading) (match-end 0)
  10048. (org-highlight-new-match
  10049. (match-beginning 1) (match-end 1)))
  10050. (org-fold-show-context 'tags-tree))
  10051. ((eq action 'agenda)
  10052. (setq txt (org-agenda-format-item
  10053. ""
  10054. (concat
  10055. (if (eq org-tags-match-list-sublevels 'indented)
  10056. (make-string (1- level) ?.) "")
  10057. (org-get-heading))
  10058. (make-string level ?\s)
  10059. category
  10060. tags-list)
  10061. priority (org-get-priority txt))
  10062. (goto-char lspos)
  10063. (setq marker (org-agenda-new-marker))
  10064. (org-add-props txt props
  10065. 'org-marker marker 'org-hd-marker marker 'org-category category
  10066. 'todo-state todo
  10067. 'ts-date ts-date
  10068. 'priority priority
  10069. 'type (concat "tagsmatch" ts-date-type))
  10070. (push txt rtn))
  10071. ((functionp action)
  10072. (setq org-map-continue-from nil)
  10073. (save-excursion
  10074. (setq rtn1 (funcall action))
  10075. (push rtn1 rtn)))
  10076. (t (user-error "Invalid action")))
  10077. ;; if we are to skip sublevels, jump to end of subtree
  10078. (unless org-tags-match-list-sublevels
  10079. (org-end-of-subtree t)
  10080. (backward-char 1))))
  10081. ;; Get the correct position from where to continue
  10082. (if org-map-continue-from
  10083. (goto-char org-map-continue-from)
  10084. (and (= (point) lspos) (end-of-line 1))))))
  10085. (when (and (eq action 'sparse-tree)
  10086. (not org-sparse-tree-open-archived-trees))
  10087. (org-fold-hide-archived-subtrees (point-min) (point-max)))
  10088. (nreverse rtn)))
  10089. (defun org-remove-uninherited-tags (tags)
  10090. "Remove all tags that are not inherited from the list TAGS."
  10091. (cond
  10092. ((eq org-use-tag-inheritance t)
  10093. (if org-tags-exclude-from-inheritance
  10094. (org-delete-all org-tags-exclude-from-inheritance tags)
  10095. tags))
  10096. ((not org-use-tag-inheritance) nil)
  10097. ((stringp org-use-tag-inheritance)
  10098. (delq nil (mapcar
  10099. (lambda (x)
  10100. (if (and (string-match org-use-tag-inheritance x)
  10101. (not (member x org-tags-exclude-from-inheritance)))
  10102. x nil))
  10103. tags)))
  10104. ((listp org-use-tag-inheritance)
  10105. (delq nil (mapcar
  10106. (lambda (x)
  10107. (if (member x org-use-tag-inheritance) x nil))
  10108. tags)))))
  10109. (defun org-match-sparse-tree (&optional todo-only match)
  10110. "Create a sparse tree according to tags string MATCH.
  10111. MATCH is a string with match syntax. It can contain a selection
  10112. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  10113. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  10114. those. See the manual for details.
  10115. If optional argument TODO-ONLY is non-nil, only select lines that
  10116. are also TODO tasks."
  10117. (interactive "P")
  10118. (org-agenda-prepare-buffers (list (current-buffer)))
  10119. (let ((org--matcher-tags-todo-only todo-only))
  10120. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match t))
  10121. org--matcher-tags-todo-only)))
  10122. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  10123. (defvar org-cached-props nil)
  10124. (defun org-cached-entry-get (pom property)
  10125. (if (or (eq t org-use-property-inheritance)
  10126. (and (stringp org-use-property-inheritance)
  10127. (let ((case-fold-search t))
  10128. (string-match-p org-use-property-inheritance property)))
  10129. (and (listp org-use-property-inheritance)
  10130. (member-ignore-case property org-use-property-inheritance)))
  10131. ;; Caching is not possible, check it directly.
  10132. (org-entry-get pom property 'inherit)
  10133. ;; Get all properties, so we can do complicated checks easily.
  10134. (cdr (assoc-string property
  10135. (or org-cached-props
  10136. (setq org-cached-props (org-entry-properties pom)))
  10137. t))))
  10138. (defun org-global-tags-completion-table (&optional files)
  10139. "Return the list of all tags in all agenda buffer/files.
  10140. Optional FILES argument is a list of files which can be used
  10141. instead of the agenda files."
  10142. (save-excursion
  10143. (org-uniquify
  10144. (delq nil
  10145. (apply #'append
  10146. (mapcar
  10147. (lambda (file)
  10148. (set-buffer (find-file-noselect file))
  10149. (org--tag-add-to-alist
  10150. (org-get-buffer-tags)
  10151. (mapcar (lambda (x)
  10152. (and (stringp (car-safe x))
  10153. (list (car-safe x))))
  10154. org-current-tag-alist)))
  10155. (if (car-safe files) files
  10156. (org-agenda-files))))))))
  10157. (defun org-make-tags-matcher (match &optional only-local-tags)
  10158. "Create the TAGS/TODO matcher form for the selection string MATCH.
  10159. Returns a cons of the selection string MATCH and a function
  10160. implementing the matcher.
  10161. The matcher is to be called at an Org entry, with point on the
  10162. headline, and returns non-nil if the entry matches the selection
  10163. string MATCH. It must be called with three arguments: the TODO
  10164. keyword at the entry (or nil if none), the list of all tags at
  10165. the entry including inherited ones and the reduced level of the
  10166. headline. Additionally, the category of the entry, if any, must
  10167. be specified as the text property `org-category' on the headline.
  10168. This function sets the variable `org--matcher-tags-todo-only' to
  10169. a non-nil value if the matcher restricts matching to TODO
  10170. entries, otherwise it is not touched.
  10171. When ONLY-LOCAL-TAGS is non-nil, ignore the global tag completion
  10172. table, only get buffer tags.
  10173. See also `org-scan-tags'."
  10174. (unless match
  10175. ;; Get a new match request, with completion against the global
  10176. ;; tags table and the local tags in current buffer.
  10177. (let ((org-last-tags-completion-table
  10178. (org--tag-add-to-alist
  10179. (org-get-buffer-tags)
  10180. (unless only-local-tags
  10181. (org-global-tags-completion-table)))))
  10182. (setq match
  10183. (completing-read
  10184. "Match: "
  10185. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  10186. (let ((match0 match)
  10187. (re (concat
  10188. "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
  10189. "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
  10190. "\\([<>=]\\{1,2\\}\\)"
  10191. "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
  10192. "\\|" org-tag-re "\\)"))
  10193. (start 0)
  10194. tagsmatch todomatch tagsmatcher todomatcher)
  10195. ;; Expand group tags.
  10196. (setq match (org-tags-expand match))
  10197. ;; Check if there is a TODO part of this match, which would be the
  10198. ;; part after a "/". To make sure that this slash is not part of
  10199. ;; a property value to be matched against, we also check that
  10200. ;; there is no / after that slash. First, find the last slash.
  10201. (let ((s 0))
  10202. (while (string-match "/+" match s)
  10203. (setq start (match-beginning 0))
  10204. (setq s (match-end 0))))
  10205. (if (and (string-match "/+" match start)
  10206. (not (string-match-p "\"" match start)))
  10207. ;; Match contains also a TODO-matching request.
  10208. (progn
  10209. (setq tagsmatch (substring match 0 (match-beginning 0)))
  10210. (setq todomatch (substring match (match-end 0)))
  10211. (when (string-prefix-p "!" todomatch)
  10212. (setq org--matcher-tags-todo-only t)
  10213. (setq todomatch (substring todomatch 1)))
  10214. (when (string-match "\\`\\s-*\\'" todomatch)
  10215. (setq todomatch nil)))
  10216. ;; Only matching tags.
  10217. (setq tagsmatch match)
  10218. (setq todomatch nil))
  10219. ;; Make the tags matcher.
  10220. (when (org-string-nw-p tagsmatch)
  10221. (let ((orlist nil)
  10222. (orterms (org-split-string tagsmatch "|"))
  10223. term)
  10224. (while (setq term (pop orterms))
  10225. (while (and (equal (substring term -1) "\\") orterms)
  10226. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  10227. (while (string-match re term)
  10228. (let* ((rest (substring term (match-end 0)))
  10229. (minus (and (match-end 1)
  10230. (equal (match-string 1 term) "-")))
  10231. (tag (save-match-data
  10232. (replace-regexp-in-string
  10233. "\\\\-" "-" (match-string 2 term))))
  10234. (regexp (eq (string-to-char tag) ?{))
  10235. (levelp (match-end 4))
  10236. (propp (match-end 5))
  10237. (mm
  10238. (cond
  10239. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  10240. (levelp
  10241. `(,(org-op-to-function (match-string 3 term))
  10242. level
  10243. ,(string-to-number (match-string 4 term))))
  10244. (propp
  10245. (let* ((gv (pcase (upcase (match-string 5 term))
  10246. ("CATEGORY"
  10247. '(org-get-category (point)))
  10248. ("TODO" 'todo)
  10249. (p `(org-cached-entry-get nil ,p))))
  10250. (pv (match-string 7 term))
  10251. (regexp (eq (string-to-char pv) ?{))
  10252. (strp (eq (string-to-char pv) ?\"))
  10253. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  10254. (po (org-op-to-function (match-string 6 term)
  10255. (if timep 'time strp))))
  10256. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  10257. (when timep (setq pv (org-matcher-time pv)))
  10258. (cond ((and regexp (eq po '/=))
  10259. `(not (string-match ,pv (or ,gv ""))))
  10260. (regexp `(string-match ,pv (or ,gv "")))
  10261. (strp `(,po (or ,gv "") ,pv))
  10262. (t
  10263. `(,po
  10264. (string-to-number (or ,gv ""))
  10265. ,(string-to-number pv))))))
  10266. (t `(member ,tag tags-list)))))
  10267. (push (if minus `(not ,mm) mm) tagsmatcher)
  10268. (setq term rest)))
  10269. (push `(and ,@tagsmatcher) orlist)
  10270. (setq tagsmatcher nil))
  10271. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  10272. ;; Make the TODO matcher.
  10273. (when (org-string-nw-p todomatch)
  10274. (let ((orlist nil))
  10275. (dolist (term (org-split-string todomatch "|"))
  10276. (while (string-match re term)
  10277. (let* ((minus (and (match-end 1)
  10278. (equal (match-string 1 term) "-")))
  10279. (kwd (match-string 2 term))
  10280. (regexp (eq (string-to-char kwd) ?{))
  10281. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  10282. `(equal todo ,kwd))))
  10283. (push (if minus `(not ,mm) mm) todomatcher))
  10284. (setq term (substring term (match-end 0))))
  10285. (push (if (> (length todomatcher) 1)
  10286. (cons 'and todomatcher)
  10287. (car todomatcher))
  10288. orlist)
  10289. (setq todomatcher nil))
  10290. (setq todomatcher (cons 'or orlist))))
  10291. ;; Return the string and function of the matcher. If no
  10292. ;; tags-specific or todo-specific matcher exists, match
  10293. ;; everything.
  10294. (let ((matcher (if (and tagsmatcher todomatcher)
  10295. `(and ,tagsmatcher ,todomatcher)
  10296. (or tagsmatcher todomatcher t))))
  10297. (when org--matcher-tags-todo-only
  10298. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  10299. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  10300. (defun org--tags-expand-group (group tag-groups expanded)
  10301. "Recursively expand all tags in GROUP, according to TAG-GROUPS.
  10302. TAG-GROUPS is the list of groups used for expansion. EXPANDED is
  10303. an accumulator used in recursive calls."
  10304. (dolist (tag group)
  10305. (unless (member tag expanded)
  10306. (let ((group (assoc tag tag-groups)))
  10307. (push tag expanded)
  10308. (when group
  10309. (setq expanded
  10310. (org--tags-expand-group (cdr group) tag-groups expanded))))))
  10311. expanded)
  10312. (defun org-tags-expand (match &optional single-as-list)
  10313. "Expand group tags in MATCH.
  10314. This replaces every group tag in MATCH with a regexp tag search.
  10315. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  10316. will be replaced like this:
  10317. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10318. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10319. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10320. Replacing by a regexp preserves the structure of the match.
  10321. E.g., this expansion
  10322. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  10323. will match anything tagged with \"Lab\" and \"Home\", or tagged
  10324. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"Home\".
  10325. A group tag in MATCH can contain regular expressions of its own.
  10326. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  10327. will be replaced like this:
  10328. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  10329. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  10330. assumed to be a single group tag, and the function will return
  10331. the list of tags in this group."
  10332. (unless (org-string-nw-p match) (error "Invalid match tag: %S" match))
  10333. (let ((tag-groups
  10334. (or org-tag-groups-alist-for-agenda org-tag-groups-alist)))
  10335. (cond
  10336. (single-as-list (org--tags-expand-group (list match) tag-groups nil))
  10337. (org-group-tags
  10338. (let* ((case-fold-search t)
  10339. (tag-syntax org-mode-syntax-table)
  10340. (group-keys (mapcar #'car tag-groups))
  10341. (key-regexp (concat "\\([+-]?\\)" (regexp-opt group-keys 'words)))
  10342. (return-match match))
  10343. ;; Mark regexp-expressions in the match-expression so that we
  10344. ;; do not replace them later on.
  10345. (let ((s 0))
  10346. (while (string-match "{.+?}" return-match s)
  10347. (setq s (match-end 0))
  10348. (add-text-properties
  10349. (match-beginning 0) (match-end 0) '(regexp t) return-match)))
  10350. ;; @ and _ are allowed as word-components in tags.
  10351. (modify-syntax-entry ?@ "w" tag-syntax)
  10352. (modify-syntax-entry ?_ "w" tag-syntax)
  10353. ;; For each tag token found in MATCH, compute a regexp and it
  10354. (with-syntax-table tag-syntax
  10355. (replace-regexp-in-string
  10356. key-regexp
  10357. (lambda (m)
  10358. (if (get-text-property (match-beginning 2) 'regexp m)
  10359. m ;regexp tag: ignore
  10360. (let* ((operator (match-string 1 m))
  10361. (tag-token (let ((tag (match-string 2 m)))
  10362. (list tag)))
  10363. regexp-tags regular-tags)
  10364. ;; Partition tags between regexp and regular tags.
  10365. ;; Remove curly bracket syntax from regexp tags.
  10366. (dolist (tag (org--tags-expand-group tag-token tag-groups nil))
  10367. (save-match-data
  10368. (if (string-match "{\\(.+?\\)}" tag)
  10369. (push (match-string 1 tag) regexp-tags)
  10370. (push tag regular-tags))))
  10371. ;; Replace tag token by the appropriate regexp.
  10372. ;; Regular tags need to be regexp-quoted, whereas
  10373. ;; regexp-tags are inserted as-is.
  10374. (let ((regular (regexp-opt regular-tags))
  10375. (regexp (mapconcat #'identity regexp-tags "\\|")))
  10376. (concat operator
  10377. (cond
  10378. ((null regular-tags) (format "{%s}" regexp))
  10379. ((null regexp-tags) (format "{\\<%s\\>}" regular))
  10380. (t (format "{\\<%s\\>\\|%s}" regular regexp))))))))
  10381. return-match
  10382. t t))))
  10383. (t match))))
  10384. (defun org-op-to-function (op &optional stringp)
  10385. "Turn an operator into the appropriate function."
  10386. (setq op
  10387. (cond
  10388. ((equal op "<" ) '(< org-string< org-time<))
  10389. ((equal op ">" ) '(> org-string> org-time>))
  10390. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  10391. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  10392. ((member op '("=" "==")) '(= string= org-time=))
  10393. ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
  10394. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  10395. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  10396. (defvar org-tags-overlay (make-overlay 1 1))
  10397. (delete-overlay org-tags-overlay)
  10398. (defun org-add-prop-inherited (s)
  10399. (add-text-properties 0 (length s) '(inherited t) s)
  10400. s)
  10401. (defun org-toggle-tag (tag &optional onoff)
  10402. "Toggle the tag TAG for the current line.
  10403. If ONOFF is `on' or `off', don't toggle but set to this state."
  10404. (save-excursion
  10405. (org-back-to-heading t)
  10406. (let ((current
  10407. ;; Reverse the tags list so any new tag is appended to the
  10408. ;; current list of tags.
  10409. (nreverse (org-get-tags nil t)))
  10410. res)
  10411. (pcase onoff
  10412. (`off (setq current (delete tag current)))
  10413. ((or `on (guard (not (member tag current))))
  10414. (setq res t)
  10415. (cl-pushnew tag current :test #'equal))
  10416. (_ (setq current (delete tag current))))
  10417. (org-set-tags (nreverse current))
  10418. res)))
  10419. (defun org--align-tags-here (to-col)
  10420. "Align tags on the current headline to TO-COL.
  10421. Assume point is on a headline. Preserve point when aligning
  10422. tags."
  10423. (when (org-match-line org-tag-line-re)
  10424. (let* ((tags-start (match-beginning 1))
  10425. (blank-start (save-excursion
  10426. (goto-char tags-start)
  10427. (skip-chars-backward " \t")
  10428. (point)))
  10429. (new (max (if (>= to-col 0) to-col
  10430. (- (abs to-col) (string-width (match-string 1))))
  10431. ;; Introduce at least one space after the heading
  10432. ;; or the stars.
  10433. (save-excursion
  10434. (goto-char blank-start)
  10435. (1+ (current-column)))))
  10436. (current
  10437. (save-excursion (goto-char tags-start) (current-column)))
  10438. (origin (point-marker))
  10439. (column (current-column))
  10440. (in-blank? (and (> origin blank-start) (<= origin tags-start))))
  10441. (when (/= new current)
  10442. (delete-region blank-start tags-start)
  10443. (goto-char blank-start)
  10444. (let ((indent-tabs-mode nil)) (indent-to new))
  10445. ;; Try to move back to original position. If point was in the
  10446. ;; blanks before the tags, ORIGIN marker is of no use because
  10447. ;; it now points to BLANK-START. Use COLUMN instead.
  10448. (if in-blank? (org-move-to-column column) (goto-char origin))))))
  10449. (defun org-set-tags-command (&optional arg)
  10450. "Set the tags for the current visible entry.
  10451. When called with `\\[universal-argument]' prefix argument ARG, \
  10452. realign all tags
  10453. in the current buffer.
  10454. When called with `\\[universal-argument] \\[universal-argument]' prefix argument, \
  10455. unconditionally do not
  10456. offer the fast tag selection interface.
  10457. If a region is active, set tags in the region according to the
  10458. setting of `org-loop-over-headlines-in-active-region'.
  10459. This function is for interactive use only;
  10460. in Lisp code use `org-set-tags' instead."
  10461. (interactive "P")
  10462. (let ((org-use-fast-tag-selection
  10463. (unless (equal '(16) arg) org-use-fast-tag-selection)))
  10464. (cond
  10465. ((equal '(4) arg) (org-align-tags t))
  10466. ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
  10467. (let (org-loop-over-headlines-in-active-region) ; hint: infinite recursion.
  10468. (org-map-entries
  10469. #'org-set-tags-command
  10470. nil
  10471. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  10472. 'region-start-level
  10473. 'region)
  10474. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
  10475. (t
  10476. (save-excursion
  10477. (org-back-to-heading)
  10478. (let* ((all-tags (org-get-tags))
  10479. (local-table (or org-current-tag-alist (org-get-buffer-tags)))
  10480. (table (setq org-last-tags-completion-table
  10481. (append
  10482. ;; Put local tags in front.
  10483. local-table
  10484. (cl-set-difference
  10485. (org--tag-add-to-alist
  10486. (and org-complete-tags-always-offer-all-agenda-tags
  10487. (org-global-tags-completion-table
  10488. (org-agenda-files)))
  10489. local-table)
  10490. local-table))))
  10491. (current-tags
  10492. (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
  10493. all-tags))
  10494. (inherited-tags
  10495. (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
  10496. all-tags))
  10497. (tags
  10498. (replace-regexp-in-string
  10499. ;; Ignore all forbidden characters in tags.
  10500. "[^[:alnum:]_@#%]+" ":"
  10501. (if (or (eq t org-use-fast-tag-selection)
  10502. (and org-use-fast-tag-selection
  10503. (delq nil (mapcar #'cdr table))))
  10504. (org-fast-tag-selection
  10505. current-tags
  10506. inherited-tags
  10507. table
  10508. (and org-fast-tag-selection-include-todo org-todo-key-alist))
  10509. (let ((org-add-colon-after-tag-completion (< 1 (length table)))
  10510. (crm-separator "[ \t]*:[ \t]*"))
  10511. (mapconcat #'identity
  10512. (completing-read-multiple
  10513. "Tags: "
  10514. org-last-tags-completion-table
  10515. nil nil (org-make-tag-string current-tags)
  10516. 'org-tags-history)
  10517. ":"))))))
  10518. (org-set-tags tags)))))
  10519. ;; `save-excursion' may not replace the point at the right
  10520. ;; position.
  10521. (when (and (save-excursion (skip-chars-backward "*") (bolp))
  10522. (looking-at-p " "))
  10523. (forward-char))))
  10524. (defun org-align-tags (&optional all)
  10525. "Align tags in current entry.
  10526. When optional argument ALL is non-nil, align all tags in the
  10527. visible part of the buffer."
  10528. (let ((get-indent-column
  10529. (lambda ()
  10530. (let ((offset (if (bound-and-true-p org-indent-mode)
  10531. (save-excursion
  10532. (org-back-to-heading-or-point-min)
  10533. (length
  10534. (get-text-property
  10535. (line-end-position)
  10536. 'line-prefix)))
  10537. 0)))
  10538. (+ org-tags-column
  10539. (if (> org-tags-column 0) (- offset) offset))))))
  10540. (if (and (not all) (org-at-heading-p))
  10541. (org--align-tags-here (funcall get-indent-column))
  10542. (save-excursion
  10543. (if all
  10544. (progn
  10545. (goto-char (point-min))
  10546. (while (re-search-forward org-tag-line-re nil t)
  10547. (org--align-tags-here (funcall get-indent-column))))
  10548. (org-back-to-heading t)
  10549. (org--align-tags-here (funcall get-indent-column)))))))
  10550. (defun org-set-tags (tags)
  10551. "Set the tags of the current entry to TAGS, replacing current tags.
  10552. TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
  10553. If TAGS is nil or the empty string, all tags are removed.
  10554. This function assumes point is on a headline."
  10555. (org-with-wide-buffer
  10556. (org-fold-core-ignore-modifications
  10557. (let ((tags (pcase tags
  10558. ((pred listp) tags)
  10559. ((pred stringp) (split-string (org-trim tags) ":" t))
  10560. (_ (error "Invalid tag specification: %S" tags))))
  10561. (old-tags (org-get-tags nil t))
  10562. (tags-change? nil))
  10563. (when (functionp org-tags-sort-function)
  10564. (setq tags (sort tags org-tags-sort-function)))
  10565. (setq tags-change? (not (equal tags old-tags)))
  10566. (when tags-change?
  10567. ;; Delete previous tags and any trailing white space.
  10568. (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
  10569. (line-end-position)))
  10570. (skip-chars-backward " \t")
  10571. (delete-region (point) (line-end-position))
  10572. ;; Deleting white spaces may break an otherwise empty headline.
  10573. ;; Re-introduce one space in this case.
  10574. (unless (org-at-heading-p) (insert " "))
  10575. (when tags
  10576. (save-excursion (insert-and-inherit " " (org-make-tag-string tags)))
  10577. ;; When text is being inserted on an invisible region
  10578. ;; boundary, it can be inadvertently sucked into
  10579. ;; invisibility.
  10580. (unless (org-invisible-p (line-beginning-position))
  10581. (org-fold-region (point) (line-end-position) nil 'outline))))
  10582. ;; Align tags, if any.
  10583. (when tags (org-align-tags))
  10584. (when tags-change? (run-hooks 'org-after-tags-change-hook))))))
  10585. (defun org-change-tag-in-region (beg end tag off)
  10586. "Add or remove TAG for each entry in the region.
  10587. This works in the agenda, and also in an Org buffer."
  10588. (interactive
  10589. (list (region-beginning) (region-end)
  10590. (let ((org-last-tags-completion-table
  10591. (if (derived-mode-p 'org-mode)
  10592. (org--tag-add-to-alist
  10593. (org-get-buffer-tags)
  10594. (org-global-tags-completion-table))
  10595. (org-global-tags-completion-table))))
  10596. (completing-read
  10597. "Tag: " org-last-tags-completion-table nil nil nil
  10598. 'org-tags-history))
  10599. (progn
  10600. (message "[s]et or [r]emove? ")
  10601. (equal (read-char-exclusive) ?r))))
  10602. (deactivate-mark)
  10603. (let ((agendap (equal major-mode 'org-agenda-mode))
  10604. l1 l2 m buf pos newhead (cnt 0))
  10605. (goto-char end)
  10606. (setq l2 (1- (org-current-line)))
  10607. (goto-char beg)
  10608. (setq l1 (org-current-line))
  10609. (cl-loop for l from l1 to l2 do
  10610. (org-goto-line l)
  10611. (setq m (get-text-property (point) 'org-hd-marker))
  10612. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  10613. (and agendap m))
  10614. (setq buf (if agendap (marker-buffer m) (current-buffer))
  10615. pos (if agendap m (point)))
  10616. (with-current-buffer buf
  10617. (save-excursion
  10618. (save-restriction
  10619. (goto-char pos)
  10620. (setq cnt (1+ cnt))
  10621. (org-toggle-tag tag (if off 'off 'on))
  10622. (setq newhead (org-get-heading)))))
  10623. (and agendap (org-agenda-change-all-lines newhead m))))
  10624. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  10625. (defun org-tags-completion-function (string _predicate &optional flag)
  10626. "Complete tag STRING.
  10627. FLAG specifies the type of completion operation to perform. This
  10628. function is passed as a collection function to `completing-read',
  10629. which see."
  10630. (let ((completion-ignore-case nil) ;tags are case-sensitive
  10631. (confirm (lambda (x) (stringp (car x))))
  10632. (prefix ""))
  10633. (when (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  10634. (setq prefix (match-string 1 string))
  10635. (setq string (match-string 2 string)))
  10636. (pcase flag
  10637. (`t (all-completions string org-last-tags-completion-table confirm))
  10638. (`lambda (assoc string org-last-tags-completion-table)) ;exact match?
  10639. (`nil
  10640. (pcase (try-completion string org-last-tags-completion-table confirm)
  10641. ((and completion (pred stringp))
  10642. (concat prefix
  10643. completion
  10644. (if (and org-add-colon-after-tag-completion
  10645. (assoc completion org-last-tags-completion-table))
  10646. ":"
  10647. "")))
  10648. (completion completion)))
  10649. (_ nil))))
  10650. (defun org-fast-tag-insert (kwd tags face &optional end)
  10651. "Insert KWD, and the TAGS, the latter with face FACE.
  10652. Also insert END."
  10653. (insert (format "%-12s" (concat kwd ":"))
  10654. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  10655. (or end "")))
  10656. (defun org-fast-tag-show-exit (flag)
  10657. (save-excursion
  10658. (org-goto-line 3)
  10659. (when (re-search-forward "[ \t]+Next change exits" (line-end-position) t)
  10660. (replace-match ""))
  10661. (when flag
  10662. (end-of-line 1)
  10663. (org-move-to-column (- (window-width) 19) t)
  10664. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  10665. (defun org-set-current-tags-overlay (current prefix)
  10666. "Add an overlay to CURRENT tag with PREFIX."
  10667. (let ((s (org-make-tag-string current)))
  10668. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  10669. (org-overlay-display org-tags-overlay (concat prefix s))))
  10670. (defvar org-last-tag-selection-key nil)
  10671. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  10672. "Fast tag selection with single keys.
  10673. CURRENT is the current list of tags in the headline, INHERITED is the
  10674. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  10675. possibly with grouping information. TODO-TABLE is a similar table with
  10676. TODO keywords, should these have keys assigned to them.
  10677. If the keys are nil, a-z are automatically assigned.
  10678. Returns the new tags string, or nil to not change the current settings."
  10679. (let* ((fulltable (append table todo-table))
  10680. (maxlen (if (null fulltable) 0
  10681. (apply #'max
  10682. (mapcar (lambda (x)
  10683. (if (stringp (car x)) (string-width (car x))
  10684. 0))
  10685. fulltable))))
  10686. (buf (current-buffer))
  10687. (expert (eq org-fast-tag-selection-single-key 'expert))
  10688. (tab-tags nil)
  10689. (fwidth (+ maxlen 3 1 3))
  10690. (ncol (/ (- (window-width) 4) fwidth))
  10691. (i-face 'org-done)
  10692. (c-face 'org-todo)
  10693. tg cnt e c char c1 c2 ntable tbl rtn
  10694. ov-start ov-end ov-prefix
  10695. (exit-after-next org-fast-tag-selection-single-key)
  10696. (done-keywords org-done-keywords)
  10697. groups ingroup intaggroup)
  10698. (save-excursion
  10699. (beginning-of-line)
  10700. (if (looking-at org-tag-line-re)
  10701. (setq ov-start (match-beginning 1)
  10702. ov-end (match-end 1)
  10703. ov-prefix "")
  10704. (setq ov-start (1- (line-end-position))
  10705. ov-end (1+ ov-start))
  10706. (skip-chars-forward "^\n\r")
  10707. (setq ov-prefix
  10708. (concat
  10709. (buffer-substring (1- (point)) (point))
  10710. (if (> (current-column) org-tags-column)
  10711. " "
  10712. (make-string (- org-tags-column (current-column)) ?\ ))))))
  10713. (move-overlay org-tags-overlay ov-start ov-end)
  10714. (save-excursion
  10715. (save-window-excursion
  10716. (if expert
  10717. (set-buffer (get-buffer-create " *Org tags*"))
  10718. (delete-other-windows)
  10719. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  10720. (org-switch-to-buffer-other-window " *Org tags*"))
  10721. (erase-buffer)
  10722. (setq-local org-done-keywords done-keywords)
  10723. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  10724. (org-fast-tag-insert "Current" current c-face "\n\n")
  10725. (org-fast-tag-show-exit exit-after-next)
  10726. (org-set-current-tags-overlay current ov-prefix)
  10727. (setq tbl fulltable char ?a cnt 0)
  10728. (while (setq e (pop tbl))
  10729. (cond
  10730. ((eq (car e) :startgroup)
  10731. (push '() groups) (setq ingroup t)
  10732. (unless (zerop cnt)
  10733. (setq cnt 0)
  10734. (insert "\n"))
  10735. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  10736. ((eq (car e) :endgroup)
  10737. (setq ingroup nil cnt 0)
  10738. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  10739. ((eq (car e) :startgrouptag)
  10740. (setq intaggroup t)
  10741. (unless (zerop cnt)
  10742. (setq cnt 0)
  10743. (insert "\n"))
  10744. (insert "[ "))
  10745. ((eq (car e) :endgrouptag)
  10746. (setq intaggroup nil cnt 0)
  10747. (insert "]\n"))
  10748. ((equal e '(:newline))
  10749. (unless (zerop cnt)
  10750. (setq cnt 0)
  10751. (insert "\n")
  10752. (setq e (car tbl))
  10753. (while (equal (car tbl) '(:newline))
  10754. (insert "\n")
  10755. (setq tbl (cdr tbl)))))
  10756. ((equal e '(:grouptags))
  10757. (delete-char -3)
  10758. (insert " : "))
  10759. (t
  10760. (setq tg (copy-sequence (car e)) c2 nil)
  10761. (if (cdr e)
  10762. (setq c (cdr e))
  10763. ;; automatically assign a character.
  10764. (setq c1 (string-to-char
  10765. (downcase (substring
  10766. tg (if (= (string-to-char tg) ?@) 1 0)))))
  10767. (if (or (rassoc c1 ntable) (rassoc c1 table))
  10768. (while (or (rassoc char ntable) (rassoc char table))
  10769. (setq char (1+ char)))
  10770. (setq c2 c1))
  10771. (setq c (or c2
  10772. (if (> char ?~)
  10773. ?\s
  10774. char)))
  10775. ;; Consider characters A-Z after a-z.
  10776. (if (equal char ?z)
  10777. (setq char ?A)))
  10778. (when ingroup (push tg (car groups)))
  10779. (setq tg (org-add-props tg nil 'face
  10780. (cond
  10781. ((not (assoc tg table))
  10782. (org-get-todo-face tg))
  10783. ((member tg current) c-face)
  10784. ((member tg inherited) i-face))))
  10785. (when (equal (caar tbl) :grouptags)
  10786. (org-add-props tg nil 'face 'org-tag-group))
  10787. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  10788. (insert "[" c "] " tg (make-string
  10789. (- fwidth 4 (length tg)) ?\ ))
  10790. (push (cons tg c) ntable)
  10791. (when (= (cl-incf cnt) ncol)
  10792. (unless (memq (caar tbl) '(:endgroup :endgrouptag))
  10793. (insert "\n")
  10794. (when (or ingroup intaggroup) (insert " ")))
  10795. (setq cnt 0)))))
  10796. (setq ntable (nreverse ntable))
  10797. (insert "\n")
  10798. (goto-char (point-min))
  10799. (unless expert (org-fit-window-to-buffer))
  10800. (setq rtn
  10801. (catch 'exit
  10802. (while t
  10803. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  10804. (if (not groups) "no " "")
  10805. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  10806. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  10807. (setq org-last-tag-selection-key c)
  10808. (cond
  10809. ((= c ?\r) (throw 'exit t))
  10810. ((= c ?!)
  10811. (setq groups (not groups))
  10812. (goto-char (point-min))
  10813. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  10814. ((= c ?\C-c)
  10815. (if (not expert)
  10816. (org-fast-tag-show-exit
  10817. (setq exit-after-next (not exit-after-next)))
  10818. (setq expert nil)
  10819. (delete-other-windows)
  10820. (set-window-buffer (split-window-vertically) " *Org tags*")
  10821. (org-switch-to-buffer-other-window " *Org tags*")
  10822. (org-fit-window-to-buffer)))
  10823. ((or (= c ?\C-g)
  10824. (and (= c ?q) (not (rassoc c ntable))))
  10825. (delete-overlay org-tags-overlay)
  10826. (setq quit-flag t))
  10827. ((= c ?\ )
  10828. (setq current nil)
  10829. (when exit-after-next (setq exit-after-next 'now)))
  10830. ((= c ?\t)
  10831. (condition-case nil
  10832. (unless tab-tags
  10833. (setq tab-tags
  10834. (delq nil
  10835. (mapcar (lambda (x)
  10836. (let ((item (car-safe x)))
  10837. (and (stringp item)
  10838. (list item))))
  10839. (org--tag-add-to-alist
  10840. (with-current-buffer buf
  10841. (org-get-buffer-tags))
  10842. table))))))
  10843. (setq tg (completing-read "Tag: " tab-tags))
  10844. (when (string-match "\\S-" tg)
  10845. (cl-pushnew (list tg) tab-tags :test #'equal)
  10846. (if (member tg current)
  10847. (setq current (delete tg current))
  10848. (push tg current)))
  10849. (when exit-after-next (setq exit-after-next 'now)))
  10850. ((setq e (rassoc c todo-table) tg (car e))
  10851. (with-current-buffer buf
  10852. (save-excursion (org-todo tg)))
  10853. (when exit-after-next (setq exit-after-next 'now)))
  10854. ((setq e (rassoc c ntable) tg (car e))
  10855. (if (member tg current)
  10856. (setq current (delete tg current))
  10857. (cl-loop for g in groups do
  10858. (when (member tg g)
  10859. (dolist (x g) (setq current (delete x current)))))
  10860. (push tg current))
  10861. (when exit-after-next (setq exit-after-next 'now))))
  10862. ;; Create a sorted list
  10863. (setq current
  10864. (sort current
  10865. (lambda (a b)
  10866. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  10867. (when (eq exit-after-next 'now) (throw 'exit t))
  10868. (goto-char (point-min))
  10869. (beginning-of-line 2)
  10870. (delete-region (point) (line-end-position))
  10871. (org-fast-tag-insert "Current" current c-face)
  10872. (org-set-current-tags-overlay current ov-prefix)
  10873. (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
  10874. (while (re-search-forward tag-re nil t)
  10875. (let ((tag (match-string 1)))
  10876. (add-text-properties
  10877. (match-beginning 1) (match-end 1)
  10878. (list 'face
  10879. (cond
  10880. ((member tag current) c-face)
  10881. ((member tag inherited) i-face)
  10882. (t 'default)))))))
  10883. (goto-char (point-min)))))
  10884. (delete-overlay org-tags-overlay)
  10885. (if rtn
  10886. (mapconcat 'identity current ":")
  10887. nil)))))
  10888. (defun org-make-tag-string (tags)
  10889. "Return string associated to TAGS.
  10890. TAGS is a list of strings."
  10891. (if (null tags) ""
  10892. (format ":%s:" (mapconcat #'identity tags ":"))))
  10893. (defun org--get-local-tags ()
  10894. "Return list of tags for the current headline.
  10895. Assume point is at the beginning of the headline."
  10896. (let* ((cached (and (org-element--cache-active-p) (org-element-at-point nil 'cached)))
  10897. (cached-tags (org-element-property :tags cached)))
  10898. (if cached
  10899. ;; If we do not explicitly copy the result, reference would
  10900. ;; be returned and cache element might be modified directly.
  10901. (mapcar #'copy-sequence cached-tags)
  10902. ;; Parse tags manually.
  10903. (and (looking-at org-tag-line-re)
  10904. (split-string (match-string-no-properties 2) ":" t)))))
  10905. (defun org-get-tags (&optional pos-or-element local)
  10906. "Get the list of tags specified in the current headline.
  10907. When argument POS-OR-ELEMENT is non-nil, retrieve tags for headline at
  10908. POS.
  10909. According to `org-use-tag-inheritance', tags may be inherited
  10910. from parent headlines, and from the whole document, through
  10911. `org-file-tags'. In this case, the returned list of tags
  10912. contains tags in this order: file tags, tags inherited from
  10913. parent headlines, local tags. If a tag appears multiple times,
  10914. only the most local tag is returned.
  10915. However, when optional argument LOCAL is non-nil, only return
  10916. tags specified at the headline.
  10917. Inherited tags have the `inherited' text property."
  10918. (save-match-data
  10919. (if (and org-trust-scanner-tags
  10920. (or (not pos-or-element) (eq pos-or-element (point)))
  10921. (not local))
  10922. org-scanner-tags
  10923. (org-with-point-at (unless (org-element-type pos-or-element)
  10924. (or pos-or-element (point)))
  10925. (unless (or (org-element-type pos-or-element)
  10926. (org-before-first-heading-p))
  10927. (org-back-to-heading t))
  10928. (let ((ltags (if (org-element-type pos-or-element)
  10929. (org-element-property :tags (org-element-lineage pos-or-element '(headline inlinetask) t))
  10930. (org--get-local-tags)))
  10931. itags)
  10932. (if (or local (not org-use-tag-inheritance)) ltags
  10933. (let ((cached (and (org-element--cache-active-p)
  10934. (if (org-element-type pos-or-element)
  10935. (org-element-lineage pos-or-element '(headline org-data inlinetask) t)
  10936. (org-element-at-point nil 'cached)))))
  10937. (if cached
  10938. (while (setq cached (org-element-property :parent cached))
  10939. (setq itags (nconc (mapcar #'org-add-prop-inherited
  10940. ;; If we do explicitly copy the result, reference would
  10941. ;; be returned and cache element might be modified directly.
  10942. (mapcar #'copy-sequence (org-element-property :tags cached)))
  10943. itags)))
  10944. (while (org-up-heading-safe)
  10945. (setq itags (nconc (mapcar #'org-add-prop-inherited
  10946. (org--get-local-tags))
  10947. itags)))))
  10948. (setq itags (append org-file-tags itags))
  10949. (nreverse
  10950. (delete-dups
  10951. (nreverse (nconc (org-remove-uninherited-tags itags) ltags))))))))))
  10952. (defun org-get-buffer-tags ()
  10953. "Get a table of all tags used in the buffer, for completion."
  10954. (if (org-element--cache-active-p)
  10955. ;; `org-element-cache-map' is about 2x faster compared to regexp
  10956. ;; search.
  10957. (let ((hashed (make-hash-table :test #'equal)))
  10958. (org-element-cache-map
  10959. (lambda (el)
  10960. (dolist (tag (org-element-property :tags el))
  10961. ;; Do not carry over the text properties. They may look
  10962. ;; ugly in the completion.
  10963. (puthash (list (substring-no-properties tag)) t hashed))))
  10964. (dolist (tag org-file-tags) (puthash (list tag) t hashed))
  10965. (hash-table-keys hashed))
  10966. (org-with-point-at 1
  10967. (let (tags)
  10968. (while (re-search-forward org-tag-line-re nil t)
  10969. (setq tags (nconc (split-string (match-string-no-properties 2) ":")
  10970. tags)))
  10971. (mapcar #'list (delete-dups (append org-file-tags tags)))))))
  10972. ;;;; The mapping API
  10973. (defvar org-agenda-skip-comment-trees)
  10974. (defvar org-agenda-skip-function)
  10975. (defun org-map-entries (func &optional match scope &rest skip)
  10976. "Call FUNC at each headline selected by MATCH in SCOPE.
  10977. FUNC is a function or a Lisp form. The function will be called without
  10978. arguments, with the cursor positioned at the beginning of the headline.
  10979. The return values of all calls to the function will be collected and
  10980. returned as a list.
  10981. The call to FUNC will be wrapped into a `save-excursion' form, so FUNC
  10982. does not need to preserve point. After evaluation, the cursor will be
  10983. moved to the end of the line (presumably of the headline of the
  10984. processed entry) and search continues from there. Under some
  10985. circumstances, this may not produce the wanted results. For example,
  10986. if you have removed (e.g. archived) the current (sub)tree it could
  10987. mean that the next entry will be skipped entirely. In such cases, you
  10988. can specify the position from where search should continue by making
  10989. FUNC set the variable `org-map-continue-from' to the desired buffer
  10990. position.
  10991. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  10992. Only headlines that are matched by this query will be considered during
  10993. the iteration. When MATCH is nil or t, all headlines will be
  10994. visited by the iteration.
  10995. SCOPE determines the scope of this command. It can be any of:
  10996. nil The current buffer, respecting the restriction if any
  10997. tree The subtree started with the entry at point
  10998. region The entries within the active region, if any
  10999. region-start-level
  11000. The entries within the active region, but only those at
  11001. the same level than the first one.
  11002. file The current buffer, without restriction
  11003. file-with-archives
  11004. The current buffer, and any archives associated with it
  11005. agenda All agenda files
  11006. agenda-with-archives
  11007. All agenda files with any archive files associated with them
  11008. \(file1 file2 ...)
  11009. If this is a list, all files in the list will be scanned
  11010. The remaining args are treated as settings for the skipping facilities of
  11011. the scanner. The following items can be given here:
  11012. archive skip trees with the archive tag
  11013. comment skip trees with the COMMENT keyword
  11014. function or Emacs Lisp form:
  11015. will be used as value for `org-agenda-skip-function', so
  11016. whenever the function returns a position, FUNC will not be
  11017. called for that entry and search will continue from the
  11018. position returned
  11019. If your function needs to retrieve the tags including inherited tags
  11020. at the *current* entry, you can use the value of the variable
  11021. `org-scanner-tags' which will be much faster than getting the value
  11022. with `org-get-tags'. If your function gets properties with
  11023. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  11024. to t around the call to `org-entry-properties' to get the same speedup.
  11025. Note that if your function moves around to retrieve tags and properties at
  11026. a *different* entry, you cannot use these techniques."
  11027. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  11028. (not (org-region-active-p)))
  11029. (let* ((org-agenda-archives-mode nil) ; just to make sure
  11030. (org-agenda-skip-archived-trees (memq 'archive skip))
  11031. (org-agenda-skip-comment-trees (memq 'comment skip))
  11032. (org-agenda-skip-function
  11033. (car (org-delete-all '(comment archive) skip)))
  11034. (org-tags-match-list-sublevels t)
  11035. (start-level (eq scope 'region-start-level))
  11036. matcher res
  11037. org-todo-keywords-for-agenda
  11038. org-done-keywords-for-agenda
  11039. org-todo-keyword-alist-for-agenda
  11040. org-tag-alist-for-agenda
  11041. org--matcher-tags-todo-only)
  11042. (cond
  11043. ((eq match t) (setq matcher t))
  11044. ((eq match nil) (setq matcher t))
  11045. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  11046. (save-excursion
  11047. (save-restriction
  11048. (cond ((eq scope 'tree)
  11049. (org-back-to-heading t)
  11050. (org-narrow-to-subtree)
  11051. (setq scope nil))
  11052. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  11053. (org-region-active-p))
  11054. ;; If needed, set start-level to a string like "2"
  11055. (when start-level
  11056. (save-excursion
  11057. (goto-char (region-beginning))
  11058. (unless (org-at-heading-p) (outline-next-heading))
  11059. (setq start-level (org-current-level))))
  11060. (narrow-to-region (region-beginning)
  11061. (save-excursion
  11062. (goto-char (region-end))
  11063. (unless (and (bolp) (org-at-heading-p))
  11064. (outline-next-heading))
  11065. (point)))
  11066. (setq scope nil)))
  11067. (if (not scope)
  11068. (progn
  11069. ;; Agenda expects a file buffer. Skip over refreshing
  11070. ;; agenda cache for non-file buffers.
  11071. (when buffer-file-name
  11072. (org-agenda-prepare-buffers
  11073. (and buffer-file-name (list buffer-file-name))))
  11074. (setq res
  11075. (org-scan-tags
  11076. func matcher org--matcher-tags-todo-only start-level)))
  11077. ;; Get the right scope
  11078. (cond
  11079. ((and scope (listp scope) (symbolp (car scope)))
  11080. (setq scope (eval scope t)))
  11081. ((eq scope 'agenda)
  11082. (setq scope (org-agenda-files t)))
  11083. ((eq scope 'agenda-with-archives)
  11084. (setq scope (org-agenda-files t))
  11085. (setq scope (org-add-archive-files scope)))
  11086. ((eq scope 'file)
  11087. (setq scope (and buffer-file-name (list buffer-file-name))))
  11088. ((eq scope 'file-with-archives)
  11089. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  11090. (org-agenda-prepare-buffers scope)
  11091. (dolist (file scope)
  11092. (with-current-buffer (org-find-base-buffer-visiting file)
  11093. (org-with-wide-buffer
  11094. (goto-char (point-min))
  11095. (setq res
  11096. (append
  11097. res
  11098. (org-scan-tags
  11099. func matcher org--matcher-tags-todo-only)))))))))
  11100. res)))
  11101. ;;; Properties API
  11102. (defconst org-special-properties
  11103. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  11104. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  11105. "The special properties valid in Org mode.
  11106. These are properties that are not defined in the property drawer,
  11107. but in some other way.")
  11108. (defconst org-default-properties
  11109. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  11110. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  11111. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  11112. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  11113. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  11114. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  11115. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS"
  11116. "ORG-IMAGE-ACTUAL-WIDTH")
  11117. "Some properties that are used by Org mode for various purposes.
  11118. Being in this list makes sure that they are offered for completion.")
  11119. (defun org--valid-property-p (property)
  11120. "Non-nil when string PROPERTY is a valid property name."
  11121. (not
  11122. (or (equal property "")
  11123. (string-match-p "\\s-" property))))
  11124. (defun org--update-property-plist (key val props)
  11125. "Associate KEY to VAL in alist PROPS.
  11126. Modifications are made by side-effect. Return new alist."
  11127. (let* ((appending (string= (substring key -1) "+"))
  11128. (key (if appending (substring key 0 -1) key))
  11129. (old (assoc-string key props t)))
  11130. (if (not old) (cons (cons key val) props)
  11131. (setcdr old (if appending (concat (cdr old) " " val) val))
  11132. props)))
  11133. (defun org-get-property-block (&optional beg force)
  11134. "Return the (beg . end) range of the body of the property drawer.
  11135. BEG is the beginning of the current subtree or the beginning of
  11136. the document if before the first headline. If it is not given,
  11137. it will be found. If the drawer does not exist, create it if
  11138. FORCE is non-nil, or return nil."
  11139. (org-with-wide-buffer
  11140. (let ((beg (cond (beg (goto-char beg))
  11141. ((or (not (featurep 'org-inlinetask))
  11142. (org-inlinetask-in-task-p))
  11143. (org-back-to-heading-or-point-min t) (point))
  11144. (t (org-with-limited-levels
  11145. (org-back-to-heading-or-point-min t))
  11146. (point)))))
  11147. ;; Move point to its position according to its positional rules.
  11148. (cond ((org-before-first-heading-p)
  11149. (while (and (org-at-comment-p) (bolp)) (forward-line)))
  11150. (t (forward-line)
  11151. (when (looking-at-p org-planning-line-re) (forward-line))))
  11152. (cond ((looking-at org-property-drawer-re)
  11153. (forward-line)
  11154. (cons (point) (progn (goto-char (match-end 0))
  11155. (line-beginning-position))))
  11156. (force
  11157. (goto-char beg)
  11158. (org-insert-property-drawer)
  11159. (let ((pos (save-excursion (re-search-forward org-property-drawer-re)
  11160. (line-beginning-position))))
  11161. (cons pos pos)))))))
  11162. (defun org-at-property-drawer-p ()
  11163. "Non-nil when point is at the first line of a property drawer."
  11164. (org-with-wide-buffer
  11165. (beginning-of-line)
  11166. (and (looking-at org-property-drawer-re)
  11167. (or (bobp)
  11168. (progn
  11169. (forward-line -1)
  11170. (cond ((org-at-heading-p))
  11171. ((looking-at org-planning-line-re)
  11172. (forward-line -1)
  11173. (org-at-heading-p))
  11174. ((looking-at org-comment-regexp)
  11175. (forward-line -1)
  11176. (while (and (not (bobp)) (looking-at org-comment-regexp))
  11177. (forward-line -1))
  11178. (looking-at org-comment-regexp))
  11179. (t nil)))))))
  11180. (defun org-at-property-p ()
  11181. "Non-nil when point is inside a property drawer.
  11182. See `org-property-re' for match data, if applicable."
  11183. (save-excursion
  11184. (beginning-of-line)
  11185. (and (looking-at org-property-re)
  11186. (let ((property-drawer (save-match-data (org-get-property-block))))
  11187. (and property-drawer
  11188. (>= (point) (car property-drawer))
  11189. (< (point) (cdr property-drawer)))))))
  11190. (defun org-property-action ()
  11191. "Do an action on properties."
  11192. (interactive)
  11193. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  11194. (let ((c (read-char-exclusive)))
  11195. (cl-case c
  11196. (?s (call-interactively #'org-set-property))
  11197. (?d (call-interactively #'org-delete-property))
  11198. (?D (call-interactively #'org-delete-property-globally))
  11199. (?c (call-interactively #'org-compute-property-at-point))
  11200. (otherwise (user-error "No such property action %c" c)))))
  11201. (defun org-inc-effort ()
  11202. "Increment the value of the effort property in the current entry."
  11203. (interactive)
  11204. (org-set-effort t))
  11205. (defvar org-clock-effort) ; Defined in org-clock.el.
  11206. (defvar org-clock-current-task) ; Defined in org-clock.el.
  11207. (defun org-set-effort (&optional increment value)
  11208. "Set the effort property of the current entry.
  11209. If INCREMENT is non-nil, set the property to the next allowed
  11210. value. Otherwise, if optional argument VALUE is provided, use
  11211. it. Eventually, prompt for the new value if none of the previous
  11212. variables is set."
  11213. (interactive "P")
  11214. (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
  11215. (current (org-entry-get nil org-effort-property))
  11216. (value
  11217. (cond
  11218. (increment
  11219. (unless allowed (user-error "Allowed effort values are not set"))
  11220. (or (cl-caadr (member (list current) allowed))
  11221. (user-error "Unknown value %S among allowed values" current)))
  11222. (value
  11223. (if (stringp value) value
  11224. (error "Invalid effort value: %S" value)))
  11225. (t
  11226. (let ((must-match
  11227. (and allowed
  11228. (not (get-text-property 0 'org-unrestricted
  11229. (caar allowed))))))
  11230. (completing-read "Effort: " allowed nil must-match))))))
  11231. ;; Test whether the value can be interpreted as a duration before
  11232. ;; inserting it in the buffer:
  11233. (org-duration-to-minutes value)
  11234. ;; Maybe update the effort value:
  11235. (unless (equal current value)
  11236. (org-entry-put nil org-effort-property value))
  11237. (unless (org-element--cache-active-p)
  11238. (org-refresh-property '((effort . identity)
  11239. (effort-minutes . org-duration-to-minutes))
  11240. value))
  11241. (when (equal (org-get-heading t t t t)
  11242. (bound-and-true-p org-clock-current-task))
  11243. (setq org-clock-effort value)
  11244. (org-clock-update-mode-line))
  11245. (message "%s is now %s" org-effort-property value)))
  11246. (defun org-entry-properties (&optional pom which)
  11247. "Get all properties of the current entry.
  11248. When POM is a buffer position, get all properties from the entry
  11249. there instead.
  11250. This includes the TODO keyword, the tags, time strings for
  11251. deadline, scheduled, and clocking, and any additional properties
  11252. defined in the entry.
  11253. If WHICH is nil or `all', get all properties. If WHICH is
  11254. `special' or `standard', only get that subclass. If WHICH is
  11255. a string, only get that property.
  11256. Return value is an alist. Keys are properties, as upcased
  11257. strings."
  11258. (org-with-point-at pom
  11259. (when (and (derived-mode-p 'org-mode)
  11260. (org-back-to-heading-or-point-min t))
  11261. (catch 'exit
  11262. (let* ((beg (point))
  11263. (specific (and (stringp which) (upcase which)))
  11264. (which (cond ((not specific) which)
  11265. ((member specific org-special-properties) 'special)
  11266. (t 'standard)))
  11267. props)
  11268. ;; Get the special properties, like TODO and TAGS.
  11269. (when (memq which '(nil all special))
  11270. (when (or (not specific) (string= specific "CLOCKSUM"))
  11271. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  11272. (when clocksum
  11273. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  11274. props)))
  11275. (when specific (throw 'exit props)))
  11276. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  11277. (let ((clocksumt (get-text-property (point)
  11278. :org-clock-minutes-today)))
  11279. (when clocksumt
  11280. (push (cons "CLOCKSUM_T"
  11281. (org-duration-from-minutes clocksumt))
  11282. props)))
  11283. (when specific (throw 'exit props)))
  11284. (when (or (not specific) (string= specific "ITEM"))
  11285. (let ((case-fold-search nil))
  11286. (when (looking-at org-complex-heading-regexp)
  11287. (push (cons "ITEM"
  11288. (let ((title (match-string-no-properties 4)))
  11289. (if (org-string-nw-p title)
  11290. (org-remove-tabs title)
  11291. "")))
  11292. props)))
  11293. (when specific (throw 'exit props)))
  11294. (when (or (not specific) (string= specific "TODO"))
  11295. (let ((case-fold-search nil))
  11296. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  11297. (push (cons "TODO" (match-string-no-properties 2)) props)))
  11298. (when specific (throw 'exit props)))
  11299. (when (or (not specific) (string= specific "PRIORITY"))
  11300. (push (cons "PRIORITY"
  11301. (if (looking-at org-priority-regexp)
  11302. (match-string-no-properties 2)
  11303. (char-to-string org-priority-default)))
  11304. props)
  11305. (when specific (throw 'exit props)))
  11306. (when (or (not specific) (string= specific "FILE"))
  11307. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  11308. props)
  11309. (when specific (throw 'exit props)))
  11310. (when (or (not specific) (string= specific "TAGS"))
  11311. (let ((tags (org-get-tags nil t)))
  11312. (when tags
  11313. (push (cons "TAGS" (org-make-tag-string tags))
  11314. props)))
  11315. (when specific (throw 'exit props)))
  11316. (when (or (not specific) (string= specific "ALLTAGS"))
  11317. (let ((tags (org-get-tags)))
  11318. (when tags
  11319. (push (cons "ALLTAGS" (org-make-tag-string tags))
  11320. props)))
  11321. (when specific (throw 'exit props)))
  11322. (when (or (not specific) (string= specific "BLOCKED"))
  11323. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  11324. (when specific (throw 'exit props)))
  11325. (when (or (not specific)
  11326. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  11327. (forward-line)
  11328. (when (looking-at-p org-planning-line-re)
  11329. (end-of-line)
  11330. (let ((bol (line-beginning-position))
  11331. ;; Backward compatibility: time keywords used to
  11332. ;; be configurable (before 8.3). Make sure we
  11333. ;; get the correct keyword.
  11334. (key-assoc `(("CLOSED" . ,org-closed-string)
  11335. ("DEADLINE" . ,org-deadline-string)
  11336. ("SCHEDULED" . ,org-scheduled-string))))
  11337. (dolist (pair (if specific (list (assoc specific key-assoc))
  11338. key-assoc))
  11339. (save-excursion
  11340. (when (search-backward (cdr pair) bol t)
  11341. (goto-char (match-end 0))
  11342. (skip-chars-forward " \t")
  11343. (and (looking-at org-ts-regexp-both)
  11344. (push (cons (car pair)
  11345. (match-string-no-properties 0))
  11346. props)))))))
  11347. (when specific (throw 'exit props)))
  11348. (when (or (not specific)
  11349. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  11350. (let ((find-ts
  11351. (lambda (end ts)
  11352. ;; Fix next time-stamp before END. TS is the
  11353. ;; list of time-stamps found so far.
  11354. (let ((ts ts)
  11355. (regexp (cond
  11356. ((string= specific "TIMESTAMP")
  11357. org-ts-regexp)
  11358. ((string= specific "TIMESTAMP_IA")
  11359. org-ts-regexp-inactive)
  11360. ((assoc "TIMESTAMP_IA" ts)
  11361. org-ts-regexp)
  11362. ((assoc "TIMESTAMP" ts)
  11363. org-ts-regexp-inactive)
  11364. (t org-ts-regexp-both))))
  11365. (catch 'next
  11366. (while (re-search-forward regexp end t)
  11367. (backward-char)
  11368. (let ((object (org-element-context)))
  11369. ;; Accept to match timestamps in node
  11370. ;; properties, too.
  11371. (when (memq (org-element-type object)
  11372. '(node-property timestamp))
  11373. (let ((type
  11374. (org-element-property :type object)))
  11375. (cond
  11376. ((and (memq type '(active active-range))
  11377. (not (equal specific "TIMESTAMP_IA")))
  11378. (unless (assoc "TIMESTAMP" ts)
  11379. (push (cons "TIMESTAMP"
  11380. (org-element-property
  11381. :raw-value object))
  11382. ts)
  11383. (when specific (throw 'exit ts))))
  11384. ((and (memq type '(inactive inactive-range))
  11385. (not (string= specific "TIMESTAMP")))
  11386. (unless (assoc "TIMESTAMP_IA" ts)
  11387. (push (cons "TIMESTAMP_IA"
  11388. (org-element-property
  11389. :raw-value object))
  11390. ts)
  11391. (when specific (throw 'exit ts))))))
  11392. ;; Both timestamp types are found,
  11393. ;; move to next part.
  11394. (when (= (length ts) 2) (throw 'next ts)))))
  11395. ts)))))
  11396. (goto-char beg)
  11397. ;; First look for timestamps within headline.
  11398. (let ((ts (funcall find-ts (line-end-position) nil)))
  11399. (if (= (length ts) 2) (setq props (nconc ts props))
  11400. ;; Then find timestamps in the section, skipping
  11401. ;; planning line.
  11402. (let ((end (save-excursion (outline-next-heading))))
  11403. (forward-line)
  11404. (when (looking-at-p org-planning-line-re) (forward-line))
  11405. (setq props (nconc (funcall find-ts end ts) props))))))))
  11406. ;; Get the standard properties, like :PROP:.
  11407. (when (memq which '(nil all standard))
  11408. ;; If we are looking after a specific property, delegate
  11409. ;; to `org-entry-get', which is faster. However, make an
  11410. ;; exception for "CATEGORY", since it can be also set
  11411. ;; through keywords (i.e. #+CATEGORY).
  11412. (if (and specific (not (equal specific "CATEGORY")))
  11413. (let ((value (org-entry-get beg specific nil t)))
  11414. (throw 'exit (and value (list (cons specific value)))))
  11415. (let ((range (org-get-property-block beg)))
  11416. (when range
  11417. (let ((end (cdr range)) seen-base)
  11418. (goto-char (car range))
  11419. ;; Unlike to `org--update-property-plist', we
  11420. ;; handle the case where base values is found
  11421. ;; after its extension. We also forbid standard
  11422. ;; properties to be named as special properties.
  11423. (while (re-search-forward org-property-re end t)
  11424. (let* ((key (upcase (match-string-no-properties 2)))
  11425. (extendp (string-match-p "\\+\\'" key))
  11426. (key-base (if extendp (substring key 0 -1) key))
  11427. (value (match-string-no-properties 3)))
  11428. (cond
  11429. ((member-ignore-case key-base org-special-properties))
  11430. (extendp
  11431. (setq props
  11432. (org--update-property-plist key value props)))
  11433. ((member key seen-base))
  11434. (t (push key seen-base)
  11435. (let ((p (assoc-string key props t)))
  11436. (if p (setcdr p (concat value " " (cdr p)))
  11437. (push (cons key value) props))))))))))))
  11438. (unless (assoc "CATEGORY" props)
  11439. (push (cons "CATEGORY" (org-get-category beg)) props)
  11440. (when (string= specific "CATEGORY") (throw 'exit props)))
  11441. ;; Return value.
  11442. props)))))
  11443. (defun org--property-local-values (property literal-nil &optional element)
  11444. "Return value for PROPERTY in current entry or ELEMENT.
  11445. Value is a list whose car is the base value for PROPERTY and cdr
  11446. a list of accumulated values. Return nil if neither is found in
  11447. the entry. Also return nil when PROPERTY is set to \"nil\",
  11448. unless LITERAL-NIL is non-nil."
  11449. (let ((element (or element
  11450. (and (org-element--cache-active-p)
  11451. (org-element-at-point nil 'cached)))))
  11452. (if element
  11453. (let* ((element (org-element-lineage element '(headline org-data inlinetask) 'with-self))
  11454. (base-value (org-element-property (intern (concat ":" (upcase property))) element))
  11455. (base-value (if literal-nil base-value (org-not-nil base-value)))
  11456. (extra-value (org-element-property (intern (concat ":" (upcase property) "+")) element))
  11457. (extra-value (if (listp extra-value) extra-value (list extra-value)))
  11458. (value (cons base-value extra-value)))
  11459. (and (not (equal value '(nil))) value))
  11460. (let ((range (org-get-property-block)))
  11461. (when range
  11462. (goto-char (car range))
  11463. (let* ((case-fold-search t)
  11464. (end (cdr range))
  11465. (value
  11466. ;; Base value.
  11467. (save-excursion
  11468. (let ((v (and (re-search-forward
  11469. (org-re-property property nil t) end t)
  11470. (match-string-no-properties 3))))
  11471. (list (if literal-nil v (org-not-nil v)))))))
  11472. ;; Find additional values.
  11473. (let* ((property+ (org-re-property (concat property "+") nil t)))
  11474. (while (re-search-forward property+ end t)
  11475. (push (match-string-no-properties 3) value)))
  11476. ;; Return final values.
  11477. (and (not (equal value '(nil))) (nreverse value))))))))
  11478. (defun org--property-global-or-keyword-value (property literal-nil)
  11479. "Return value for PROPERTY as defined by global properties or by keyword.
  11480. Return value is a string. Return nil if property is not set
  11481. globally or by keyword. Also return nil when PROPERTY is set to
  11482. \"nil\", unless LITERAL-NIL is non-nil."
  11483. (let ((global
  11484. (cdr (or (assoc-string property org-keyword-properties t)
  11485. (assoc-string property org-global-properties t)
  11486. (assoc-string property org-global-properties-fixed t)))))
  11487. (if literal-nil global (org-not-nil global))))
  11488. (defun org-entry-get (pom property &optional inherit literal-nil)
  11489. "Get value of PROPERTY for entry or content at point-or-marker POM.
  11490. If INHERIT is non-nil and the entry does not have the property,
  11491. then also check higher levels of the hierarchy. If INHERIT is
  11492. the symbol `selective', use inheritance only if the setting in
  11493. `org-use-property-inheritance' selects PROPERTY for inheritance.
  11494. If the property is present but empty, the return value is the
  11495. empty string. If the property is not present at all, nil is
  11496. returned. In any other case, return the value as a string.
  11497. Search is case-insensitive.
  11498. If LITERAL-NIL is set, return the string value \"nil\" as
  11499. a string, do not interpret it as the list atom nil. This is used
  11500. for inheritance when a \"nil\" value can supersede a non-nil
  11501. value higher up the hierarchy."
  11502. (org-with-point-at pom
  11503. (cond
  11504. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  11505. ;; We need a special property. Use `org-entry-properties' to
  11506. ;; retrieve it, but specify the wanted property.
  11507. (cdr (assoc-string property (org-entry-properties nil property))))
  11508. ((and inherit
  11509. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  11510. (org-entry-get-with-inheritance property literal-nil))
  11511. (t
  11512. (let* ((local (org--property-local-values property literal-nil))
  11513. (value (and local (mapconcat #'identity
  11514. (delq nil local)
  11515. (org--property-get-separator property)))))
  11516. (if literal-nil value (org-not-nil value)))))))
  11517. (defun org-property-or-variable-value (var &optional inherit)
  11518. "Check if there is a property fixing the value of VAR.
  11519. If yes, return this value. If not, return the current value of the variable."
  11520. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  11521. (if (and prop (stringp prop) (string-match "\\S-" prop))
  11522. (read prop)
  11523. (symbol-value var))))
  11524. (defun org-entry-delete (pom property)
  11525. "Delete PROPERTY from entry at point-or-marker POM.
  11526. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  11527. non-nil when a property was removed."
  11528. (org-with-point-at pom
  11529. (pcase (org-get-property-block)
  11530. (`(,begin . ,origin)
  11531. (let* ((end (copy-marker origin))
  11532. (re (org-re-property
  11533. (concat (regexp-quote property) "\\+?") t t)))
  11534. (goto-char begin)
  11535. (while (re-search-forward re end t)
  11536. (delete-region (match-beginning 0) (line-beginning-position 2)))
  11537. ;; If drawer is empty, remove it altogether.
  11538. (when (= begin end)
  11539. (delete-region (line-beginning-position 0)
  11540. (line-beginning-position 2)))
  11541. ;; Return non-nil if some property was removed.
  11542. (prog1 (/= end origin) (set-marker end nil))))
  11543. (_ nil))))
  11544. ;; Multi-values properties are properties that contain multiple values
  11545. ;; These values are assumed to be single words, separated by whitespace.
  11546. (defun org-entry-add-to-multivalued-property (pom property value)
  11547. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  11548. (let* ((old (org-entry-get pom property))
  11549. (values (and old (split-string old))))
  11550. (setq value (org-entry-protect-space value))
  11551. (unless (member value values)
  11552. (setq values (append values (list value)))
  11553. (org-entry-put pom property (mapconcat #'identity values " ")))))
  11554. (defun org-entry-remove-from-multivalued-property (pom property value)
  11555. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  11556. (let* ((old (org-entry-get pom property))
  11557. (values (and old (split-string old))))
  11558. (setq value (org-entry-protect-space value))
  11559. (when (member value values)
  11560. (setq values (delete value values))
  11561. (org-entry-put pom property (mapconcat #'identity values " ")))))
  11562. (defun org-entry-member-in-multivalued-property (pom property value)
  11563. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  11564. (let* ((old (org-entry-get pom property))
  11565. (values (and old (split-string old))))
  11566. (setq value (org-entry-protect-space value))
  11567. (member value values)))
  11568. (defun org-entry-get-multivalued-property (pom property)
  11569. "Return a list of values in a multivalued property."
  11570. (let* ((value (org-entry-get pom property))
  11571. (values (and value (split-string value))))
  11572. (mapcar #'org-entry-restore-space values)))
  11573. (defun org-entry-put-multivalued-property (pom property &rest values)
  11574. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  11575. VALUES should be a list of strings. Spaces will be protected."
  11576. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  11577. (let* ((value (org-entry-get pom property))
  11578. (values (and value (split-string value))))
  11579. (mapcar #'org-entry-restore-space values)))
  11580. (defun org-entry-protect-space (s)
  11581. "Protect spaces and newline in string S."
  11582. (while (string-match " " s)
  11583. (setq s (replace-match "%20" t t s)))
  11584. (while (string-match "\n" s)
  11585. (setq s (replace-match "%0A" t t s)))
  11586. s)
  11587. (defun org-entry-restore-space (s)
  11588. "Restore spaces and newline in string S."
  11589. (while (string-match "%20" s)
  11590. (setq s (replace-match " " t t s)))
  11591. (while (string-match "%0A" s)
  11592. (setq s (replace-match "\n" t t s)))
  11593. s)
  11594. (defvar org-entry-property-inherited-from (make-marker)
  11595. "Marker pointing to the entry from where a property was inherited.
  11596. Each call to `org-entry-get-with-inheritance' will set this marker to the
  11597. location of the entry where the inheritance search matched. If there was
  11598. no match, the marker will point nowhere.
  11599. Note that also `org-entry-get' calls this function, if the INHERIT flag
  11600. is set.")
  11601. (defun org-entry-get-with-inheritance (property &optional literal-nil element)
  11602. "Get PROPERTY of entry or content at point, search higher levels if needed.
  11603. The search will stop at the first ancestor which has the property defined.
  11604. If the value found is \"nil\", return nil to show that the property
  11605. should be considered as undefined (this is the meaning of nil here).
  11606. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  11607. (move-marker org-entry-property-inherited-from nil)
  11608. (org-with-wide-buffer
  11609. (let (value at-bob-no-heading)
  11610. (catch 'exit
  11611. (let ((element (or element
  11612. (and (org-element--cache-active-p)
  11613. (org-element-at-point nil 'cached))))
  11614. (separator (org--property-get-separator property)))
  11615. (if element
  11616. (let ((element (org-element-lineage element '(headline org-data inlinetask) 'with-self)))
  11617. (while t
  11618. (let* ((v (org--property-local-values property literal-nil element))
  11619. (v (if (listp v) v (list v))))
  11620. (when v
  11621. (setq value
  11622. (concat (mapconcat #'identity (delq nil v) separator)
  11623. (and value separator)
  11624. value)))
  11625. (cond
  11626. ((car v)
  11627. (move-marker org-entry-property-inherited-from (org-element-property :begin element))
  11628. (throw 'exit nil))
  11629. ((org-element-property :parent element)
  11630. (setq element (org-element-property :parent element)))
  11631. (t
  11632. (let ((global (org--property-global-or-keyword-value property literal-nil)))
  11633. (cond ((not global))
  11634. (value (setq value (concat global separator value)))
  11635. (t (setq value global))))
  11636. (throw 'exit nil))))))
  11637. (while t
  11638. (let ((v (org--property-local-values property literal-nil)))
  11639. (when v
  11640. (setq value
  11641. (concat (mapconcat #'identity (delq nil v) separator)
  11642. (and value separator)
  11643. value)))
  11644. (cond
  11645. ((car v)
  11646. (org-back-to-heading-or-point-min t)
  11647. (move-marker org-entry-property-inherited-from (point))
  11648. (throw 'exit nil))
  11649. ((or (org-up-heading-safe)
  11650. (and (not (bobp))
  11651. (goto-char (point-min))
  11652. nil)
  11653. ;; `org-up-heading-safe' returned nil. We are at low
  11654. ;; level heading or bob. If there is headline
  11655. ;; there, do not try to fetch its properties.
  11656. (and (bobp)
  11657. (not at-bob-no-heading)
  11658. (not (org-at-heading-p))
  11659. (setq at-bob-no-heading t))))
  11660. (t
  11661. (let ((global (org--property-global-or-keyword-value property literal-nil)))
  11662. (cond ((not global))
  11663. (value (setq value (concat global separator value)))
  11664. (t (setq value global))))
  11665. (throw 'exit nil))))))))
  11666. (if literal-nil value (org-not-nil value)))))
  11667. (defvar org-property-changed-functions nil
  11668. "Hook called when the value of a property has changed.
  11669. Each hook function should accept two arguments, the name of the property
  11670. and the new value.")
  11671. (defun org-entry-put (pom property value)
  11672. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  11673. If the value is nil, it is converted to the empty string. If it
  11674. is not a string, an error is raised. Also raise an error on
  11675. invalid property names.
  11676. PROPERTY can be any regular property (see
  11677. `org-special-properties'). It can also be \"TODO\",
  11678. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  11679. For the last two properties, VALUE may have any of the special
  11680. values \"earlier\" and \"later\". The function then increases or
  11681. decreases scheduled or deadline date by one day."
  11682. (cond ((null value) (setq value ""))
  11683. ((not (stringp value)) (error "Properties values should be strings"))
  11684. ((not (org--valid-property-p property))
  11685. (user-error "Invalid property name: \"%s\"" property)))
  11686. (org-no-read-only
  11687. (org-with-point-at pom
  11688. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  11689. (org-back-to-heading-or-point-min t)
  11690. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  11691. (let ((beg (point)))
  11692. (cond
  11693. ((equal property "TODO")
  11694. (cond ((not (org-string-nw-p value)) (setq value 'none))
  11695. ((not (member value org-todo-keywords-1))
  11696. (user-error "\"%s\" is not a valid TODO state" value)))
  11697. (org-todo value)
  11698. (org-align-tags))
  11699. ((equal property "PRIORITY")
  11700. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  11701. (org-align-tags))
  11702. ((equal property "SCHEDULED")
  11703. (forward-line)
  11704. (if (and (looking-at-p org-planning-line-re)
  11705. (re-search-forward
  11706. org-scheduled-time-regexp (line-end-position) t))
  11707. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  11708. ((string= value "later") (org-timestamp-change 1 'day))
  11709. ((string= value "") (org-schedule '(4)))
  11710. (t (org-schedule nil value)))
  11711. (if (member value '("earlier" "later" ""))
  11712. (call-interactively #'org-schedule)
  11713. (org-schedule nil value))))
  11714. ((equal property "DEADLINE")
  11715. (forward-line)
  11716. (if (and (looking-at-p org-planning-line-re)
  11717. (re-search-forward
  11718. org-deadline-time-regexp (line-end-position) t))
  11719. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  11720. ((string= value "later") (org-timestamp-change 1 'day))
  11721. ((string= value "") (org-deadline '(4)))
  11722. (t (org-deadline nil value)))
  11723. (if (member value '("earlier" "later" ""))
  11724. (call-interactively #'org-deadline)
  11725. (org-deadline nil value))))
  11726. ((member property org-special-properties)
  11727. (error "The %s property cannot be set with `org-entry-put'" property))
  11728. (t
  11729. (org-fold-core-ignore-modifications
  11730. (let* ((range (org-get-property-block beg 'force))
  11731. (end (cdr range))
  11732. (case-fold-search t))
  11733. (goto-char (car range))
  11734. (if (re-search-forward (org-re-property property nil t) end t)
  11735. (progn (delete-region (match-beginning 0) (match-end 0))
  11736. (goto-char (match-beginning 0)))
  11737. (goto-char end)
  11738. (insert-and-inherit "\n")
  11739. (backward-char))
  11740. (insert-and-inherit ":" property ":")
  11741. (when value (insert-and-inherit " " value))
  11742. (org-indent-line))))))
  11743. (run-hook-with-args 'org-property-changed-functions property value))))
  11744. (defun org-buffer-property-keys (&optional specials defaults columns)
  11745. "Get all property keys in the current buffer.
  11746. When SPECIALS is non-nil, also list the special properties that
  11747. reflect things like tags and TODO state.
  11748. When DEFAULTS is non-nil, also include properties that has
  11749. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  11750. DESCRIPTION, LOCATION, and LOGGING and others.
  11751. When COLUMNS in non-nil, also include property names given in
  11752. COLUMN formats in the current buffer."
  11753. (let ((case-fold-search t)
  11754. (props (append
  11755. (and specials org-special-properties)
  11756. (and defaults (cons org-effort-property org-default-properties))
  11757. ;; Get property names from #+PROPERTY keywords as well
  11758. (mapcar (lambda (s)
  11759. (nth 0 (split-string s)))
  11760. (cdar (org-collect-keywords '("PROPERTY")))))))
  11761. (org-with-wide-buffer
  11762. (goto-char (point-min))
  11763. (while (re-search-forward org-property-start-re nil t)
  11764. (catch :skip
  11765. (let ((range (org-get-property-block)))
  11766. (unless range (throw :skip nil))
  11767. (goto-char (car range))
  11768. (let ((begin (car range))
  11769. (end (cdr range)))
  11770. ;; Make sure that found property block is not located
  11771. ;; before current point, as it would generate an infloop.
  11772. ;; It can happen, for example, in the following
  11773. ;; situation:
  11774. ;;
  11775. ;; * Headline
  11776. ;; :PROPERTIES:
  11777. ;; ...
  11778. ;; :END:
  11779. ;; *************** Inlinetask
  11780. ;; #+BEGIN_EXAMPLE
  11781. ;; :PROPERTIES:
  11782. ;; #+END_EXAMPLE
  11783. ;;
  11784. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  11785. (while (< (point) end)
  11786. (let ((p (progn (looking-at org-property-re)
  11787. (match-string-no-properties 2))))
  11788. ;; Only add true property name, not extension symbol.
  11789. (push (if (not (string-match-p "\\+\\'" p)) p
  11790. (substring p 0 -1))
  11791. props))
  11792. (forward-line))))
  11793. (outline-next-heading)))
  11794. (when columns
  11795. (goto-char (point-min))
  11796. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  11797. (let ((element (org-element-at-point)))
  11798. (when (memq (org-element-type element) '(keyword node-property))
  11799. (let ((value (org-element-property :value element))
  11800. (start 0))
  11801. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  11802. \\(?:{[^}]+}\\)?"
  11803. value start)
  11804. (setq start (match-end 0))
  11805. (let ((p (match-string-no-properties 1 value)))
  11806. (unless (member-ignore-case p org-special-properties)
  11807. (push p props))))))))))
  11808. (sort (delete-dups
  11809. (append props
  11810. ;; for each xxx_ALL property, make sure the bare
  11811. ;; xxx property is also included
  11812. (delq nil (mapcar (lambda (p)
  11813. (and (string-match-p "._ALL\\'" p)
  11814. (substring p 0 -4)))
  11815. props))))
  11816. (lambda (a b) (string< (upcase a) (upcase b))))))
  11817. (defun org-property-values (key)
  11818. "List all non-nil values of property KEY in current buffer."
  11819. (org-with-wide-buffer
  11820. (goto-char (point-min))
  11821. (let ((case-fold-search t)
  11822. (re (org-re-property key))
  11823. values)
  11824. (while (re-search-forward re nil t)
  11825. (push (org-entry-get (point) key) values))
  11826. (delete-dups values))))
  11827. (defun org-insert-property-drawer ()
  11828. "Insert a property drawer into the current entry.
  11829. Do nothing if the drawer already exists. The newly created
  11830. drawer is immediately hidden."
  11831. (org-with-wide-buffer
  11832. ;; Set point to the position where the drawer should be inserted.
  11833. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  11834. (org-back-to-heading-or-point-min t)
  11835. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  11836. (if (org-before-first-heading-p)
  11837. (while (and (org-at-comment-p) (bolp)) (forward-line))
  11838. (forward-line)
  11839. (when (looking-at-p org-planning-line-re) (forward-line)))
  11840. (unless (looking-at-p org-property-drawer-re)
  11841. ;; Make sure we start editing a line from current entry, not from
  11842. ;; next one. It prevents extending text properties or overlays
  11843. ;; belonging to the latter.
  11844. (when (and (bolp) (> (point) (point-min))) (backward-char))
  11845. (let ((begin (if (bobp) (point) (1+ (point))))
  11846. (inhibit-read-only t))
  11847. (unless (bobp) (insert "\n"))
  11848. (insert ":PROPERTIES:\n:END:")
  11849. (org-fold-region (line-end-position 0) (point) t (if (eq org-fold-core-style 'text-properties) 'drawer 'outline))
  11850. (when (or (eobp) (= begin (point-min))) (insert "\n"))
  11851. (org-indent-region begin (point))))))
  11852. (defun org-insert-drawer (&optional arg drawer)
  11853. "Insert a drawer at point.
  11854. When optional argument ARG is non-nil, insert a property drawer.
  11855. Optional argument DRAWER, when non-nil, is a string representing
  11856. drawer's name. Otherwise, the user is prompted for a name.
  11857. If a region is active, insert the drawer around that region
  11858. instead.
  11859. Point is left between drawer's boundaries."
  11860. (interactive "P")
  11861. (let* ((drawer (if arg "PROPERTIES"
  11862. (or drawer (read-from-minibuffer "Drawer: ")))))
  11863. (cond
  11864. ;; With C-u, fall back on `org-insert-property-drawer'
  11865. (arg (org-insert-property-drawer))
  11866. ;; Check validity of suggested drawer's name.
  11867. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  11868. (user-error "Invalid drawer name"))
  11869. ;; With an active region, insert a drawer at point.
  11870. ((not (org-region-active-p))
  11871. (progn
  11872. (unless (bolp) (insert "\n"))
  11873. (insert (format ":%s:\n\n:END:\n" drawer))
  11874. (forward-line -2)))
  11875. ;; Otherwise, insert the drawer at point
  11876. (t
  11877. (let ((rbeg (region-beginning))
  11878. (rend (copy-marker (region-end))))
  11879. (unwind-protect
  11880. (progn
  11881. (goto-char rbeg)
  11882. (beginning-of-line)
  11883. (when (save-excursion
  11884. (re-search-forward org-outline-regexp-bol rend t))
  11885. (user-error "Drawers cannot contain headlines"))
  11886. ;; Position point at the beginning of the first
  11887. ;; non-blank line in region. Insert drawer's opening
  11888. ;; there, then indent it.
  11889. (org-skip-whitespace)
  11890. (beginning-of-line)
  11891. (insert ":" drawer ":\n")
  11892. (forward-line -1)
  11893. (indent-for-tab-command)
  11894. ;; Move point to the beginning of the first blank line
  11895. ;; after the last non-blank line in region. Insert
  11896. ;; drawer's closing, then indent it.
  11897. (goto-char rend)
  11898. (skip-chars-backward " \r\t\n")
  11899. (insert "\n:END:")
  11900. (deactivate-mark t)
  11901. (indent-for-tab-command)
  11902. (unless (eolp) (insert "\n")))
  11903. ;; Clear marker, whatever the outcome of insertion is.
  11904. (set-marker rend nil)))))))
  11905. (defvar org-property-set-functions-alist nil
  11906. "Property set function alist.
  11907. Each entry should have the following format:
  11908. (PROPERTY . READ-FUNCTION)
  11909. The read function will be called with the same argument as
  11910. `org-completing-read'.")
  11911. (defun org-set-property-function (property)
  11912. "Get the function that should be used to set PROPERTY.
  11913. This is computed according to `org-property-set-functions-alist'."
  11914. (or (cdr (assoc property org-property-set-functions-alist))
  11915. 'org-completing-read))
  11916. (defun org-read-property-value (property &optional pom default)
  11917. "Read value for PROPERTY, as a string.
  11918. When optional argument POM is non-nil, completion uses additional
  11919. information, i.e., allowed or existing values at point or marker
  11920. POM.
  11921. Optional argument DEFAULT provides a default value for PROPERTY."
  11922. (let* ((completion-ignore-case t)
  11923. (allowed
  11924. (or (org-property-get-allowed-values nil property 'table)
  11925. (and pom (org-property-get-allowed-values pom property 'table))))
  11926. (current (org-entry-get nil property))
  11927. (prompt (format "%s value%s: "
  11928. property
  11929. (if (org-string-nw-p current)
  11930. (format " [%s]" current)
  11931. "")))
  11932. (set-function (org-set-property-function property)))
  11933. (org-trim
  11934. (if allowed
  11935. (funcall set-function
  11936. prompt allowed nil
  11937. (not (get-text-property 0 'org-unrestricted (caar allowed)))
  11938. default nil default)
  11939. (let ((all (mapcar #'list
  11940. (append (org-property-values property)
  11941. (and pom
  11942. (org-with-point-at pom
  11943. (org-property-values property)))))))
  11944. (funcall set-function prompt all nil nil "" nil current))))))
  11945. (defvar org-last-set-property nil)
  11946. (defvar org-last-set-property-value nil)
  11947. (defun org-read-property-name ()
  11948. "Read a property name."
  11949. (let ((completion-ignore-case t)
  11950. (default-prop (or (and (org-at-property-p)
  11951. (match-string-no-properties 2))
  11952. org-last-set-property)))
  11953. (org-completing-read
  11954. (concat "Property"
  11955. (if default-prop (concat " [" default-prop "]") "")
  11956. ": ")
  11957. (mapcar #'list (org-buffer-property-keys nil t t))
  11958. nil nil nil nil default-prop)))
  11959. (defun org-set-property-and-value (use-last)
  11960. "Allow to set [PROPERTY]: [value] direction from prompt.
  11961. When use-default, don't even ask, just use the last
  11962. \"[PROPERTY]: [value]\" string from the history."
  11963. (interactive "P")
  11964. (let* ((completion-ignore-case t)
  11965. (pv (or (and use-last org-last-set-property-value)
  11966. (org-completing-read
  11967. "Enter a \"[Property]: [value]\" pair: "
  11968. nil nil nil nil nil
  11969. org-last-set-property-value)))
  11970. prop val)
  11971. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  11972. (setq prop (match-string 1 pv)
  11973. val (match-string 2 pv))
  11974. (org-set-property prop val))))
  11975. (defun org-set-property (property value)
  11976. "In the current entry, set PROPERTY to VALUE.
  11977. When called interactively, this will prompt for a property name, offering
  11978. completion on existing and default properties. And then it will prompt
  11979. for a value, offering completion either on allowed values (via an inherited
  11980. xxx_ALL property) or on existing values in other instances of this property
  11981. in the current file.
  11982. Throw an error when trying to set a property with an invalid name."
  11983. (interactive (list nil nil))
  11984. (let ((property (or property (org-read-property-name))))
  11985. ;; `org-entry-put' also makes the following check, but this one
  11986. ;; avoids polluting `org-last-set-property' and
  11987. ;; `org-last-set-property-value' needlessly.
  11988. (unless (org--valid-property-p property)
  11989. (user-error "Invalid property name: \"%s\"" property))
  11990. (let ((value (or value (org-read-property-value property)))
  11991. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  11992. (setq org-last-set-property property)
  11993. (setq org-last-set-property-value (concat property ": " value))
  11994. ;; Possibly postprocess the inserted value:
  11995. (when fn (setq value (funcall fn value)))
  11996. (unless (equal (org-entry-get nil property) value)
  11997. (org-entry-put nil property value)))))
  11998. (defun org-find-property (property &optional value)
  11999. "Find first entry in buffer that sets PROPERTY.
  12000. When optional argument VALUE is non-nil, only consider an entry
  12001. if it contains PROPERTY set to this value. If PROPERTY should be
  12002. explicitly set to nil, use string \"nil\" for VALUE.
  12003. Return position where the entry begins, or nil if there is no
  12004. such entry. If narrowing is in effect, only search the visible
  12005. part of the buffer."
  12006. (save-excursion
  12007. (goto-char (point-min))
  12008. (let ((case-fold-search t)
  12009. (re (org-re-property property nil (not value) value)))
  12010. (catch 'exit
  12011. (while (re-search-forward re nil t)
  12012. (when (if value (org-at-property-p)
  12013. (org-entry-get (point) property nil t))
  12014. (throw 'exit (progn (org-back-to-heading-or-point-min t)
  12015. (point)))))))))
  12016. (defun org-delete-property (property)
  12017. "In the current entry, delete PROPERTY."
  12018. (interactive
  12019. (let* ((completion-ignore-case t)
  12020. (cat (org-entry-get (point) "CATEGORY"))
  12021. (props0 (org-entry-properties nil 'standard))
  12022. (props (if cat props0
  12023. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  12024. (prop (if (< 1 (length props))
  12025. (completing-read "Property: " props nil t)
  12026. (caar props))))
  12027. (list prop)))
  12028. (if (not property)
  12029. (message "No property to delete in this entry")
  12030. (org-entry-delete nil property)
  12031. (message "Property \"%s\" deleted" property)))
  12032. (defun org-delete-property-globally (property)
  12033. "Remove PROPERTY globally, from all entries.
  12034. This function ignores narrowing, if any."
  12035. (interactive
  12036. (let* ((completion-ignore-case t)
  12037. (prop (completing-read
  12038. "Globally remove property: "
  12039. (mapcar #'list (org-buffer-property-keys)))))
  12040. (list prop)))
  12041. (org-with-wide-buffer
  12042. (goto-char (point-min))
  12043. (let ((count 0)
  12044. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  12045. (while (re-search-forward re nil t)
  12046. (when (org-entry-delete (point) property) (cl-incf count)))
  12047. (message "Property \"%s\" removed from %d entries" property count))))
  12048. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  12049. (defun org-compute-property-at-point ()
  12050. "Compute the property at point.
  12051. This looks for an enclosing column format, extracts the operator and
  12052. then applies it to the property in the column format's scope."
  12053. (interactive)
  12054. (unless (org-at-property-p)
  12055. (user-error "Not at a property"))
  12056. (let ((prop (match-string-no-properties 2)))
  12057. (org-columns-get-format-and-top-level)
  12058. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  12059. (user-error "No operator defined for property %s" prop))
  12060. (org-columns-compute prop)))
  12061. (defvar org-property-allowed-value-functions nil
  12062. "Hook for functions supplying allowed values for a specific property.
  12063. The functions must take a single argument, the name of the property, and
  12064. return a flat list of allowed values. If \":ETC\" is one of
  12065. the values, this means that these values are intended as defaults for
  12066. completion, but that other values should be allowed too.
  12067. The functions must return nil if they are not responsible for this
  12068. property.")
  12069. (defun org-property-get-allowed-values (pom property &optional table)
  12070. "Get allowed values for the property PROPERTY.
  12071. When TABLE is non-nil, return an alist that can directly be used for
  12072. completion."
  12073. (let (vals)
  12074. (cond
  12075. ((equal property "TODO")
  12076. (setq vals (org-with-point-at pom
  12077. (append org-todo-keywords-1 '("")))))
  12078. ((equal property "PRIORITY")
  12079. (let ((n org-priority-lowest))
  12080. (while (>= n org-priority-highest)
  12081. (push (char-to-string n) vals)
  12082. (setq n (1- n)))))
  12083. ((equal property "CATEGORY"))
  12084. ((member property org-special-properties))
  12085. ((setq vals (run-hook-with-args-until-success
  12086. 'org-property-allowed-value-functions property)))
  12087. (t
  12088. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  12089. (when (and vals (string-match "\\S-" vals))
  12090. (setq vals (car (read-from-string (concat "(" vals ")"))))
  12091. (setq vals (mapcar (lambda (x)
  12092. (cond ((stringp x) x)
  12093. ((numberp x) (number-to-string x))
  12094. ((symbolp x) (symbol-name x))
  12095. (t "???")))
  12096. vals)))))
  12097. (when (member ":ETC" vals)
  12098. (setq vals (remove ":ETC" vals))
  12099. (org-add-props (car vals) '(org-unrestricted t)))
  12100. (if table (mapcar 'list vals) vals)))
  12101. (defun org-property-previous-allowed-value (&optional _previous)
  12102. "Switch to the next allowed value for this property."
  12103. (interactive)
  12104. (org-property-next-allowed-value t))
  12105. (defun org-property-next-allowed-value (&optional previous)
  12106. "Switch to the next allowed value for this property."
  12107. (interactive)
  12108. (unless (org-at-property-p)
  12109. (user-error "Not at a property"))
  12110. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  12111. (key (match-string 2))
  12112. (value (match-string 3))
  12113. (allowed (or (org-property-get-allowed-values (point) key)
  12114. (and (member value '("[ ]" "[-]" "[X]"))
  12115. '("[ ]" "[X]"))))
  12116. (heading (save-match-data (nth 4 (org-heading-components))))
  12117. nval)
  12118. (unless allowed
  12119. (user-error "Allowed values for this property have not been defined"))
  12120. (when previous (setq allowed (reverse allowed)))
  12121. (when (member value allowed)
  12122. (setq nval (car (cdr (member value allowed)))))
  12123. (setq nval (or nval (car allowed)))
  12124. (when (equal nval value)
  12125. (user-error "Only one allowed value for this property"))
  12126. (org-at-property-p)
  12127. (replace-match (concat " :" key ": " nval) t t)
  12128. (org-indent-line)
  12129. (beginning-of-line 1)
  12130. (skip-chars-forward " \t")
  12131. (when (equal prop org-effort-property)
  12132. (unless (org-element--cache-active-p)
  12133. (org-refresh-property
  12134. '((effort . identity)
  12135. (effort-minutes . org-duration-to-minutes))
  12136. nval))
  12137. (when (string= org-clock-current-task heading)
  12138. (setq org-clock-effort nval)
  12139. (org-clock-update-mode-line)))
  12140. (run-hook-with-args 'org-property-changed-functions key nval)))
  12141. (defun org-find-olp (path &optional this-buffer)
  12142. "Return a marker pointing to the entry at outline path OLP.
  12143. If anything goes wrong, throw an error, and if you need to do
  12144. something based on this error, you can catch it with
  12145. `condition-case'.
  12146. If THIS-BUFFER is set, the outline path does not contain a file,
  12147. only headings."
  12148. (let* ((file (if this-buffer buffer-file-name (pop path)))
  12149. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  12150. (level 1)
  12151. (lmin 1)
  12152. (lmax 1)
  12153. end found flevel)
  12154. (unless buffer (error "File not found :%s" file))
  12155. (with-current-buffer buffer
  12156. (unless (derived-mode-p 'org-mode)
  12157. (error "Buffer %s needs to be in Org mode" buffer))
  12158. (org-with-wide-buffer
  12159. (goto-char (point-min))
  12160. (dolist (heading path)
  12161. (let ((re (format org-complex-heading-regexp-format
  12162. (regexp-quote heading)))
  12163. (cnt 0))
  12164. (while (re-search-forward re end t)
  12165. (setq level (- (match-end 1) (match-beginning 1)))
  12166. (when (and (>= level lmin) (<= level lmax))
  12167. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  12168. (when (= cnt 0)
  12169. (error "Heading not found on level %d: %s" lmax heading))
  12170. (when (> cnt 1)
  12171. (error "Heading not unique on level %d: %s" lmax heading))
  12172. (goto-char found)
  12173. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  12174. (setq end (save-excursion (org-end-of-subtree t t)))))
  12175. (when (org-at-heading-p)
  12176. (point-marker))))))
  12177. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  12178. "Find node HEADING in BUFFER.
  12179. Return a marker to the heading if it was found, or nil if not.
  12180. If POS-ONLY is set, return just the position instead of a marker.
  12181. The heading text must match exact, but it may have a TODO keyword,
  12182. a priority cookie and tags in the standard locations."
  12183. (with-current-buffer (or buffer (current-buffer))
  12184. (org-with-wide-buffer
  12185. (goto-char (point-min))
  12186. (let (case-fold-search)
  12187. (when (re-search-forward
  12188. (format org-complex-heading-regexp-format
  12189. (regexp-quote heading)) nil t)
  12190. (if pos-only
  12191. (match-beginning 0)
  12192. (move-marker (make-marker) (match-beginning 0))))))))
  12193. (defun org-find-exact-heading-in-directory (heading &optional dir)
  12194. "Find Org node headline HEADING in all \".org\" files in directory DIR.
  12195. When the target headline is found, return a marker to this location."
  12196. (let ((files (directory-files (or dir default-directory)
  12197. t "\\`[^.#].*\\.org\\'"))
  12198. visiting m buffer)
  12199. (catch 'found
  12200. (dolist (file files)
  12201. (message "trying %s" file)
  12202. (setq visiting (org-find-base-buffer-visiting file))
  12203. (setq buffer (or visiting (find-file-noselect file)))
  12204. (setq m (org-find-exact-headline-in-buffer
  12205. heading buffer))
  12206. (when (and (not m) (not visiting)) (kill-buffer buffer))
  12207. (and m (throw 'found m))))))
  12208. (defun org-find-entry-with-id (ident)
  12209. "Locate the entry that contains the ID property with exact value IDENT.
  12210. IDENT can be a string, a symbol or a number, this function will search for
  12211. the string representation of it.
  12212. Return the position where this entry starts, or nil if there is no such entry."
  12213. (interactive "sID: ")
  12214. (let ((id (cond
  12215. ((stringp ident) ident)
  12216. ((symbolp ident) (symbol-name ident))
  12217. ((numberp ident) (number-to-string ident))
  12218. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  12219. (org-with-wide-buffer (org-find-property "ID" id))))
  12220. ;;;; Timestamps
  12221. (defvar org-last-changed-timestamp nil)
  12222. (defvar org-last-inserted-timestamp nil
  12223. "The last time stamp inserted with `org-insert-time-stamp'.")
  12224. (defun org-time-stamp (arg &optional inactive)
  12225. "Prompt for a date/time and insert a time stamp.
  12226. If the user specifies a time like HH:MM or if this command is
  12227. called with at least one prefix argument, the time stamp contains
  12228. the date and the time. Otherwise, only the date is included.
  12229. All parts of a date not specified by the user are filled in from
  12230. the timestamp at point, if any, or the current date/time
  12231. otherwise.
  12232. If there is already a timestamp at the cursor, it is replaced.
  12233. With two universal prefix arguments, insert an active timestamp
  12234. with the current time without prompting the user.
  12235. When called from Lisp, the timestamp is inactive if INACTIVE is
  12236. non-nil."
  12237. (interactive "P")
  12238. (let* ((ts (cond
  12239. ((org-at-date-range-p t)
  12240. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  12241. ((org-at-timestamp-p 'lax) (match-string 0))))
  12242. ;; Default time is either the timestamp at point or today.
  12243. ;; When entering a range, only the range start is considered.
  12244. (default-time (and ts (org-time-string-to-time ts)))
  12245. (default-input (and ts (org-get-compact-tod ts)))
  12246. (repeater (and ts
  12247. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  12248. (match-string 0 ts)))
  12249. org-time-was-given
  12250. org-end-time-was-given
  12251. (time
  12252. (if (equal arg '(16)) (current-time)
  12253. ;; Preserve `this-command' and `last-command'.
  12254. (let ((this-command this-command)
  12255. (last-command last-command))
  12256. (org-read-date
  12257. arg 'totime nil nil default-time default-input
  12258. inactive)))))
  12259. (cond
  12260. ((and ts
  12261. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  12262. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  12263. (insert "--")
  12264. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  12265. (ts
  12266. ;; Make sure we're on a timestamp. When in the middle of a date
  12267. ;; range, move arbitrarily to range end.
  12268. (unless (org-at-timestamp-p 'lax)
  12269. (skip-chars-forward "-")
  12270. (org-at-timestamp-p 'lax))
  12271. (replace-match "")
  12272. (setq org-last-changed-timestamp
  12273. (org-insert-time-stamp
  12274. time (or org-time-was-given arg)
  12275. inactive nil nil (list org-end-time-was-given)))
  12276. (when repeater
  12277. (backward-char)
  12278. (insert " " repeater)
  12279. (setq org-last-changed-timestamp
  12280. (concat (substring org-last-inserted-timestamp 0 -1)
  12281. " " repeater ">")))
  12282. (message "Timestamp updated"))
  12283. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  12284. (t (org-insert-time-stamp
  12285. time (or org-time-was-given arg) inactive nil nil
  12286. (list org-end-time-was-given))))))
  12287. ;; FIXME: can we use this for something else, like computing time differences?
  12288. (defun org-get-compact-tod (s)
  12289. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  12290. (let* ((t1 (match-string 1 s))
  12291. (h1 (string-to-number (match-string 2 s)))
  12292. (m1 (string-to-number (match-string 3 s)))
  12293. (t2 (and (match-end 4) (match-string 5 s)))
  12294. (h2 (and t2 (string-to-number (match-string 6 s))))
  12295. (m2 (and t2 (string-to-number (match-string 7 s))))
  12296. dh dm)
  12297. (if (not t2)
  12298. t1
  12299. (setq dh (- h2 h1) dm (- m2 m1))
  12300. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  12301. (concat t1 "+" (number-to-string dh)
  12302. (and (/= 0 dm) (format ":%02d" dm)))))))
  12303. (defun org-time-stamp-inactive (&optional arg)
  12304. "Insert an inactive time stamp.
  12305. An inactive time stamp is enclosed in square brackets instead of
  12306. angle brackets. It is inactive in the sense that it does not
  12307. trigger agenda entries. So these are more for recording a
  12308. certain time/date.
  12309. If the user specifies a time like HH:MM or if this command is called with
  12310. at least one prefix argument, the time stamp contains the date and the time.
  12311. Otherwise, only the date is included.
  12312. When called with two universal prefix arguments, insert an inactive time stamp
  12313. with the current time without prompting the user."
  12314. (interactive "P")
  12315. (org-time-stamp arg 'inactive))
  12316. (defvar org-date-ovl (make-overlay 1 1))
  12317. (overlay-put org-date-ovl 'face 'org-date-selected)
  12318. (delete-overlay org-date-ovl)
  12319. (defvar org-ans1) ; dynamically scoped parameter
  12320. (defvar org-ans2) ; dynamically scoped parameter
  12321. (defvar org-plain-time-of-day-regexp) ; defined below
  12322. (defvar org-overriding-default-time nil) ; dynamically scoped
  12323. (defvar org-read-date-overlay nil)
  12324. (defvar org-read-date-history nil)
  12325. (defvar org-read-date-final-answer nil)
  12326. (defvar org-read-date-analyze-futurep nil)
  12327. (defvar org-read-date-analyze-forced-year nil)
  12328. (defvar org-read-date-inactive)
  12329. (defvar org-def)
  12330. (defvar org-defdecode)
  12331. (defvar org-with-time)
  12332. (defvar calendar-setup) ; Dynamically scoped.
  12333. (defun org-read-date (&optional with-time to-time from-string prompt
  12334. default-time default-input inactive)
  12335. "Read a date, possibly a time, and make things smooth for the user.
  12336. The prompt will suggest to enter an ISO date, but you can also enter anything
  12337. which will at least partially be understood by `parse-time-string'.
  12338. Unrecognized parts of the date will default to the current day, month, year,
  12339. hour and minute. If this command is called to replace a timestamp at point,
  12340. or to enter the second timestamp of a range, the default time is taken
  12341. from the existing stamp. Furthermore, the command prefers the future,
  12342. so if you are giving a date where the year is not given, and the day-month
  12343. combination is already past in the current year, it will assume you
  12344. mean next year. For details, see the manual. A few examples:
  12345. 3-2-5 --> 2003-02-05
  12346. feb 15 --> currentyear-02-15
  12347. 2/15 --> currentyear-02-15
  12348. sep 12 9 --> 2009-09-12
  12349. 12:45 --> today 12:45
  12350. 22 sept 0:34 --> currentyear-09-22 0:34
  12351. 12 --> currentyear-currentmonth-12
  12352. Fri --> nearest Friday after today
  12353. -Tue --> last Tuesday
  12354. etc.
  12355. Furthermore you can specify a relative date by giving, as the *first* thing
  12356. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  12357. change in days weeks, months, years.
  12358. With a single plus or minus, the date is relative to today. With a double
  12359. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  12360. +4d --> four days from today
  12361. +4 --> same as above
  12362. +2w --> two weeks from today
  12363. ++5 --> five days from default date
  12364. The function understands only English month and weekday abbreviations.
  12365. While prompting, a calendar is popped up - you can also select the
  12366. date with the mouse (button 1). The calendar shows a period of three
  12367. months. To scroll it to other months, use the keys `>' and `<'.
  12368. There are many other calendar navigation commands available, see
  12369. Info node `(org) The date/time prompt' for a full list.
  12370. If you don't like the calendar, turn it off with
  12371. (setq org-read-date-popup-calendar nil)
  12372. With optional argument TO-TIME, the date will immediately be converted
  12373. to an internal time.
  12374. With an optional argument WITH-TIME, the prompt will suggest to
  12375. also insert a time. Note that when WITH-TIME is not set, you can
  12376. still enter a time, and this function will inform the calling routine
  12377. about this change. The calling routine may then choose to change the
  12378. format used to insert the time stamp into the buffer to include the time.
  12379. With optional argument FROM-STRING, read from this string instead from
  12380. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  12381. the time/date that is used for everything that is not specified by the
  12382. user."
  12383. (require 'parse-time)
  12384. (let* ((org-with-time with-time)
  12385. (org-time-stamp-rounding-minutes
  12386. (if (equal org-with-time '(16))
  12387. '(0 0)
  12388. org-time-stamp-rounding-minutes))
  12389. (ct (org-current-time))
  12390. (org-def (or org-overriding-default-time default-time ct))
  12391. (org-defdecode (decode-time org-def))
  12392. (cur-frame (selected-frame))
  12393. (mouse-autoselect-window nil) ; Don't let the mouse jump
  12394. (calendar-setup
  12395. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  12396. (calendar-move-hook nil)
  12397. (calendar-view-diary-initially-flag nil)
  12398. (calendar-view-holidays-initially-flag nil)
  12399. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  12400. ;; Rationalize `org-def' and `org-defdecode', if required.
  12401. (when (< (nth 2 org-defdecode) org-extend-today-until)
  12402. (setf (nth 2 org-defdecode) -1)
  12403. (setf (nth 1 org-defdecode) 59)
  12404. (setq org-def (org-encode-time org-defdecode))
  12405. (setq org-defdecode (decode-time org-def)))
  12406. (let* ((timestr (format-time-string
  12407. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  12408. org-def))
  12409. (prompt (concat (if prompt (concat prompt " ") "")
  12410. (format "Date+time [%s]: " timestr))))
  12411. (cond
  12412. (from-string (setq ans from-string))
  12413. (org-read-date-popup-calendar
  12414. (save-excursion
  12415. (save-window-excursion
  12416. (calendar)
  12417. (when (eq calendar-setup 'calendar-only)
  12418. (setq cal-frame
  12419. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  12420. (select-frame cal-frame))
  12421. (org-eval-in-calendar '(setq cursor-type nil) t)
  12422. (unwind-protect
  12423. (progn
  12424. (calendar-forward-day (- (time-to-days org-def)
  12425. (calendar-absolute-from-gregorian
  12426. (calendar-current-date))))
  12427. (org-eval-in-calendar nil t)
  12428. (let* ((old-map (current-local-map))
  12429. (map (copy-keymap calendar-mode-map))
  12430. (minibuffer-local-map
  12431. (copy-keymap org-read-date-minibuffer-local-map)))
  12432. (org-defkey map (kbd "RET") 'org-calendar-select)
  12433. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  12434. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  12435. (unwind-protect
  12436. (progn
  12437. (use-local-map map)
  12438. (setq org-read-date-inactive inactive)
  12439. (add-hook 'post-command-hook 'org-read-date-display)
  12440. (setq org-ans0
  12441. (read-string prompt
  12442. default-input
  12443. 'org-read-date-history
  12444. nil))
  12445. ;; org-ans0: from prompt
  12446. ;; org-ans1: from mouse click
  12447. ;; org-ans2: from calendar motion
  12448. (setq ans
  12449. (concat org-ans0 " " (or org-ans1 org-ans2))))
  12450. (remove-hook 'post-command-hook 'org-read-date-display)
  12451. (use-local-map old-map)
  12452. (when org-read-date-overlay
  12453. (delete-overlay org-read-date-overlay)
  12454. (setq org-read-date-overlay nil)))))
  12455. (bury-buffer "*Calendar*")
  12456. (when cal-frame
  12457. (delete-frame cal-frame)
  12458. (select-frame-set-input-focus cur-frame))))))
  12459. (t ; Naked prompt only
  12460. (unwind-protect
  12461. (setq ans (read-string prompt default-input
  12462. 'org-read-date-history timestr))
  12463. (when org-read-date-overlay
  12464. (delete-overlay org-read-date-overlay)
  12465. (setq org-read-date-overlay nil))))))
  12466. (setq final (org-read-date-analyze ans org-def org-defdecode))
  12467. (when org-read-date-analyze-forced-year
  12468. (message "Year was forced into %s"
  12469. (if org-read-date-force-compatible-dates
  12470. "compatible range (1970-2037)"
  12471. "range representable on this machine"))
  12472. (ding))
  12473. (setq final (org-encode-time final))
  12474. (setq org-read-date-final-answer ans)
  12475. (if to-time
  12476. final
  12477. ;; This round-trip gets rid of 34th of August and stuff like that....
  12478. (setq final (decode-time final))
  12479. (if (and (boundp 'org-time-was-given) org-time-was-given)
  12480. (format "%04d-%02d-%02d %02d:%02d"
  12481. (nth 5 final) (nth 4 final) (nth 3 final)
  12482. (nth 2 final) (nth 1 final))
  12483. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  12484. (defun org-read-date-display ()
  12485. "Display the current date prompt interpretation in the minibuffer."
  12486. (when org-read-date-display-live
  12487. (when org-read-date-overlay
  12488. (delete-overlay org-read-date-overlay))
  12489. (when (minibufferp (current-buffer))
  12490. (save-excursion
  12491. (end-of-line 1)
  12492. (while (not (equal (buffer-substring
  12493. (max (point-min) (- (point) 4)) (point))
  12494. " "))
  12495. (insert " ")))
  12496. (let* ((ans (concat (buffer-substring (line-beginning-position)
  12497. (point-max))
  12498. " " (or org-ans1 org-ans2)))
  12499. (org-end-time-was-given nil)
  12500. (f (org-read-date-analyze ans org-def org-defdecode))
  12501. (fmts (if org-display-custom-times
  12502. org-time-stamp-custom-formats
  12503. org-time-stamp-formats))
  12504. (fmt (if (or org-with-time
  12505. (and (boundp 'org-time-was-given) org-time-was-given))
  12506. (cdr fmts)
  12507. (car fmts)))
  12508. (txt (format-time-string fmt (org-encode-time f)))
  12509. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  12510. (txt (concat "=> " txt)))
  12511. (when (and org-end-time-was-given
  12512. (string-match org-plain-time-of-day-regexp txt))
  12513. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  12514. org-end-time-was-given
  12515. (substring txt (match-end 0)))))
  12516. (when org-read-date-analyze-futurep
  12517. (setq txt (concat txt " (=>F)")))
  12518. (setq org-read-date-overlay
  12519. (make-overlay (1- (line-end-position)) (line-end-position)))
  12520. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  12521. (defun org-read-date-analyze (ans def defdecode)
  12522. "Analyze the combined answer of the date prompt."
  12523. ;; FIXME: cleanup and comment
  12524. (let ((org-def def)
  12525. (org-defdecode defdecode)
  12526. (nowdecode (decode-time))
  12527. delta deltan deltaw deltadef year month day
  12528. hour minute second wday pm h2 m2 tl wday1
  12529. iso-year iso-weekday iso-week iso-date futurep kill-year)
  12530. (setq org-read-date-analyze-futurep nil
  12531. org-read-date-analyze-forced-year nil)
  12532. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  12533. (setq ans "+0"))
  12534. (when (setq delta (org-read-date-get-relative ans nil org-def))
  12535. (setq ans (replace-match "" t t ans)
  12536. deltan (car delta)
  12537. deltaw (nth 1 delta)
  12538. deltadef (nth 2 delta)))
  12539. ;; Check if there is an iso week date in there. If yes, store the
  12540. ;; info and postpone interpreting it until the rest of the parsing
  12541. ;; is done.
  12542. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  12543. (setq iso-year (when (match-end 1)
  12544. (org-small-year-to-year
  12545. (string-to-number (match-string 1 ans))))
  12546. iso-weekday (when (match-end 3)
  12547. (string-to-number (match-string 3 ans)))
  12548. iso-week (string-to-number (match-string 2 ans)))
  12549. (setq ans (replace-match "" t t ans)))
  12550. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  12551. (when (string-match
  12552. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  12553. (setq year (if (match-end 2)
  12554. (string-to-number (match-string 2 ans))
  12555. (progn (setq kill-year t)
  12556. (string-to-number (format-time-string "%Y"))))
  12557. month (string-to-number (match-string 3 ans))
  12558. day (string-to-number (match-string 4 ans)))
  12559. (setq year (org-small-year-to-year year))
  12560. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  12561. t nil ans)))
  12562. ;; Help matching dotted european dates
  12563. (when (string-match
  12564. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  12565. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  12566. (setq kill-year t)
  12567. (string-to-number (format-time-string "%Y")))
  12568. day (string-to-number (match-string 1 ans))
  12569. month (string-to-number (match-string 2 ans))
  12570. ans (replace-match (format "%04d-%02d-%02d" year month day)
  12571. t nil ans)))
  12572. ;; Help matching american dates, like 5/30 or 5/30/7
  12573. (when (string-match
  12574. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  12575. (setq year (if (match-end 4)
  12576. (string-to-number (match-string 4 ans))
  12577. (progn (setq kill-year t)
  12578. (string-to-number (format-time-string "%Y"))))
  12579. month (string-to-number (match-string 1 ans))
  12580. day (string-to-number (match-string 2 ans)))
  12581. (setq year (org-small-year-to-year year))
  12582. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  12583. t nil ans)))
  12584. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  12585. ;; If there is a time with am/pm, and *no* time without it, we convert
  12586. ;; so that matching will be successful.
  12587. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  12588. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  12589. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  12590. (setq hour (string-to-number (match-string 1 ans))
  12591. minute (if (match-end 3)
  12592. (string-to-number (match-string 3 ans))
  12593. 0)
  12594. pm (equal ?p
  12595. (string-to-char (downcase (match-string 4 ans)))))
  12596. (if (and (= hour 12) (not pm))
  12597. (setq hour 0)
  12598. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  12599. (setq ans (replace-match (format "%02d:%02d" hour minute)
  12600. t t ans))))
  12601. ;; Help matching HHhMM times, similarly as for am/pm times.
  12602. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  12603. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  12604. (string-match "\\(?:\\(?1:[012]?[0-9]\\)?h\\(?2:[0-5][0-9]\\)\\)\\|\\(?:\\(?1:[012]?[0-9]\\)h\\(?2:[0-5][0-9]\\)?\\)\\>" ans))
  12605. (setq hour (if (match-end 1)
  12606. (string-to-number (match-string 1 ans))
  12607. 0)
  12608. minute (if (match-end 2)
  12609. (string-to-number (match-string 2 ans))
  12610. 0))
  12611. (setq ans (replace-match (format "%02d:%02d" hour minute)
  12612. t t ans))))
  12613. ;; Check if a time range is given as a duration
  12614. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  12615. (setq hour (string-to-number (match-string 1 ans))
  12616. h2 (+ hour (string-to-number (match-string 3 ans)))
  12617. minute (string-to-number (match-string 2 ans))
  12618. m2 (+ minute (if (match-end 5) (string-to-number
  12619. (match-string 5 ans))0)))
  12620. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  12621. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  12622. t t ans)))
  12623. ;; Check if there is a time range
  12624. (when (boundp 'org-end-time-was-given)
  12625. (setq org-time-was-given nil)
  12626. (when (and (string-match org-plain-time-of-day-regexp ans)
  12627. (match-end 8))
  12628. (setq org-end-time-was-given (match-string 8 ans))
  12629. (setq ans (concat (substring ans 0 (match-beginning 7))
  12630. (substring ans (match-end 7))))))
  12631. (setq tl (parse-time-string ans)
  12632. day (or (nth 3 tl) (nth 3 org-defdecode))
  12633. month
  12634. (cond ((nth 4 tl))
  12635. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  12636. ;; Day was specified. Make sure DAY+MONTH
  12637. ;; combination happens in the future.
  12638. ((nth 3 tl)
  12639. (setq futurep t)
  12640. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  12641. (nth 4 nowdecode)))
  12642. (t (nth 4 org-defdecode)))
  12643. year
  12644. (cond ((and (not kill-year) (nth 5 tl)))
  12645. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  12646. ;; Month was guessed in the future and is at least
  12647. ;; equal to NOWDECODE's. Fix year accordingly.
  12648. (futurep
  12649. (if (or (> month (nth 4 nowdecode))
  12650. (>= day (nth 3 nowdecode)))
  12651. (nth 5 nowdecode)
  12652. (1+ (nth 5 nowdecode))))
  12653. ;; Month was specified. Make sure MONTH+YEAR
  12654. ;; combination happens in the future.
  12655. ((nth 4 tl)
  12656. (setq futurep t)
  12657. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  12658. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  12659. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  12660. (t (nth 5 nowdecode))))
  12661. (t (nth 5 org-defdecode)))
  12662. hour (or (nth 2 tl) (nth 2 org-defdecode))
  12663. minute (or (nth 1 tl) (nth 1 org-defdecode))
  12664. second (or (nth 0 tl) 0)
  12665. wday (nth 6 tl))
  12666. (when (and (eq org-read-date-prefer-future 'time)
  12667. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  12668. (equal day (nth 3 nowdecode))
  12669. (equal month (nth 4 nowdecode))
  12670. (equal year (nth 5 nowdecode))
  12671. (nth 2 tl)
  12672. (or (< (nth 2 tl) (nth 2 nowdecode))
  12673. (and (= (nth 2 tl) (nth 2 nowdecode))
  12674. (nth 1 tl)
  12675. (< (nth 1 tl) (nth 1 nowdecode)))))
  12676. (setq day (1+ day)
  12677. futurep t))
  12678. ;; Special date definitions below
  12679. (cond
  12680. (iso-week
  12681. ;; There was an iso week
  12682. (require 'cal-iso)
  12683. (setq futurep nil)
  12684. (setq year (or iso-year year)
  12685. day (or iso-weekday wday 1)
  12686. wday nil ; to make sure that the trigger below does not match
  12687. iso-date (calendar-gregorian-from-absolute
  12688. (calendar-iso-to-absolute
  12689. (list iso-week day year))))
  12690. ; FIXME: Should we also push ISO weeks into the future?
  12691. ; (when (and org-read-date-prefer-future
  12692. ; (not iso-year)
  12693. ; (< (calendar-absolute-from-gregorian iso-date)
  12694. ; (time-to-days nil)))
  12695. ; (setq year (1+ year)
  12696. ; iso-date (calendar-gregorian-from-absolute
  12697. ; (calendar-iso-to-absolute
  12698. ; (list iso-week day year)))))
  12699. (setq month (car iso-date)
  12700. year (nth 2 iso-date)
  12701. day (nth 1 iso-date)))
  12702. (deltan
  12703. (setq futurep nil)
  12704. (unless deltadef
  12705. (let ((now (decode-time)))
  12706. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  12707. (cond ((member deltaw '("h" ""))
  12708. (when (boundp 'org-time-was-given)
  12709. (setq org-time-was-given t))
  12710. (setq hour (+ hour deltan)))
  12711. ((member deltaw '("d" "")) (setq day (+ day deltan)))
  12712. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  12713. ((equal deltaw "m") (setq month (+ month deltan)))
  12714. ((equal deltaw "y") (setq year (+ year deltan)))))
  12715. ((and wday (not (nth 3 tl)))
  12716. ;; Weekday was given, but no day, so pick that day in the week
  12717. ;; on or after the derived date.
  12718. (setq wday1 (nth 6 (decode-time (org-encode-time 0 0 0 day month year))))
  12719. (unless (equal wday wday1)
  12720. (setq day (+ day (% (- wday wday1 -7) 7))))))
  12721. (when (and (boundp 'org-time-was-given)
  12722. (nth 2 tl))
  12723. (setq org-time-was-given t))
  12724. (when (< year 100) (setq year (+ 2000 year)))
  12725. ;; Check of the date is representable
  12726. (if org-read-date-force-compatible-dates
  12727. (progn
  12728. (when (< year 1970)
  12729. (setq year 1970 org-read-date-analyze-forced-year t))
  12730. (when (> year 2037)
  12731. (setq year 2037 org-read-date-analyze-forced-year t)))
  12732. (condition-case nil
  12733. (ignore (org-encode-time second minute hour day month year))
  12734. (error
  12735. (setq year (nth 5 org-defdecode))
  12736. (setq org-read-date-analyze-forced-year t))))
  12737. (setq org-read-date-analyze-futurep futurep)
  12738. (list second minute hour day month year nil -1 nil)))
  12739. (defvar parse-time-weekdays)
  12740. (defun org-read-date-get-relative (s today default)
  12741. "Check string S for special relative date string.
  12742. TODAY and DEFAULT are internal times, for today and for a default.
  12743. Return shift list (N what def-flag)
  12744. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  12745. N is the number of WHATs to shift.
  12746. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  12747. the DEFAULT date rather than TODAY."
  12748. (require 'parse-time)
  12749. (when (and
  12750. (string-match
  12751. (concat
  12752. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  12753. "\\([0-9]+\\)?"
  12754. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  12755. "\\([ \t]\\|$\\)") s)
  12756. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  12757. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  12758. (string-to-char (substring (match-string 1 s) -1))
  12759. ?+))
  12760. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  12761. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  12762. (what (if (match-end 3) (match-string 3 s) "d"))
  12763. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  12764. (date (if rel default today))
  12765. (wday (nth 6 (decode-time date)))
  12766. delta)
  12767. (if wday1
  12768. (progn
  12769. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  12770. (when (= delta 0) (setq delta 7))
  12771. (when (= dir ?-)
  12772. (setq delta (- delta 7))
  12773. (when (= delta 0) (setq delta -7)))
  12774. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  12775. (list delta "d" rel))
  12776. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  12777. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  12778. "Turn a user-specified date into the internal representation.
  12779. The internal representation needed by the calendar is (month day year).
  12780. This is a wrapper to handle the brain-dead convention in calendar that
  12781. user function argument order change dependent on argument order."
  12782. (pcase calendar-date-style
  12783. (`american (list arg1 arg2 arg3))
  12784. (`european (list arg2 arg1 arg3))
  12785. (`iso (list arg2 arg3 arg1))))
  12786. (defun org-eval-in-calendar (form &optional keepdate)
  12787. "Eval FORM in the calendar window and return to current window.
  12788. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  12789. (let ((sf (selected-frame))
  12790. (sw (selected-window)))
  12791. (select-window (get-buffer-window "*Calendar*" t))
  12792. (eval form t)
  12793. (when (and (not keepdate) (calendar-cursor-to-date))
  12794. (let* ((date (calendar-cursor-to-date))
  12795. (time (org-encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  12796. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  12797. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  12798. (select-window sw)
  12799. (select-frame-set-input-focus sf)))
  12800. (defun org-calendar-select ()
  12801. "Return to `org-read-date' with the date currently selected.
  12802. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  12803. (interactive)
  12804. (when (calendar-cursor-to-date)
  12805. (let* ((date (calendar-cursor-to-date))
  12806. (time (org-encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  12807. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  12808. (when (active-minibuffer-window) (exit-minibuffer))))
  12809. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  12810. "Insert a date stamp for the date given by the internal TIME.
  12811. See `format-time-string' for the format of TIME.
  12812. WITH-HM means use the stamp format that includes the time of the day.
  12813. INACTIVE means use square brackets instead of angular ones, so that the
  12814. stamp will not contribute to the agenda.
  12815. PRE and POST are optional strings to be inserted before and after the
  12816. stamp.
  12817. The command returns the inserted time stamp."
  12818. (org-fold-core-ignore-modifications
  12819. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  12820. stamp)
  12821. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  12822. (insert-before-markers-and-inherit (or pre ""))
  12823. (when (listp extra)
  12824. (setq extra (car extra))
  12825. (if (and (stringp extra)
  12826. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  12827. (setq extra (format "-%02d:%02d"
  12828. (string-to-number (match-string 1 extra))
  12829. (string-to-number (match-string 2 extra))))
  12830. (setq extra nil)))
  12831. (when extra
  12832. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  12833. (insert-before-markers-and-inherit (setq stamp (format-time-string fmt time)))
  12834. (insert-before-markers-and-inherit (or post ""))
  12835. (setq org-last-inserted-timestamp stamp))))
  12836. (defun org-toggle-time-stamp-overlays ()
  12837. "Toggle the use of custom time stamp formats."
  12838. (interactive)
  12839. (setq org-display-custom-times (not org-display-custom-times))
  12840. (unless org-display-custom-times
  12841. (let ((p (point-min)) (bmp (buffer-modified-p)))
  12842. (while (setq p (next-single-property-change p 'display))
  12843. (when (and (get-text-property p 'display)
  12844. (eq (get-text-property p 'face) 'org-date))
  12845. (remove-text-properties
  12846. p (setq p (next-single-property-change p 'display))
  12847. '(display t))))
  12848. (set-buffer-modified-p bmp)))
  12849. (org-restart-font-lock)
  12850. (setq org-table-may-need-update t)
  12851. (if org-display-custom-times
  12852. (message "Time stamps are overlaid with custom format")
  12853. (message "Time stamp overlays removed")))
  12854. (defun org-display-custom-time (beg end)
  12855. "Overlay modified time stamp format over timestamp between BEG and END."
  12856. (let* ((ts (buffer-substring beg end))
  12857. t1 with-hm tf time str (off 0))
  12858. (save-match-data
  12859. (setq t1 (org-parse-time-string ts t))
  12860. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  12861. (setq off (- (match-end 0) (match-beginning 0)))))
  12862. (setq end (- end off))
  12863. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  12864. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  12865. time (org-fix-decoded-time t1)
  12866. str (org-add-props
  12867. (format-time-string
  12868. (substring tf 1 -1) (org-encode-time time))
  12869. nil 'mouse-face 'highlight))
  12870. (put-text-property beg end 'display str)))
  12871. (defun org-fix-decoded-time (time)
  12872. "Set 0 instead of nil for the first 6 elements of time.
  12873. Don't touch the rest."
  12874. (let ((n 0))
  12875. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  12876. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  12877. "Difference between TIMESTAMP-STRING and now in days.
  12878. If SECONDS is non-nil, return the difference in seconds."
  12879. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  12880. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  12881. (funcall fdiff nil))))
  12882. (defun org-deadline-close-p (timestamp-string &optional ndays)
  12883. "Is the time in TIMESTAMP-STRING close to the current date?"
  12884. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  12885. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  12886. (not (org-entry-is-done-p))))
  12887. (defun org-get-wdays (ts &optional delay zero-delay)
  12888. "Get the deadline lead time appropriate for timestring TS.
  12889. When DELAY is non-nil, get the delay time for scheduled items
  12890. instead of the deadline lead time. When ZERO-DELAY is non-nil
  12891. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  12892. don't try to find the delay cookie in the scheduled timestamp."
  12893. (let ((tv (if delay org-scheduled-delay-days
  12894. org-deadline-warning-days)))
  12895. (cond
  12896. ((or (and delay (< tv 0))
  12897. (and delay zero-delay (<= tv 0))
  12898. (and (not delay) (<= tv 0)))
  12899. ;; Enforce this value no matter what
  12900. (- tv))
  12901. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  12902. ;; lead time is specified.
  12903. (floor (* (string-to-number (match-string 1 ts))
  12904. (cdr (assoc (match-string 2 ts)
  12905. '(("d" . 1) ("w" . 7)
  12906. ("m" . 30.4) ("y" . 365.25)
  12907. ("h" . 0.041667)))))))
  12908. ;; go for the default.
  12909. (t tv))))
  12910. (defun org-calendar-select-mouse (ev)
  12911. "Return to `org-read-date' with the date currently selected.
  12912. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  12913. (interactive "e")
  12914. (mouse-set-point ev)
  12915. (when (calendar-cursor-to-date)
  12916. (let* ((date (calendar-cursor-to-date))
  12917. (time (org-encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  12918. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  12919. (when (active-minibuffer-window) (exit-minibuffer))))
  12920. (defun org-check-deadlines (ndays)
  12921. "Check if there are any deadlines due or past due.
  12922. A deadline is considered due if it happens within `org-deadline-warning-days'
  12923. days from today's date. If the deadline appears in an entry marked DONE,
  12924. it is not shown. A numeric prefix argument NDAYS can be used to test that
  12925. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  12926. are shown."
  12927. (interactive "P")
  12928. (let* ((org-warn-days
  12929. (cond
  12930. ((equal ndays '(4)) 100000)
  12931. (ndays (prefix-numeric-value ndays))
  12932. (t (abs org-deadline-warning-days))))
  12933. (case-fold-search nil)
  12934. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  12935. (callback
  12936. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  12937. (message "%d deadlines past-due or due within %d days"
  12938. (org-occur regexp nil callback)
  12939. org-warn-days)))
  12940. (defsubst org-re-timestamp (type)
  12941. "Return a regexp for timestamp TYPE.
  12942. Allowed values for TYPE are:
  12943. all: all timestamps
  12944. active: only active timestamps (<...>)
  12945. inactive: only inactive timestamps ([...])
  12946. scheduled: only scheduled timestamps
  12947. deadline: only deadline timestamps
  12948. closed: only closed time-stamps
  12949. When TYPE is nil, fall back on returning a regexp that matches
  12950. both scheduled and deadline timestamps."
  12951. (cl-case type
  12952. (all org-ts-regexp-both)
  12953. (active org-ts-regexp)
  12954. (inactive org-ts-regexp-inactive)
  12955. (scheduled org-scheduled-time-regexp)
  12956. (deadline org-deadline-time-regexp)
  12957. (closed org-closed-time-regexp)
  12958. (otherwise
  12959. (concat "\\<"
  12960. (regexp-opt (list org-deadline-string org-scheduled-string))
  12961. " *<\\([^>]+\\)>"))))
  12962. (defun org-check-before-date (d)
  12963. "Check if there are deadlines or scheduled entries before date D."
  12964. (interactive (list (org-read-date)))
  12965. (let* ((case-fold-search nil)
  12966. (regexp (org-re-timestamp org-ts-type))
  12967. (ts-type org-ts-type)
  12968. (callback
  12969. (lambda ()
  12970. (let ((match (match-string 1)))
  12971. (and (if (memq ts-type '(active inactive all))
  12972. (eq (org-element-type (save-excursion
  12973. (backward-char)
  12974. (org-element-context)))
  12975. 'timestamp)
  12976. (org-at-planning-p))
  12977. (time-less-p
  12978. (org-time-string-to-time match)
  12979. (org-time-string-to-time d)))))))
  12980. (message "%d entries before %s"
  12981. (org-occur regexp nil callback)
  12982. d)))
  12983. (defun org-check-after-date (d)
  12984. "Check if there are deadlines or scheduled entries after date D."
  12985. (interactive (list (org-read-date)))
  12986. (let* ((case-fold-search nil)
  12987. (regexp (org-re-timestamp org-ts-type))
  12988. (ts-type org-ts-type)
  12989. (callback
  12990. (lambda ()
  12991. (let ((match (match-string 1)))
  12992. (and (if (memq ts-type '(active inactive all))
  12993. (eq (org-element-type (save-excursion
  12994. (backward-char)
  12995. (org-element-context)))
  12996. 'timestamp)
  12997. (org-at-planning-p))
  12998. (not (time-less-p
  12999. (org-time-string-to-time match)
  13000. (org-time-string-to-time d))))))))
  13001. (message "%d entries after %s"
  13002. (org-occur regexp nil callback)
  13003. d)))
  13004. (defun org-check-dates-range (start-date end-date)
  13005. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  13006. (interactive (list (org-read-date nil nil nil "Range starts")
  13007. (org-read-date nil nil nil "Range end")))
  13008. (let ((case-fold-search nil)
  13009. (regexp (org-re-timestamp org-ts-type))
  13010. (callback
  13011. (let ((type org-ts-type))
  13012. (lambda ()
  13013. (let ((match (match-string 1)))
  13014. (and
  13015. (if (memq type '(active inactive all))
  13016. (eq (org-element-type (save-excursion
  13017. (backward-char)
  13018. (org-element-context)))
  13019. 'timestamp)
  13020. (org-at-planning-p))
  13021. (not (time-less-p
  13022. (org-time-string-to-time match)
  13023. (org-time-string-to-time start-date)))
  13024. (time-less-p
  13025. (org-time-string-to-time match)
  13026. (org-time-string-to-time end-date))))))))
  13027. (message "%d entries between %s and %s"
  13028. (org-occur regexp nil callback) start-date end-date)))
  13029. (defun org-evaluate-time-range (&optional to-buffer)
  13030. "Evaluate a time range by computing the difference between start and end.
  13031. Normally the result is just printed in the echo area, but with prefix arg
  13032. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  13033. If the time range is actually in a table, the result is inserted into the
  13034. next column.
  13035. For time difference computation, a year is assumed to be exactly 365
  13036. days in order to avoid rounding problems."
  13037. (interactive "P")
  13038. (or
  13039. (org-clock-update-time-maybe)
  13040. (save-excursion
  13041. (unless (org-at-date-range-p t)
  13042. (goto-char (line-beginning-position))
  13043. (re-search-forward org-tr-regexp-both (line-end-position) t))
  13044. (unless (org-at-date-range-p t)
  13045. (user-error "Not at a time-stamp range, and none found in current line")))
  13046. (let* ((ts1 (match-string 1))
  13047. (ts2 (match-string 2))
  13048. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  13049. (match-end (match-end 0))
  13050. (time1 (org-time-string-to-time ts1))
  13051. (time2 (org-time-string-to-time ts2))
  13052. (diff (abs (float-time (time-subtract time2 time1))))
  13053. (negative (time-less-p time2 time1))
  13054. ;; (ys (floor (* 365 24 60 60)))
  13055. (ds (* 24 60 60))
  13056. (hs (* 60 60))
  13057. (fy "%dy %dd %02d:%02d")
  13058. (fy1 "%dy %dd")
  13059. (fd "%dd %02d:%02d")
  13060. (fd1 "%dd")
  13061. (fh "%02d:%02d")
  13062. y d h m align)
  13063. (if havetime
  13064. (setq ; y (floor diff ys) diff (mod diff ys)
  13065. y 0
  13066. d (floor diff ds) diff (mod diff ds)
  13067. h (floor diff hs) diff (mod diff hs)
  13068. m (floor diff 60))
  13069. (setq ; y (floor diff ys) diff (mod diff ys)
  13070. y 0
  13071. d (round diff ds)
  13072. h 0 m 0))
  13073. (if (not to-buffer)
  13074. (message "%s" (org-make-tdiff-string y d h m))
  13075. (if (org-at-table-p)
  13076. (progn
  13077. (goto-char match-end)
  13078. (setq align t)
  13079. (and (looking-at " *|") (goto-char (match-end 0))))
  13080. (goto-char match-end))
  13081. (when (looking-at
  13082. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  13083. (replace-match ""))
  13084. (when negative (insert " -"))
  13085. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  13086. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  13087. (insert " " (format fh h m))))
  13088. (when align (org-table-align))
  13089. (message "Time difference inserted")))))
  13090. (defun org-make-tdiff-string (y d h m)
  13091. (let ((fmt "")
  13092. (l nil))
  13093. (when (> y 0)
  13094. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  13095. (push y l))
  13096. (when (> d 0)
  13097. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  13098. (push d l))
  13099. (when (> h 0)
  13100. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  13101. (push h l))
  13102. (when (> m 0)
  13103. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  13104. (push m l))
  13105. (apply 'format fmt (nreverse l))))
  13106. (defun org-time-string-to-time (s)
  13107. "Convert timestamp string S into internal time."
  13108. (org-encode-time (org-parse-time-string s)))
  13109. (defun org-time-string-to-seconds (s)
  13110. "Convert a timestamp string S into a number of seconds."
  13111. (float-time (org-time-string-to-time s)))
  13112. (define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  13113. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  13114. "Convert time stamp S to an absolute day number.
  13115. If DAYNR in non-nil, and there is a specifier for a cyclic time
  13116. stamp, get the closest date to DAYNR. If PREFER is
  13117. `past' (respectively `future') return a date past (respectively
  13118. after) or equal to DAYNR.
  13119. POS is the location of time stamp S, as a buffer position in
  13120. BUFFER.
  13121. Diary sexp timestamps are matched against DAYNR, when non-nil.
  13122. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  13123. signaled."
  13124. (cond
  13125. ((string-match "\\`%%\\((.*)\\)" s)
  13126. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  13127. ;; only able to match individual dates. If it fails, raise an
  13128. ;; error.
  13129. (if (and daynr
  13130. (org-diary-sexp-entry
  13131. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  13132. daynr
  13133. (signal 'org-diary-sexp-no-match (list s))))
  13134. (daynr (org-closest-date s daynr prefer))
  13135. (t (time-to-days
  13136. (condition-case errdata
  13137. (org-time-string-to-time s)
  13138. (error (error "Bad timestamp `%s'%s\nError was: %s"
  13139. s
  13140. (if (not (and buffer pos)) ""
  13141. (format-message " at %d in buffer `%s'" pos buffer))
  13142. (cdr errdata))))))))
  13143. (defun org-days-to-iso-week (days)
  13144. "Return the ISO week number."
  13145. (require 'cal-iso)
  13146. (car (calendar-iso-from-absolute days)))
  13147. (defun org-small-year-to-year (year)
  13148. "Convert 2-digit years into 4-digit years.
  13149. YEAR is expanded into one of the 30 next years, if possible, or
  13150. into a past one. Any year larger than 99 is returned unchanged."
  13151. (if (>= year 100) year
  13152. (let* ((current (string-to-number (format-time-string "%Y")))
  13153. (century (/ current 100))
  13154. (offset (- year (% current 100))))
  13155. (cond ((> offset 30) (+ (* (1- century) 100) year))
  13156. ((> offset -70) (+ (* century 100) year))
  13157. (t (+ (* (1+ century) 100) year))))))
  13158. (defun org-time-from-absolute (d)
  13159. "Return the time corresponding to date D.
  13160. D may be an absolute day number, or a calendar-type list (month day year)."
  13161. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  13162. (org-encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  13163. (defvar org-agenda-current-date)
  13164. (defun org-calendar-holiday ()
  13165. "List of holidays, for Diary display in Org mode."
  13166. (require 'holidays)
  13167. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  13168. (and hl (mapconcat #'identity hl "; "))))
  13169. (defvar org--diary-sexp-entry-cache (make-hash-table :test #'equal)
  13170. "Hash table holding return values of `org-diary-sexp-entry'.")
  13171. (defun org-diary-sexp-entry (sexp entry d)
  13172. "Process a SEXP diary ENTRY for date D."
  13173. (require 'diary-lib)
  13174. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  13175. ;; dynamically.
  13176. (let ((cached (gethash (list sexp entry d) org--diary-sexp-entry-cache 'none)))
  13177. (if (not (eq 'none cached)) cached
  13178. (puthash (list sexp entry d)
  13179. (let* ((sexp `(let ((entry ,entry)
  13180. (date ',d))
  13181. ,(car (read-from-string sexp))))
  13182. ;; FIXME: Do not use (eval ... t) in the following sexp as
  13183. ;; diary vars are still using dynamic scope.
  13184. (result (if calendar-debug-sexp (eval sexp)
  13185. (condition-case nil
  13186. (eval sexp)
  13187. (error
  13188. (beep)
  13189. (message "Bad sexp at line %d in %s: %s"
  13190. (org-current-line)
  13191. (buffer-file-name) sexp)
  13192. (sleep-for 2))))))
  13193. (cond ((stringp result) (split-string result "; "))
  13194. ((and (consp result)
  13195. (not (consp (cdr result)))
  13196. (stringp (cdr result)))
  13197. (cdr result))
  13198. ((and (consp result)
  13199. (stringp (car result)))
  13200. result)
  13201. (result entry)))
  13202. org--diary-sexp-entry-cache))))
  13203. (defun org-diary-to-ical-string (frombuf)
  13204. "Get iCalendar entries from diary entries in buffer FROMBUF.
  13205. This uses the icalendar.el library."
  13206. (let* ((tmpdir temporary-file-directory)
  13207. (tmpfile (make-temp-name
  13208. (expand-file-name "orgics" tmpdir)))
  13209. buf rtn b e)
  13210. (with-current-buffer frombuf
  13211. (icalendar-export-region (point-min) (point-max) tmpfile)
  13212. (setq buf (find-buffer-visiting tmpfile))
  13213. (set-buffer buf)
  13214. (goto-char (point-min))
  13215. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  13216. (setq b (match-beginning 0)))
  13217. (goto-char (point-max))
  13218. (when (re-search-backward "^END:VEVENT" nil t)
  13219. (setq e (match-end 0)))
  13220. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  13221. (kill-buffer buf)
  13222. (delete-file tmpfile)
  13223. rtn))
  13224. (defun org-closest-date (start current prefer)
  13225. "Return closest date to CURRENT starting from START.
  13226. CURRENT and START are both time stamps.
  13227. When PREFER is `past', return a date that is either CURRENT or
  13228. past. When PREFER is `future', return a date that is either
  13229. CURRENT or future.
  13230. Only time stamps with a repeater are modified. Any other time
  13231. stamp stay unchanged. In any case, return value is an absolute
  13232. day number."
  13233. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  13234. ;; No repeater. Do not shift time stamp.
  13235. (time-to-days (org-time-string-to-time start))
  13236. (let ((value (string-to-number (match-string 1 start)))
  13237. (type (match-string 2 start)))
  13238. (if (= 0 value)
  13239. ;; Repeater with a 0-value is considered as void.
  13240. (time-to-days (org-time-string-to-time start))
  13241. (let* ((base (org-date-to-gregorian start))
  13242. (target (org-date-to-gregorian current))
  13243. (sday (calendar-absolute-from-gregorian base))
  13244. (cday (calendar-absolute-from-gregorian target))
  13245. n1 n2)
  13246. ;; If START is already past CURRENT, just return START.
  13247. (if (<= cday sday) sday
  13248. ;; Compute closest date before (N1) and closest date past
  13249. ;; (N2) CURRENT.
  13250. (pcase type
  13251. ("h"
  13252. (let ((missing-hours
  13253. (mod (+ (- (* 24 (- cday sday))
  13254. (nth 2 (org-parse-time-string start)))
  13255. org-extend-today-until)
  13256. value)))
  13257. (setf n1 (if (= missing-hours 0) cday
  13258. (- cday (1+ (/ missing-hours 24)))))
  13259. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  13260. ((or "d" "w")
  13261. (let ((value (if (equal type "w") (* 7 value) value)))
  13262. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  13263. (setf n2 (+ n1 value))))
  13264. ("m"
  13265. (let* ((add-months
  13266. (lambda (d n)
  13267. ;; Add N months to gregorian date D, i.e.,
  13268. ;; a list (MONTH DAY YEAR). Return a valid
  13269. ;; gregorian date.
  13270. (let ((m (+ (nth 0 d) n)))
  13271. (list (mod m 12)
  13272. (nth 1 d)
  13273. (+ (/ m 12) (nth 2 d))))))
  13274. (months ; Complete months to TARGET.
  13275. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  13276. (- (nth 0 target) (nth 0 base))
  13277. ;; If START's day is greater than
  13278. ;; TARGET's, remove incomplete month.
  13279. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  13280. value)
  13281. value))
  13282. (before (funcall add-months base months)))
  13283. (setf n1 (calendar-absolute-from-gregorian before))
  13284. (setf n2
  13285. (calendar-absolute-from-gregorian
  13286. (funcall add-months before value)))))
  13287. (_
  13288. (let* ((d (nth 1 base))
  13289. (m (nth 0 base))
  13290. (y (nth 2 base))
  13291. (years ; Complete years to TARGET.
  13292. (* (/ (- (nth 2 target)
  13293. y
  13294. ;; If START's month and day are
  13295. ;; greater than TARGET's, remove
  13296. ;; incomplete year.
  13297. (if (or (> (nth 0 target) m)
  13298. (and (= (nth 0 target) m)
  13299. (> (nth 1 target) d)))
  13300. 0
  13301. 1))
  13302. value)
  13303. value))
  13304. (before (list m d (+ y years))))
  13305. (setf n1 (calendar-absolute-from-gregorian before))
  13306. (setf n2 (calendar-absolute-from-gregorian
  13307. (list m d (+ (nth 2 before) value)))))))
  13308. ;; Handle PREFER parameter, if any.
  13309. (cond
  13310. ((eq prefer 'past) (if (= cday n2) n2 n1))
  13311. ((eq prefer 'future) (if (= cday n1) n1 n2))
  13312. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  13313. (defun org-date-to-gregorian (d)
  13314. "Turn any specification of date D into a Gregorian date for the calendar."
  13315. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  13316. ((and (listp d) (= (length d) 3)) d)
  13317. ((stringp d)
  13318. (let ((d (org-parse-time-string d)))
  13319. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  13320. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  13321. (defun org-timestamp-up (&optional arg)
  13322. "Increase the date item at the cursor by one.
  13323. If the cursor is on the year, change the year. If it is on the month,
  13324. the day or the time, change that. If the cursor is on the enclosing
  13325. bracket, change the timestamp type.
  13326. With prefix ARG, change by that many units."
  13327. (interactive "p")
  13328. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  13329. (defun org-timestamp-down (&optional arg)
  13330. "Decrease the date item at the cursor by one.
  13331. If the cursor is on the year, change the year. If it is on the month,
  13332. the day or the time, change that. If the cursor is on the enclosing
  13333. bracket, change the timestamp type.
  13334. With prefix ARG, change by that many units."
  13335. (interactive "p")
  13336. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  13337. (defun org-timestamp-up-day (&optional arg)
  13338. "Increase the date in the time stamp by one day.
  13339. With prefix ARG, change that many days."
  13340. (interactive "p")
  13341. (if (and (not (org-at-timestamp-p 'lax))
  13342. (org-at-heading-p))
  13343. (org-todo 'up)
  13344. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  13345. (defun org-timestamp-down-day (&optional arg)
  13346. "Decrease the date in the time stamp by one day.
  13347. With prefix ARG, change that many days."
  13348. (interactive "p")
  13349. (if (and (not (org-at-timestamp-p 'lax))
  13350. (org-at-heading-p))
  13351. (org-todo 'down)
  13352. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  13353. (defun org-at-timestamp-p (&optional extended)
  13354. "Non-nil if point is inside a timestamp.
  13355. By default, the function only consider syntactically valid active
  13356. timestamps. However, the caller may have a broader definition
  13357. for timestamps. As a consequence, optional argument EXTENDED can
  13358. be set to the following values
  13359. `inactive'
  13360. Include also syntactically valid inactive timestamps.
  13361. `agenda'
  13362. Include timestamps allowed in Agenda, i.e., those in
  13363. properties drawers, planning lines and clock lines.
  13364. `lax'
  13365. Ignore context. The function matches any part of the
  13366. document looking like a timestamp. This includes comments,
  13367. example blocks...
  13368. For backward-compatibility with Org 9.0, every other non-nil
  13369. value is equivalent to `inactive'.
  13370. When at a timestamp, return the position of the point as a symbol
  13371. among `bracket', `after', `year', `month', `hour', `minute',
  13372. `day' or a number of character from the last know part of the
  13373. time stamp. If diary sexp timestamps, any point inside the timestamp
  13374. is considered `day' (i.e. only `bracket', `day', and `after' return
  13375. values are possible).
  13376. When matching, the match groups are the following:
  13377. group 1: year, if any
  13378. group 2: month, if any
  13379. group 3: day number, if any
  13380. group 4: day name, if any
  13381. group 5: hours, if any
  13382. group 6: minutes, if any"
  13383. (let* ((regexp
  13384. (if extended
  13385. (if (eq extended 'agenda)
  13386. (rx-to-string
  13387. `(or (regexp ,org-ts-regexp3)
  13388. (regexp ,org-element--timestamp-regexp)))
  13389. org-ts-regexp3)
  13390. org-ts-regexp2))
  13391. (pos (point))
  13392. (match?
  13393. (let ((boundaries (org-in-regexp regexp)))
  13394. (save-match-data
  13395. (cond ((null boundaries) nil)
  13396. ((eq extended 'lax) t)
  13397. (t
  13398. (or (and (eq extended 'agenda)
  13399. (or (org-at-planning-p)
  13400. (org-at-property-p)
  13401. (and (bound-and-true-p
  13402. org-agenda-include-inactive-timestamps)
  13403. (org-at-clock-log-p))))
  13404. (eq 'timestamp
  13405. (save-excursion
  13406. (when (= pos (cdr boundaries)) (forward-char -1))
  13407. (org-element-type (org-element-context)))))))))))
  13408. (cond
  13409. ((not match?) nil)
  13410. ((= pos (match-beginning 0)) 'bracket)
  13411. ;; Distinguish location right before the closing bracket from
  13412. ;; right after it.
  13413. ((= pos (1- (match-end 0))) 'bracket)
  13414. ((= pos (match-end 0)) 'after)
  13415. ((org-pos-in-match-range pos 2) 'year)
  13416. ((org-pos-in-match-range pos 3) 'month)
  13417. ((org-pos-in-match-range pos 7) 'hour)
  13418. ((org-pos-in-match-range pos 8) 'minute)
  13419. ((or (org-pos-in-match-range pos 4)
  13420. (org-pos-in-match-range pos 5)) 'day)
  13421. ((and (or (match-end 8) (match-end 5))
  13422. (> pos (or (match-end 8) (match-end 5)))
  13423. (< pos (match-end 0)))
  13424. (- pos (or (match-end 8) (match-end 5))))
  13425. (t 'day))))
  13426. (defun org-toggle-timestamp-type ()
  13427. "Toggle the type (<active> or [inactive]) of a time stamp."
  13428. (interactive)
  13429. (when (org-at-timestamp-p 'lax)
  13430. (let ((beg (match-beginning 0)) (end (match-end 0))
  13431. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  13432. (save-excursion
  13433. (goto-char beg)
  13434. (while (re-search-forward "[][<>]" end t)
  13435. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  13436. t t)))
  13437. (message "Timestamp is now %sactive"
  13438. (if (equal (char-after beg) ?<) "" "in")))))
  13439. (defun org-at-clock-log-p ()
  13440. "Non-nil if point is on a clock log line."
  13441. (and (org-match-line org-clock-line-re)
  13442. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  13443. (defvar org-clock-history) ; defined in org-clock.el
  13444. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  13445. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  13446. "Change the date in the time stamp at point.
  13447. The date is changed by N times WHAT. WHAT can be `day', `month',
  13448. `year', `hour', or `minute'. If WHAT is not given, the cursor
  13449. position in the timestamp determines what is changed.
  13450. When optional argument UPDOWN is non-nil, minutes are rounded
  13451. according to `org-time-stamp-rounding-minutes'.
  13452. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like
  13453. \"--2d\"."
  13454. (let ((origin (point))
  13455. (timestamp? (org-at-timestamp-p 'lax))
  13456. origin-cat
  13457. with-hm inactive
  13458. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  13459. extra rem
  13460. ts time time0 fixnext clrgx)
  13461. (unless timestamp? (user-error "Not at a timestamp"))
  13462. (if (and (not what) (eq timestamp? 'bracket))
  13463. (org-toggle-timestamp-type)
  13464. ;; Point isn't on brackets. Remember the part of the time-stamp
  13465. ;; the point was in. Indeed, size of time-stamps may change,
  13466. ;; but point must be kept in the same category nonetheless.
  13467. (setq origin-cat timestamp?)
  13468. (when (and (not what) (not (eq timestamp? 'day))
  13469. org-display-custom-times
  13470. (get-text-property (point) 'display)
  13471. (not (get-text-property (1- (point)) 'display)))
  13472. (setq timestamp? 'day))
  13473. (setq timestamp? (or what timestamp?)
  13474. inactive (= (char-after (match-beginning 0)) ?\[)
  13475. ts (match-string 0))
  13476. (replace-match "")
  13477. (when (string-match
  13478. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  13479. ts)
  13480. (setq extra (match-string 1 ts))
  13481. (when suppress-tmp-delay
  13482. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  13483. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  13484. (setq with-hm t))
  13485. (setq time0 (org-parse-time-string ts))
  13486. (when (and updown
  13487. (eq timestamp? 'minute)
  13488. (not current-prefix-arg))
  13489. ;; This looks like s-up and s-down. Change by one rounding step.
  13490. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  13491. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  13492. (setcar (cdr time0) (+ (nth 1 time0)
  13493. (if (> n 0) (- rem) (- dm rem))))))
  13494. (setq time
  13495. (org-encode-time
  13496. (apply #'list
  13497. (or (car time0) 0)
  13498. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  13499. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  13500. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  13501. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  13502. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  13503. (nthcdr 6 time0))))
  13504. (when (and (memq timestamp? '(hour minute))
  13505. extra
  13506. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  13507. (setq extra (org-modify-ts-extra
  13508. extra
  13509. (if (eq timestamp? 'hour) 2 5)
  13510. n dm)))
  13511. (when (integerp timestamp?)
  13512. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  13513. (when (eq what 'calendar)
  13514. (let ((cal-date (org-get-date-from-calendar)))
  13515. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  13516. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  13517. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  13518. (setcar time0 (or (car time0) 0))
  13519. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  13520. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  13521. (setq time (org-encode-time time0))))
  13522. ;; Insert the new time-stamp, and ensure point stays in the same
  13523. ;; category as before (i.e. not after the last position in that
  13524. ;; category).
  13525. (let ((pos (point)))
  13526. ;; Stay before inserted string. `save-excursion' is of no use.
  13527. (setq org-last-changed-timestamp
  13528. (org-insert-time-stamp time with-hm inactive nil nil extra))
  13529. (goto-char pos))
  13530. (save-match-data
  13531. (looking-at org-ts-regexp3)
  13532. (goto-char
  13533. (pcase origin-cat
  13534. ;; `day' category ends before `hour' if any, or at the end
  13535. ;; of the day name.
  13536. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  13537. (`hour (min (match-end 7) origin))
  13538. (`minute (min (1- (match-end 8)) origin))
  13539. ((pred integerp) (min (1- (match-end 0)) origin))
  13540. ;; Point was right after the time-stamp. However, the
  13541. ;; time-stamp length might have changed, so refer to
  13542. ;; (match-end 0) instead.
  13543. (`after (match-end 0))
  13544. ;; `year' and `month' have both fixed size: point couldn't
  13545. ;; have moved into another part.
  13546. (_ origin))))
  13547. ;; Update clock if on a CLOCK line.
  13548. (org-clock-update-time-maybe)
  13549. ;; Maybe adjust the closest clock in `org-clock-history'
  13550. (when org-clock-adjust-closest
  13551. (if (not (and (org-at-clock-log-p)
  13552. (< 1 (length (delq nil (mapcar 'marker-position
  13553. org-clock-history))))))
  13554. (message "No clock to adjust")
  13555. (cond ((save-excursion ; fix previous clock?
  13556. (re-search-backward org-ts-regexp0 nil t)
  13557. (looking-back (concat org-clock-string " \\[")
  13558. (line-beginning-position)))
  13559. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  13560. ((save-excursion ; fix next clock?
  13561. (re-search-backward org-ts-regexp0 nil t)
  13562. (looking-at (concat org-ts-regexp0 "\\] =>")))
  13563. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  13564. (save-window-excursion
  13565. ;; Find closest clock to point, adjust the previous/next one in history
  13566. (let* ((p (save-excursion (org-back-to-heading t)))
  13567. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  13568. (clfixnth
  13569. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  13570. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  13571. (if (not clfixpos)
  13572. (message "No clock to adjust")
  13573. (save-excursion
  13574. (org-goto-marker-or-bmk clfixpos)
  13575. (org-fold-show-subtree)
  13576. (when (re-search-forward clrgx nil t)
  13577. (goto-char (match-beginning 1))
  13578. (let (org-clock-adjust-closest)
  13579. (org-timestamp-change n timestamp? updown))
  13580. (message "Clock adjusted in %s for heading: %s"
  13581. (file-name-nondirectory (buffer-file-name))
  13582. (org-get-heading t t)))))))))
  13583. ;; Try to recenter the calendar window, if any.
  13584. (when (and org-calendar-follow-timestamp-change
  13585. (get-buffer-window "*Calendar*" t)
  13586. (memq timestamp? '(day month year)))
  13587. (org-recenter-calendar (time-to-days time))))))
  13588. (defun org-modify-ts-extra (s pos n dm)
  13589. "Change the different parts of the lead-time and repeat fields in timestamp."
  13590. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  13591. ng h m new rem)
  13592. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  13593. (cond
  13594. ((or (org-pos-in-match-range pos 2)
  13595. (org-pos-in-match-range pos 3))
  13596. (setq m (string-to-number (match-string 3 s))
  13597. h (string-to-number (match-string 2 s)))
  13598. (if (org-pos-in-match-range pos 2)
  13599. (setq h (+ h n))
  13600. (setq n (* dm (with-no-warnings (cl-signum n))))
  13601. (unless (= 0 (setq rem (% m dm)))
  13602. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  13603. (setq m (+ m n)))
  13604. (when (< m 0) (setq m (+ m 60) h (1- h)))
  13605. (when (> m 59) (setq m (- m 60) h (1+ h)))
  13606. (setq h (mod h 24))
  13607. (setq ng 1 new (format "-%02d:%02d" h m)))
  13608. ((org-pos-in-match-range pos 6)
  13609. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  13610. ((org-pos-in-match-range pos 5)
  13611. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  13612. ((org-pos-in-match-range pos 9)
  13613. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  13614. ((org-pos-in-match-range pos 8)
  13615. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  13616. (when ng
  13617. (setq s (concat
  13618. (substring s 0 (match-beginning ng))
  13619. new
  13620. (substring s (match-end ng))))))
  13621. s))
  13622. (defun org-recenter-calendar (d)
  13623. "If the calendar is visible, recenter it to date D."
  13624. (let ((cwin (get-buffer-window "*Calendar*" t)))
  13625. (when cwin
  13626. (let ((calendar-move-hook nil))
  13627. (with-selected-window cwin
  13628. (calendar-goto-date
  13629. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  13630. (defun org-goto-calendar (&optional arg)
  13631. "Go to the Emacs calendar at the current date.
  13632. If there is a time stamp in the current line, go to that date.
  13633. A prefix ARG can be used to force the current date."
  13634. (interactive "P")
  13635. (let ((calendar-move-hook nil)
  13636. (calendar-view-holidays-initially-flag nil)
  13637. (calendar-view-diary-initially-flag nil)
  13638. diff)
  13639. (when (or (org-at-timestamp-p 'lax)
  13640. (org-match-line (concat ".*" org-ts-regexp)))
  13641. (let ((d1 (time-to-days nil))
  13642. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  13643. (setq diff (- d2 d1))))
  13644. (calendar)
  13645. (calendar-goto-today)
  13646. (when (and diff (not arg)) (calendar-forward-day diff))))
  13647. (defun org-get-date-from-calendar ()
  13648. "Return a list (month day year) of date at point in calendar."
  13649. (with-current-buffer "*Calendar*"
  13650. (save-match-data
  13651. (calendar-cursor-to-date))))
  13652. (defun org-date-from-calendar ()
  13653. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  13654. If there is already a time stamp at the cursor position, update it."
  13655. (interactive)
  13656. (if (org-at-timestamp-p 'lax)
  13657. (org-timestamp-change 0 'calendar)
  13658. (let ((cal-date (org-get-date-from-calendar)))
  13659. (org-insert-time-stamp
  13660. (org-encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  13661. (defcustom org-image-actual-width t
  13662. "When non-nil, use the actual width of images when inlining them.
  13663. When set to a number, use imagemagick (when available) to set the
  13664. image's width to this value.
  13665. When set to a number in a list, try to get the width from any
  13666. #+ATTR.* keyword if it matches a width specification like
  13667. #+ATTR_HTML: :width 300px
  13668. and fall back on that number if none is found.
  13669. When set to nil, try to get the width from an #+ATTR.* keyword
  13670. and fall back on the original width if none is found.
  13671. When set to any other non-nil value, always use the image width.
  13672. This requires Emacs >= 24.1, built with imagemagick support."
  13673. :group 'org-appearance
  13674. :version "24.4"
  13675. :package-version '(Org . "8.0")
  13676. :type '(choice
  13677. (const :tag "Use the image width" t)
  13678. (integer :tag "Use a number of pixels")
  13679. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  13680. (const :tag "Use #+ATTR* or don't resize" nil)))
  13681. (defcustom org-agenda-inhibit-startup nil
  13682. "Inhibit startup when preparing agenda buffers.
  13683. When this variable is t, the initialization of the Org agenda
  13684. buffers is inhibited: e.g. the visibility state is not set, the
  13685. tables are not re-aligned, etc."
  13686. :type 'boolean
  13687. :version "24.3"
  13688. :group 'org-agenda)
  13689. (defcustom org-agenda-ignore-properties nil
  13690. "Avoid updating text properties when building the agenda.
  13691. Properties are used to prepare buffers for effort estimates,
  13692. appointments, statistics and subtree-local categories.
  13693. If you don't use these in the agenda, you can add them to this
  13694. list and agenda building will be a bit faster.
  13695. The value is a list, with zero or more of the symbols `effort', `appt',
  13696. `stats' or `category'."
  13697. :type '(set :greedy t
  13698. (const effort)
  13699. (const appt)
  13700. (const stats)
  13701. (const category))
  13702. :version "26.1"
  13703. :package-version '(Org . "8.3")
  13704. :group 'org-agenda)
  13705. ;;;; Files
  13706. (defun org-save-all-org-buffers ()
  13707. "Save all Org buffers without user confirmation."
  13708. (interactive)
  13709. (message "Saving all Org buffers...")
  13710. (save-some-buffers t (lambda () (and (derived-mode-p 'org-mode) t)))
  13711. (when (featurep 'org-id) (org-id-locations-save))
  13712. (message "Saving all Org buffers... done"))
  13713. (defun org-revert-all-org-buffers ()
  13714. "Revert all Org buffers.
  13715. Prompt for confirmation when there are unsaved changes.
  13716. Be sure you know what you are doing before letting this function
  13717. overwrite your changes.
  13718. This function is useful in a setup where one tracks Org files
  13719. with a version control system, to revert on one machine after pulling
  13720. changes from another. I believe the procedure must be like this:
  13721. 1. \\[org-save-all-org-buffers]
  13722. 2. Pull changes from the other machine, resolve conflicts
  13723. 3. \\[org-revert-all-org-buffers]"
  13724. (interactive)
  13725. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  13726. (user-error "Abort"))
  13727. (save-excursion
  13728. (save-window-excursion
  13729. (dolist (b (buffer-list))
  13730. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  13731. (with-current-buffer b buffer-file-name))
  13732. (pop-to-buffer-same-window b)
  13733. (revert-buffer t 'no-confirm)))
  13734. (when (and (featurep 'org-id) org-id-track-globally)
  13735. (org-id-locations-load)))))
  13736. ;;;; Agenda files
  13737. ;;;###autoload
  13738. (defun org-switchb (&optional arg)
  13739. "Switch between Org buffers.
  13740. With `\\[universal-argument]' prefix, restrict available buffers to files.
  13741. With `\\[universal-argument] \\[universal-argument]' \
  13742. prefix, restrict available buffers to agenda files."
  13743. (interactive "P")
  13744. (let ((blist (org-buffer-list
  13745. (cond ((equal arg '(4)) 'files)
  13746. ((equal arg '(16)) 'agenda)))))
  13747. (pop-to-buffer-same-window
  13748. (completing-read "Org buffer: "
  13749. (mapcar #'list (mapcar #'buffer-name blist))
  13750. nil t))))
  13751. (defun org-agenda-files (&optional unrestricted archives)
  13752. "Get the list of agenda files.
  13753. Optional UNRESTRICTED means return the full list even if a restriction
  13754. is currently in place.
  13755. When ARCHIVES is t, include all archive files that are really being
  13756. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  13757. `org-agenda-archives-mode' is t."
  13758. (let ((files
  13759. (cond
  13760. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  13761. ((stringp org-agenda-files) (org-read-agenda-file-list))
  13762. ((listp org-agenda-files) org-agenda-files)
  13763. (t (error "Invalid value of `org-agenda-files'")))))
  13764. (setq files (apply 'append
  13765. (mapcar (lambda (f)
  13766. (if (file-directory-p f)
  13767. (directory-files
  13768. f t org-agenda-file-regexp)
  13769. (list (expand-file-name f org-directory))))
  13770. files)))
  13771. (when org-agenda-skip-unavailable-files
  13772. (setq files (delq nil
  13773. (mapcar (lambda (file)
  13774. (and (file-readable-p file) file))
  13775. files))))
  13776. (when (or (eq archives t)
  13777. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  13778. (setq files (org-add-archive-files files)))
  13779. files))
  13780. (defun org-agenda-file-p (&optional file)
  13781. "Return non-nil, if FILE is an agenda file.
  13782. If FILE is omitted, use the file associated with the current
  13783. buffer."
  13784. (let ((fname (or file (buffer-file-name))))
  13785. (and fname
  13786. (member (file-truename fname)
  13787. (mapcar #'file-truename (org-agenda-files t))))))
  13788. (defun org-edit-agenda-file-list ()
  13789. "Edit the list of agenda files.
  13790. Depending on setup, this either uses customize to edit the variable
  13791. `org-agenda-files', or it visits the file that is holding the list. In the
  13792. latter case, the buffer is set up in a way that saving it automatically kills
  13793. the buffer and restores the previous window configuration."
  13794. (interactive)
  13795. (if (stringp org-agenda-files)
  13796. (let ((cw (current-window-configuration)))
  13797. (find-file org-agenda-files)
  13798. (setq-local org-window-configuration cw)
  13799. (add-hook 'after-save-hook
  13800. (lambda ()
  13801. (set-window-configuration
  13802. (prog1 org-window-configuration
  13803. (kill-buffer (current-buffer))))
  13804. (org-install-agenda-files-menu)
  13805. (message "New agenda file list installed"))
  13806. nil 'local)
  13807. (message "%s" (substitute-command-keys
  13808. "Edit list and finish with \\[save-buffer]")))
  13809. (customize-variable 'org-agenda-files)))
  13810. (defun org-store-new-agenda-file-list (list)
  13811. "Set new value for the agenda file list and save it correctly."
  13812. (if (stringp org-agenda-files)
  13813. (let ((fe (org-read-agenda-file-list t)) b u)
  13814. (while (setq b (find-buffer-visiting org-agenda-files))
  13815. (kill-buffer b))
  13816. (with-temp-file org-agenda-files
  13817. (insert
  13818. (mapconcat
  13819. (lambda (f) ;; Keep un-expanded entries.
  13820. (if (setq u (assoc f fe))
  13821. (cdr u)
  13822. f))
  13823. list "\n")
  13824. "\n")))
  13825. (let ((org-mode-hook nil) (org-inhibit-startup t)
  13826. (org-insert-mode-line-in-empty-file nil))
  13827. (setq org-agenda-files list)
  13828. (customize-save-variable 'org-agenda-files org-agenda-files))))
  13829. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  13830. "Read the list of agenda files from a file.
  13831. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  13832. filenames, used by `org-store-new-agenda-file-list' to write back
  13833. un-expanded file names."
  13834. (when (file-directory-p org-agenda-files)
  13835. (error "`org-agenda-files' cannot be a single directory"))
  13836. (when (stringp org-agenda-files)
  13837. (with-temp-buffer
  13838. (insert-file-contents org-agenda-files)
  13839. (mapcar
  13840. (lambda (f)
  13841. (let ((e (expand-file-name (substitute-in-file-name f)
  13842. org-directory)))
  13843. (if pair-with-expansion
  13844. (cons e f)
  13845. e)))
  13846. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  13847. ;;;###autoload
  13848. (defun org-cycle-agenda-files ()
  13849. "Cycle through the files in `org-agenda-files'.
  13850. If the current buffer visits an agenda file, find the next one in the list.
  13851. If the current buffer does not, find the first agenda file."
  13852. (interactive)
  13853. (let* ((fs (or (org-agenda-files t)
  13854. (user-error "No agenda files")))
  13855. (files (copy-sequence fs))
  13856. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  13857. file)
  13858. (when tcf
  13859. (while (and (setq file (pop files))
  13860. (not (equal (file-truename file) tcf)))))
  13861. (find-file (car (or files fs)))
  13862. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  13863. (defun org-agenda-file-to-front (&optional to-end)
  13864. "Move/add the current file to the top of the agenda file list.
  13865. If the file is not present in the list, it is added to the front. If it is
  13866. present, it is moved there. With optional argument TO-END, add/move to the
  13867. end of the list."
  13868. (interactive "P")
  13869. (let ((org-agenda-skip-unavailable-files nil)
  13870. (file-alist (mapcar (lambda (x)
  13871. (cons (file-truename x) x))
  13872. (org-agenda-files t)))
  13873. (ctf (file-truename
  13874. (or buffer-file-name
  13875. (user-error "Please save the current buffer to a file"))))
  13876. x had)
  13877. (setq x (assoc ctf file-alist) had x)
  13878. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  13879. (if to-end
  13880. (setq file-alist (append (delq x file-alist) (list x)))
  13881. (setq file-alist (cons x (delq x file-alist))))
  13882. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  13883. (org-install-agenda-files-menu)
  13884. (message "File %s to %s of agenda file list"
  13885. (if had "moved" "added") (if to-end "end" "front"))))
  13886. (defun org-remove-file (&optional file)
  13887. "Remove current file from the list of files in variable `org-agenda-files'.
  13888. These are the files which are being checked for agenda entries.
  13889. Optional argument FILE means use this file instead of the current."
  13890. (interactive)
  13891. (let* ((org-agenda-skip-unavailable-files nil)
  13892. (file (or file buffer-file-name
  13893. (user-error "Current buffer does not visit a file")))
  13894. (true-file (file-truename file))
  13895. (afile (abbreviate-file-name file))
  13896. (files (delq nil (mapcar
  13897. (lambda (x)
  13898. (unless (equal true-file
  13899. (file-truename x))
  13900. x))
  13901. (org-agenda-files t)))))
  13902. (if (not (= (length files) (length (org-agenda-files t))))
  13903. (progn
  13904. (org-store-new-agenda-file-list files)
  13905. (org-install-agenda-files-menu)
  13906. (message "Removed from Org Agenda list: %s" afile))
  13907. (message "File was not in list: %s (not removed)" afile))))
  13908. (defun org-file-menu-entry (file)
  13909. (vector file (list 'find-file file) t))
  13910. (defun org-check-agenda-file (file)
  13911. "Make sure FILE exists. If not, ask user what to do."
  13912. (unless (file-exists-p file)
  13913. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  13914. (abbreviate-file-name file))
  13915. (let ((r (downcase (read-char-exclusive))))
  13916. (cond
  13917. ((equal r ?r)
  13918. (org-remove-file file)
  13919. (throw 'nextfile t))
  13920. (t (user-error "Abort"))))))
  13921. (defun org-get-agenda-file-buffer (file)
  13922. "Get an agenda buffer visiting FILE.
  13923. If the buffer needs to be created, add it to the list of buffers
  13924. which might be released later."
  13925. (let ((buf (org-find-base-buffer-visiting file)))
  13926. (if buf
  13927. buf ; just return it
  13928. ;; Make a new buffer and remember it
  13929. (setq buf (find-file-noselect file))
  13930. (when buf (push buf org-agenda-new-buffers))
  13931. buf)))
  13932. (defun org-release-buffers (blist)
  13933. "Release all buffers in list, asking the user for confirmation when needed.
  13934. When a buffer is unmodified, it is just killed. When modified, it is saved
  13935. \(if the user agrees) and then killed."
  13936. (let (file)
  13937. (dolist (buf blist)
  13938. (setq file (buffer-file-name buf))
  13939. (when (and (buffer-modified-p buf)
  13940. file
  13941. (y-or-n-p (format "Save file %s? " file)))
  13942. (with-current-buffer buf (save-buffer)))
  13943. (kill-buffer buf))))
  13944. (defun org-agenda-prepare-buffers (files)
  13945. "Create buffers for all agenda files, protect archived trees and comments."
  13946. (interactive)
  13947. (let ((inhibit-read-only t)
  13948. (org-inhibit-startup org-agenda-inhibit-startup)
  13949. ;; Do not refresh list of agenda files in the menu when
  13950. ;; opening every new file.
  13951. (org-agenda-file-menu-enabled nil))
  13952. (setq org-tag-alist-for-agenda nil
  13953. org-tag-groups-alist-for-agenda nil)
  13954. (dolist (file files)
  13955. (catch 'nextfile
  13956. (with-current-buffer
  13957. (if (bufferp file)
  13958. file
  13959. (org-check-agenda-file file)
  13960. (org-get-agenda-file-buffer file))
  13961. (org-with-wide-buffer
  13962. (org-set-regexps-and-options 'tags-only)
  13963. (or (memq 'category org-agenda-ignore-properties)
  13964. (org-refresh-category-properties))
  13965. (or (memq 'stats org-agenda-ignore-properties)
  13966. (org-refresh-stats-properties))
  13967. (or (memq 'effort org-agenda-ignore-properties)
  13968. (unless org-element-use-cache
  13969. (org-refresh-effort-properties)))
  13970. (or (memq 'appt org-agenda-ignore-properties)
  13971. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  13972. (dolist (el org-todo-keywords-1)
  13973. (unless (member el org-todo-keywords-for-agenda)
  13974. (push el org-todo-keywords-for-agenda)))
  13975. (dolist (el org-done-keywords)
  13976. (unless (member el org-done-keywords-for-agenda)
  13977. (push el org-done-keywords-for-agenda)))
  13978. (setq org-todo-keyword-alist-for-agenda
  13979. (org--tag-add-to-alist
  13980. org-todo-key-alist
  13981. org-todo-keyword-alist-for-agenda))
  13982. (setq org-tag-alist-for-agenda
  13983. (org--tag-add-to-alist
  13984. org-current-tag-alist
  13985. org-tag-alist-for-agenda))
  13986. ;; Merge current file's tag groups into global
  13987. ;; `org-tag-groups-alist-for-agenda'.
  13988. (when org-group-tags
  13989. (dolist (alist org-tag-groups-alist)
  13990. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  13991. (if old
  13992. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  13993. (push alist org-tag-groups-alist-for-agenda)))))))))
  13994. ;; Refresh the menu once after loading all the agenda buffers.
  13995. (when org-agenda-file-menu-enabled
  13996. (org-install-agenda-files-menu))))
  13997. ;;;; CDLaTeX minor mode
  13998. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  13999. "Keymap for the minor `org-cdlatex-mode'.")
  14000. (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
  14001. (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
  14002. (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
  14003. (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
  14004. (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
  14005. (defvar org-cdlatex-texmathp-advice-is-done nil
  14006. "Flag remembering if we have applied the advice to texmathp already.")
  14007. (define-minor-mode org-cdlatex-mode
  14008. "Toggle the minor `org-cdlatex-mode'.
  14009. This mode supports entering LaTeX environment and math in LaTeX fragments
  14010. in Org mode.
  14011. \\{org-cdlatex-mode-map}"
  14012. :lighter " OCDL"
  14013. (when org-cdlatex-mode
  14014. (require 'cdlatex)
  14015. (run-hooks 'cdlatex-mode-hook)
  14016. (cdlatex-compute-tables))
  14017. (unless org-cdlatex-texmathp-advice-is-done
  14018. (setq org-cdlatex-texmathp-advice-is-done t)
  14019. (advice-add 'texmathp :around #'org--math-always-on)))
  14020. (defun org--math-always-on (orig-fun &rest args)
  14021. "Always return t in Org buffers.
  14022. This is because we want to insert math symbols without dollars even outside
  14023. the LaTeX math segments. If Org mode thinks that point is actually inside
  14024. an embedded LaTeX fragment, let `texmathp' do its job.
  14025. `\\[org-cdlatex-mode-map]'"
  14026. (interactive)
  14027. (cond
  14028. ((not (derived-mode-p 'org-mode)) (apply orig-fun args))
  14029. ((eq this-command 'cdlatex-math-symbol)
  14030. (setq texmathp-why '("cdlatex-math-symbol in org-mode" . 0))
  14031. t)
  14032. (t
  14033. (let ((p (org-inside-LaTeX-fragment-p)))
  14034. (when p ;; FIXME: Shouldn't we return t when `p' is nil?
  14035. (if (member (car p)
  14036. (plist-get org-format-latex-options :matchers))
  14037. (progn
  14038. (setq texmathp-why '("Org mode embedded math" . 0))
  14039. t)
  14040. (apply orig-fun args)))))))
  14041. (defun turn-on-org-cdlatex ()
  14042. "Unconditionally turn on `org-cdlatex-mode'."
  14043. (org-cdlatex-mode 1))
  14044. (defun org-try-cdlatex-tab ()
  14045. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  14046. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  14047. - inside a LaTeX fragment, or
  14048. - after the first word in a line, where an abbreviation expansion could
  14049. insert a LaTeX environment."
  14050. (when org-cdlatex-mode
  14051. (cond
  14052. ;; Before any word on the line: No expansion possible.
  14053. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  14054. ;; Just after first word on the line: Expand it. Make sure it
  14055. ;; cannot happen on headlines, though.
  14056. ((save-excursion
  14057. (skip-chars-backward "a-zA-Z0-9*")
  14058. (skip-chars-backward " \t")
  14059. (and (bolp) (not (org-at-heading-p))))
  14060. (cdlatex-tab) t)
  14061. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  14062. (defun org-cdlatex-underscore-caret (&optional _arg)
  14063. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  14064. Revert to the normal definition outside of these fragments."
  14065. (interactive "P")
  14066. (if (org-inside-LaTeX-fragment-p)
  14067. (call-interactively 'cdlatex-sub-superscript)
  14068. (let (org-cdlatex-mode)
  14069. (call-interactively (key-binding (vector last-input-event))))))
  14070. (defun org-cdlatex-math-modify (&optional _arg)
  14071. "Execute `cdlatex-math-modify' in LaTeX fragments.
  14072. Revert to the normal definition outside of these fragments."
  14073. (interactive "P")
  14074. (if (org-inside-LaTeX-fragment-p)
  14075. (call-interactively 'cdlatex-math-modify)
  14076. (let (org-cdlatex-mode)
  14077. (call-interactively (key-binding (vector last-input-event))))))
  14078. (defun org-cdlatex-environment-indent (&optional environment item)
  14079. "Execute `cdlatex-environment' and indent the inserted environment.
  14080. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  14081. The inserted environment is indented to current indentation
  14082. unless point is at the beginning of the line, in which the
  14083. environment remains unintended."
  14084. (interactive)
  14085. ;; cdlatex-environment always return nil. Therefore, capture output
  14086. ;; first and determine if an environment was selected.
  14087. (let* ((beg (point-marker))
  14088. (end (copy-marker (point) t))
  14089. (inserted (progn
  14090. (ignore-errors (cdlatex-environment environment item))
  14091. (< beg end)))
  14092. ;; Figure out how many lines to move forward after the
  14093. ;; environment has been inserted.
  14094. (lines (when inserted
  14095. (save-excursion
  14096. (- (cl-loop while (< beg (point))
  14097. with x = 0
  14098. do (forward-line -1)
  14099. (cl-incf x)
  14100. finally return x)
  14101. (if (progn (goto-char beg)
  14102. (and (progn (skip-chars-forward " \t") (eolp))
  14103. (progn (skip-chars-backward " \t") (bolp))))
  14104. 1 0)))))
  14105. (env (org-trim (delete-and-extract-region beg end))))
  14106. (when inserted
  14107. ;; Get indentation of next line unless at column 0.
  14108. (let ((ind (if (bolp) 0
  14109. (save-excursion
  14110. (org-return t)
  14111. (prog1 (current-indentation)
  14112. (when (progn (skip-chars-forward " \t") (eolp))
  14113. (delete-region beg (point)))))))
  14114. (bol (progn (skip-chars-backward " \t") (bolp))))
  14115. ;; Insert a newline before environment unless at column zero
  14116. ;; to "escape" the current line. Insert a newline if
  14117. ;; something is one the same line as \end{ENVIRONMENT}.
  14118. (insert
  14119. (concat (unless bol "\n") env
  14120. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  14121. (unless (zerop ind)
  14122. (save-excursion
  14123. (goto-char beg)
  14124. (while (< (point) end)
  14125. (unless (eolp) (indent-line-to ind))
  14126. (forward-line))))
  14127. (goto-char beg)
  14128. (forward-line lines)
  14129. (indent-line-to ind)))
  14130. (set-marker beg nil)
  14131. (set-marker end nil)))
  14132. ;;;; LaTeX fragments
  14133. (defun org-inside-LaTeX-fragment-p ()
  14134. "Test if point is inside a LaTeX fragment.
  14135. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  14136. sequence appearing also before point.
  14137. Even though the matchers for math are configurable, this function assumes
  14138. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  14139. delimiters are skipped when they have been removed by customization.
  14140. The return value is nil, or a cons cell with the delimiter and the
  14141. position of this delimiter.
  14142. This function does a reasonably good job, but can locally be fooled by
  14143. for example currency specifications. For example it will assume being in
  14144. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  14145. fragments that are properly closed, but during editing, we have to live
  14146. with the uncertainty caused by missing closing delimiters. This function
  14147. looks only before point, not after."
  14148. (catch 'exit
  14149. (let ((pos (point))
  14150. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  14151. (lim (progn
  14152. (re-search-backward (concat "^\\(" paragraph-start "\\)") nil
  14153. 'move)
  14154. (point)))
  14155. dd-on str (start 0) m re)
  14156. (goto-char pos)
  14157. (when dodollar
  14158. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  14159. re (nth 1 (assoc "$" org-latex-regexps)))
  14160. (while (string-match re str start)
  14161. (cond
  14162. ((= (match-end 0) (length str))
  14163. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  14164. ((= (match-end 0) (- (length str) 5))
  14165. (throw 'exit nil))
  14166. (t (setq start (match-end 0))))))
  14167. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  14168. (goto-char pos)
  14169. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  14170. (and (match-beginning 2) (throw 'exit nil))
  14171. ;; count $$
  14172. (while (re-search-backward "\\$\\$" lim t)
  14173. (setq dd-on (not dd-on)))
  14174. (goto-char pos)
  14175. (when dd-on (cons "$$" m))))))
  14176. (defun org-inside-latex-macro-p ()
  14177. "Is point inside a LaTeX macro or its arguments?"
  14178. (save-match-data
  14179. (org-in-regexp
  14180. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  14181. (defun org--make-preview-overlay (beg end image &optional imagetype)
  14182. "Build an overlay between BEG and END using IMAGE file.
  14183. Argument IMAGETYPE is the extension of the displayed image,
  14184. as a string. It defaults to \"png\"."
  14185. (let ((ov (make-overlay beg end))
  14186. (imagetype (or (intern imagetype) 'png)))
  14187. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  14188. (overlay-put ov 'evaporate t)
  14189. (overlay-put ov
  14190. 'modification-hooks
  14191. (list (lambda (o _flag _beg _end &optional _l)
  14192. (delete-overlay o))))
  14193. (overlay-put ov
  14194. 'display
  14195. (list 'image :type imagetype :file image :ascent 'center))))
  14196. (defun org-clear-latex-preview (&optional beg end)
  14197. "Remove all overlays with LaTeX fragment images in current buffer.
  14198. When optional arguments BEG and END are non-nil, remove all
  14199. overlays between them instead. Return a non-nil value when some
  14200. overlays were removed, nil otherwise."
  14201. (let ((overlays
  14202. (cl-remove-if-not
  14203. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  14204. (overlays-in (or beg (point-min)) (or end (point-max))))))
  14205. (mapc #'delete-overlay overlays)
  14206. overlays))
  14207. (defun org--latex-preview-region (beg end)
  14208. "Preview LaTeX fragments between BEG and END.
  14209. BEG and END are buffer positions."
  14210. (let ((file (buffer-file-name (buffer-base-buffer))))
  14211. (save-excursion
  14212. (org-format-latex
  14213. (concat org-preview-latex-image-directory "org-ltximg")
  14214. beg end
  14215. ;; Emacs cannot overlay images from remote hosts. Create it in
  14216. ;; `temporary-file-directory' instead.
  14217. (if (or (not file) (file-remote-p file))
  14218. temporary-file-directory
  14219. default-directory)
  14220. 'overlays nil 'forbuffer org-preview-latex-default-process))))
  14221. (defun org-latex-preview (&optional arg)
  14222. "Toggle preview of the LaTeX fragment at point.
  14223. If the cursor is on a LaTeX fragment, create the image and
  14224. overlay it over the source code, if there is none. Remove it
  14225. otherwise. If there is no fragment at point, display images for
  14226. all fragments in the current section. With an active region,
  14227. display images for all fragments in the region.
  14228. With a `\\[universal-argument]' prefix argument ARG, clear images \
  14229. for all fragments
  14230. in the current section.
  14231. With a `\\[universal-argument] \\[universal-argument]' prefix \
  14232. argument ARG, display image for all
  14233. fragments in the buffer.
  14234. With a `\\[universal-argument] \\[universal-argument] \
  14235. \\[universal-argument]' prefix argument ARG, clear image for all
  14236. fragments in the buffer."
  14237. (interactive "P")
  14238. (cond
  14239. ((not (display-graphic-p)) nil)
  14240. ;; Clear whole buffer.
  14241. ((equal arg '(64))
  14242. (org-clear-latex-preview (point-min) (point-max))
  14243. (message "LaTeX previews removed from buffer"))
  14244. ;; Preview whole buffer.
  14245. ((equal arg '(16))
  14246. (message "Creating LaTeX previews in buffer...")
  14247. (org--latex-preview-region (point-min) (point-max))
  14248. (message "Creating LaTeX previews in buffer... done."))
  14249. ;; Clear current section.
  14250. ((equal arg '(4))
  14251. (org-clear-latex-preview
  14252. (if (use-region-p)
  14253. (region-beginning)
  14254. (if (org-before-first-heading-p) (point-min)
  14255. (save-excursion
  14256. (org-with-limited-levels (org-back-to-heading t) (point)))))
  14257. (if (use-region-p)
  14258. (region-end)
  14259. (org-with-limited-levels (org-entry-end-position)))))
  14260. ((use-region-p)
  14261. (message "Creating LaTeX previews in region...")
  14262. (org--latex-preview-region (region-beginning) (region-end))
  14263. (message "Creating LaTeX previews in region... done."))
  14264. ;; Toggle preview on LaTeX code at point.
  14265. ((let ((datum (org-element-context)))
  14266. (and (memq (org-element-type datum) '(latex-environment latex-fragment))
  14267. (let ((beg (org-element-property :begin datum))
  14268. (end (org-element-property :end datum)))
  14269. (if (org-clear-latex-preview beg end)
  14270. (message "LaTeX preview removed")
  14271. (message "Creating LaTeX preview...")
  14272. (org--latex-preview-region beg end)
  14273. (message "Creating LaTeX preview... done."))
  14274. t))))
  14275. ;; Preview current section.
  14276. (t
  14277. (let ((beg (if (org-before-first-heading-p) (point-min)
  14278. (save-excursion
  14279. (org-with-limited-levels (org-back-to-heading t) (point)))))
  14280. (end (org-with-limited-levels (org-entry-end-position))))
  14281. (message "Creating LaTeX previews in section...")
  14282. (org--latex-preview-region beg end)
  14283. (message "Creating LaTeX previews in section... done.")))))
  14284. (defun org-format-latex
  14285. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  14286. "Replace LaTeX fragments with links to an image.
  14287. The function takes care of creating the replacement image.
  14288. Only consider fragments between BEG and END when those are
  14289. provided.
  14290. When optional argument OVERLAYS is non-nil, display the image on
  14291. top of the fragment instead of replacing it.
  14292. PROCESSING-TYPE is the conversion method to use, as a symbol.
  14293. Some of the options can be changed using the variable
  14294. `org-format-latex-options', which see."
  14295. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  14296. (unless (eq processing-type 'verbatim)
  14297. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  14298. (cnt 0)
  14299. checkdir-flag)
  14300. (goto-char (or beg (point-min)))
  14301. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  14302. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  14303. (overlay-recenter (or end (point-max))))
  14304. (while (re-search-forward math-regexp end t)
  14305. (unless (and overlays
  14306. (eq (get-char-property (point) 'org-overlay-type)
  14307. 'org-latex-overlay))
  14308. (let* ((context (org-element-context))
  14309. (type (org-element-type context)))
  14310. (when (memq type '(latex-environment latex-fragment))
  14311. (let ((block-type (eq type 'latex-environment))
  14312. (value (org-element-property :value context))
  14313. (beg (org-element-property :begin context))
  14314. (end (save-excursion
  14315. (goto-char (org-element-property :end context))
  14316. (skip-chars-backward " \r\t\n")
  14317. (point))))
  14318. (cond
  14319. ((eq processing-type 'mathjax)
  14320. ;; Prepare for MathJax processing.
  14321. (if (not (string-match "\\`\\$\\$?" value))
  14322. (goto-char end)
  14323. (delete-region beg end)
  14324. (if (string= (match-string 0 value) "$$")
  14325. (insert "\\[" (substring value 2 -2) "\\]")
  14326. (insert "\\(" (substring value 1 -1) "\\)"))))
  14327. ((eq processing-type 'html)
  14328. (goto-char beg)
  14329. (delete-region beg end)
  14330. (insert (org-format-latex-as-html value)))
  14331. ((assq processing-type org-preview-latex-process-alist)
  14332. ;; Process to an image.
  14333. (cl-incf cnt)
  14334. (goto-char beg)
  14335. (let* ((processing-info
  14336. (cdr (assq processing-type org-preview-latex-process-alist)))
  14337. (face (face-at-point))
  14338. ;; Get the colors from the face at point.
  14339. (fg
  14340. (let ((color (plist-get org-format-latex-options
  14341. :foreground)))
  14342. (if forbuffer
  14343. (cond
  14344. ((eq color 'auto)
  14345. (face-attribute face :foreground nil 'default))
  14346. ((eq color 'default)
  14347. (face-attribute 'default :foreground nil))
  14348. (t color))
  14349. color)))
  14350. (bg
  14351. (let ((color (plist-get org-format-latex-options
  14352. :background)))
  14353. (if forbuffer
  14354. (cond
  14355. ((eq color 'auto)
  14356. (face-attribute face :background nil 'default))
  14357. ((eq color 'default)
  14358. (face-attribute 'default :background nil))
  14359. (t color))
  14360. color)))
  14361. (hash (sha1 (prin1-to-string
  14362. (list org-format-latex-header
  14363. org-latex-default-packages-alist
  14364. org-latex-packages-alist
  14365. org-format-latex-options
  14366. forbuffer value fg bg))))
  14367. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  14368. (absprefix (expand-file-name prefix dir))
  14369. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  14370. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  14371. (sep (and block-type "\n\n"))
  14372. (link (concat sep "[[file:" linkfile "]]" sep))
  14373. (options
  14374. (org-combine-plists
  14375. org-format-latex-options
  14376. `(:foreground ,fg :background ,bg))))
  14377. (when msg (message msg cnt))
  14378. (unless checkdir-flag ; Ensure the directory exists.
  14379. (setq checkdir-flag t)
  14380. (let ((todir (file-name-directory absprefix)))
  14381. (unless (file-directory-p todir)
  14382. (make-directory todir t))))
  14383. (unless (file-exists-p movefile)
  14384. (org-create-formula-image
  14385. value movefile options forbuffer processing-type))
  14386. (if overlays
  14387. (progn
  14388. (dolist (o (overlays-in beg end))
  14389. (when (eq (overlay-get o 'org-overlay-type)
  14390. 'org-latex-overlay)
  14391. (delete-overlay o)))
  14392. (org--make-preview-overlay beg end movefile imagetype)
  14393. (goto-char end))
  14394. (delete-region beg end)
  14395. (insert
  14396. (org-add-props link
  14397. (list 'org-latex-src
  14398. (replace-regexp-in-string "\"" "" value)
  14399. 'org-latex-src-embed-type
  14400. (if block-type 'paragraph 'character)))))))
  14401. ((eq processing-type 'mathml)
  14402. ;; Process to MathML.
  14403. (unless (org-format-latex-mathml-available-p)
  14404. (user-error "LaTeX to MathML converter not configured"))
  14405. (cl-incf cnt)
  14406. (when msg (message msg cnt))
  14407. (goto-char beg)
  14408. (delete-region beg end)
  14409. (insert (org-format-latex-as-mathml
  14410. value block-type prefix dir)))
  14411. (t
  14412. (error "Unknown conversion process %s for LaTeX fragments"
  14413. processing-type)))))))))))
  14414. (defun org-create-math-formula (latex-frag &optional mathml-file)
  14415. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  14416. Use `org-latex-to-mathml-convert-command'. If the conversion is
  14417. successful, return the portion between \"<math...> </math>\"
  14418. elements otherwise return nil. When MATHML-FILE is specified,
  14419. write the results in to that file. When invoked as an
  14420. interactive command, prompt for LATEX-FRAG, with initial value
  14421. set to the current active region and echo the results for user
  14422. inspection."
  14423. (interactive (list (let ((frag (when (org-region-active-p)
  14424. (buffer-substring-no-properties
  14425. (region-beginning) (region-end)))))
  14426. (read-string "LaTeX Fragment: " frag nil frag))))
  14427. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  14428. (let* ((tmp-in-file
  14429. (let ((file (file-relative-name
  14430. (make-temp-name (expand-file-name "ltxmathml-in")))))
  14431. (write-region latex-frag nil file)
  14432. file))
  14433. (tmp-out-file (file-relative-name
  14434. (make-temp-name (expand-file-name "ltxmathml-out"))))
  14435. (cmd (format-spec
  14436. org-latex-to-mathml-convert-command
  14437. `((?j . ,(and org-latex-to-mathml-jar-file
  14438. (shell-quote-argument
  14439. (expand-file-name
  14440. org-latex-to-mathml-jar-file))))
  14441. (?I . ,(shell-quote-argument tmp-in-file))
  14442. (?i . ,latex-frag)
  14443. (?o . ,(shell-quote-argument tmp-out-file)))))
  14444. mathml shell-command-output)
  14445. (when (called-interactively-p 'any)
  14446. (unless (org-format-latex-mathml-available-p)
  14447. (user-error "LaTeX to MathML converter not configured")))
  14448. (message "Running %s" cmd)
  14449. (setq shell-command-output (shell-command-to-string cmd))
  14450. (setq mathml
  14451. (when (file-readable-p tmp-out-file)
  14452. (with-current-buffer (find-file-noselect tmp-out-file t)
  14453. (goto-char (point-min))
  14454. (when (re-search-forward
  14455. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  14456. (regexp-quote
  14457. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  14458. nil t)
  14459. (prog1 (match-string 0) (kill-buffer))))))
  14460. (cond
  14461. (mathml
  14462. (setq mathml
  14463. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  14464. (when mathml-file
  14465. (write-region mathml nil mathml-file))
  14466. (when (called-interactively-p 'any)
  14467. (message mathml)))
  14468. ((warn "LaTeX to MathML conversion failed")
  14469. (message shell-command-output)))
  14470. (delete-file tmp-in-file)
  14471. (when (file-exists-p tmp-out-file)
  14472. (delete-file tmp-out-file))
  14473. mathml))
  14474. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  14475. prefix &optional dir)
  14476. "Use `org-create-math-formula' but check local cache first."
  14477. (let* ((absprefix (expand-file-name prefix dir))
  14478. (print-length nil) (print-level nil)
  14479. (formula-id (concat
  14480. "formula-"
  14481. (sha1
  14482. (prin1-to-string
  14483. (list latex-frag
  14484. org-latex-to-mathml-convert-command)))))
  14485. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  14486. (formula-cache-dir (file-name-directory formula-cache)))
  14487. (unless (file-directory-p formula-cache-dir)
  14488. (make-directory formula-cache-dir t))
  14489. (unless (file-exists-p formula-cache)
  14490. (org-create-math-formula latex-frag formula-cache))
  14491. (if (file-exists-p formula-cache)
  14492. ;; Successful conversion. Return the link to MathML file.
  14493. (org-add-props
  14494. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  14495. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  14496. 'org-latex-src-embed-type (if latex-frag-type
  14497. 'paragraph 'character)))
  14498. ;; Failed conversion. Return the LaTeX fragment verbatim
  14499. latex-frag)))
  14500. (defun org-format-latex-as-html (latex-fragment)
  14501. "Convert LATEX-FRAGMENT to HTML.
  14502. This uses `org-latex-to-html-convert-command', which see."
  14503. (let ((cmd (format-spec org-latex-to-html-convert-command
  14504. `((?i . ,latex-fragment)))))
  14505. (message "Running %s" cmd)
  14506. (shell-command-to-string cmd)))
  14507. (defun org--get-display-dpi ()
  14508. "Get the DPI of the display.
  14509. The function assumes that the display has the same pixel width in
  14510. the horizontal and vertical directions."
  14511. (if (display-graphic-p)
  14512. (round (/ (display-pixel-height)
  14513. (/ (display-mm-height) 25.4)))
  14514. (error "Attempt to calculate the dpi of a non-graphic display")))
  14515. (defun org-create-formula-image
  14516. (string tofile options buffer &optional processing-type)
  14517. "Create an image from LaTeX source using external processes.
  14518. The LaTeX STRING is saved to a temporary LaTeX file, then
  14519. converted to an image file by process PROCESSING-TYPE defined in
  14520. `org-preview-latex-process-alist'. A nil value defaults to
  14521. `org-preview-latex-default-process'.
  14522. The generated image file is eventually moved to TOFILE.
  14523. The OPTIONS argument controls the size, foreground color and
  14524. background color of the generated image.
  14525. When BUFFER non-nil, this function is used for LaTeX previewing.
  14526. Otherwise, it is used to deal with LaTeX snippets showed in
  14527. a HTML file."
  14528. (let* ((processing-type (or processing-type
  14529. org-preview-latex-default-process))
  14530. (processing-info
  14531. (cdr (assq processing-type org-preview-latex-process-alist)))
  14532. (programs (plist-get processing-info :programs))
  14533. (error-message (or (plist-get processing-info :message) ""))
  14534. (image-input-type (plist-get processing-info :image-input-type))
  14535. (image-output-type (plist-get processing-info :image-output-type))
  14536. (post-clean (or (plist-get processing-info :post-clean)
  14537. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  14538. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  14539. (latex-header
  14540. (or (plist-get processing-info :latex-header)
  14541. (org-latex-make-preamble
  14542. (org-export-get-environment (org-export-get-backend 'latex))
  14543. org-format-latex-header
  14544. 'snippet)))
  14545. (latex-compiler (plist-get processing-info :latex-compiler))
  14546. (tmpdir temporary-file-directory)
  14547. (texfilebase (make-temp-name
  14548. (expand-file-name "orgtex" tmpdir)))
  14549. (texfile (concat texfilebase ".tex"))
  14550. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  14551. '(1.0 . 1.0)))
  14552. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  14553. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  14554. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  14555. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  14556. "Black"))
  14557. (bg (or (plist-get options (if buffer :background :html-background))
  14558. "Transparent"))
  14559. (image-converter
  14560. (or (and (string= bg "Transparent")
  14561. (plist-get processing-info :transparent-image-converter))
  14562. (plist-get processing-info :image-converter)))
  14563. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  14564. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  14565. (dolist (program programs)
  14566. (org-check-external-command program error-message))
  14567. (if (eq fg 'default)
  14568. (setq fg (org-latex-color :foreground))
  14569. (setq fg (org-latex-color-format fg)))
  14570. (setq bg (cond
  14571. ((eq bg 'default) (org-latex-color :background))
  14572. ((string= bg "Transparent") nil)
  14573. (t (org-latex-color-format bg))))
  14574. ;; Remove TeX \par at end of snippet to avoid trailing space.
  14575. (if (string-suffix-p string "\n")
  14576. (aset string (1- (length string)) ?%)
  14577. (setq string (concat string "%")))
  14578. (with-temp-file texfile
  14579. (insert latex-header)
  14580. (insert "\n\\begin{document}\n"
  14581. "\\definecolor{fg}{rgb}{" fg "}%\n"
  14582. (if bg
  14583. (concat "\\definecolor{bg}{rgb}{" bg "}%\n"
  14584. "\n\\pagecolor{bg}%\n")
  14585. "")
  14586. "\n{\\color{fg}\n"
  14587. string
  14588. "\n}\n"
  14589. "\n\\end{document}\n"))
  14590. (let* ((err-msg (format "Please adjust `%s' part of \
  14591. `org-preview-latex-process-alist'."
  14592. processing-type))
  14593. (image-input-file
  14594. (org-compile-file
  14595. texfile latex-compiler image-input-type err-msg log-buf))
  14596. (image-output-file
  14597. (org-compile-file
  14598. image-input-file image-converter image-output-type err-msg log-buf
  14599. `((?D . ,(shell-quote-argument (format "%s" dpi)))
  14600. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  14601. (copy-file image-output-file tofile 'replace)
  14602. (dolist (e post-clean)
  14603. (when (file-exists-p (concat texfilebase e))
  14604. (delete-file (concat texfilebase e))))
  14605. image-output-file)))
  14606. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  14607. "Fill a LaTeX header template TPL.
  14608. In the template, the following place holders will be recognized:
  14609. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  14610. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  14611. [PACKAGES] \\usepackage statements for PKG
  14612. [NO-PACKAGES] do not include PKG
  14613. [EXTRA] the string EXTRA
  14614. [NO-EXTRA] do not include EXTRA
  14615. For backward compatibility, if both the positive and the negative place
  14616. holder is missing, the positive one (without the \"NO-\") will be
  14617. assumed to be present at the end of the template.
  14618. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  14619. EXTRA is a string.
  14620. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  14621. (let (rpl (end ""))
  14622. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  14623. (setq rpl (if (or (match-end 1) (not def-pkg))
  14624. "" (org-latex-packages-to-string def-pkg snippets-p t))
  14625. tpl (replace-match rpl t t tpl))
  14626. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  14627. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  14628. (setq rpl (if (or (match-end 1) (not pkg))
  14629. "" (org-latex-packages-to-string pkg snippets-p t))
  14630. tpl (replace-match rpl t t tpl))
  14631. (when pkg (setq end
  14632. (concat end "\n"
  14633. (org-latex-packages-to-string pkg snippets-p)))))
  14634. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  14635. (setq rpl (if (or (match-end 1) (not extra))
  14636. "" (concat extra "\n"))
  14637. tpl (replace-match rpl t t tpl))
  14638. (when (and extra (string-match "\\S-" extra))
  14639. (setq end (concat end "\n" extra))))
  14640. (if (string-match "\\S-" end)
  14641. (concat tpl "\n" end)
  14642. tpl)))
  14643. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  14644. "Turn an alist of packages into a string with the \\usepackage macros."
  14645. (setq pkg (mapconcat (lambda(p)
  14646. (cond
  14647. ((stringp p) p)
  14648. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  14649. (format "%% Package %s omitted" (cadr p)))
  14650. ((equal "" (car p))
  14651. (format "\\usepackage{%s}" (cadr p)))
  14652. (t
  14653. (format "\\usepackage[%s]{%s}"
  14654. (car p) (cadr p)))))
  14655. pkg
  14656. "\n"))
  14657. (if newline (concat pkg "\n") pkg))
  14658. (defun org-dvipng-color (attr)
  14659. "Return a RGB color specification for dvipng."
  14660. (org-dvipng-color-format (face-attribute 'default attr nil)))
  14661. (defun org-dvipng-color-format (color-name)
  14662. "Convert COLOR-NAME to a RGB color value for dvipng."
  14663. (apply #'format "rgb %s %s %s"
  14664. (mapcar 'org-normalize-color
  14665. (color-values color-name))))
  14666. (defun org-latex-color (attr)
  14667. "Return a RGB color for the LaTeX color package."
  14668. (org-latex-color-format (face-attribute 'default attr nil)))
  14669. (defun org-latex-color-format (color-name)
  14670. "Convert COLOR-NAME to a RGB color value."
  14671. (apply #'format "%s,%s,%s"
  14672. (mapcar 'org-normalize-color
  14673. (color-values color-name))))
  14674. (defun org-normalize-color (value)
  14675. "Return string to be used as color value for an RGB component."
  14676. (format "%g" (/ value 65535.0)))
  14677. ;; Image display
  14678. (defvar-local org-inline-image-overlays nil)
  14679. (defun org-toggle-inline-images (&optional include-linked)
  14680. "Toggle the display of inline images.
  14681. INCLUDE-LINKED is passed to `org-display-inline-images'."
  14682. (interactive "P")
  14683. (if org-inline-image-overlays
  14684. (progn
  14685. (org-remove-inline-images)
  14686. (when (called-interactively-p 'interactive)
  14687. (message "Inline image display turned off")))
  14688. (org-display-inline-images include-linked)
  14689. (when (called-interactively-p 'interactive)
  14690. (message (if org-inline-image-overlays
  14691. (format "%d images displayed inline"
  14692. (length org-inline-image-overlays))
  14693. "No images to display inline")))))
  14694. (defun org-redisplay-inline-images ()
  14695. "Assure display of inline images and refresh them."
  14696. (interactive)
  14697. (org-toggle-inline-images)
  14698. (unless org-inline-image-overlays
  14699. (org-toggle-inline-images)))
  14700. ;; For without-x builds.
  14701. (declare-function image-flush "image" (spec &optional frame))
  14702. (defcustom org-display-remote-inline-images 'skip
  14703. "How to display remote inline images.
  14704. Possible values of this option are:
  14705. skip Don't display remote images.
  14706. download Always download and display remote images.
  14707. cache Display remote images, and open them in separate buffers
  14708. for caching. Silently update the image buffer when a file
  14709. change is detected."
  14710. :group 'org-appearance
  14711. :package-version '(Org . "9.4")
  14712. :type '(choice
  14713. (const :tag "Ignore remote images" skip)
  14714. (const :tag "Always display remote images" download)
  14715. (const :tag "Display and silently update remote images" cache))
  14716. :safe #'symbolp)
  14717. (defun org--create-inline-image (file width)
  14718. "Create image located at FILE, or return nil.
  14719. WIDTH is the width of the image. The image may not be created
  14720. according to the value of `org-display-remote-inline-images'."
  14721. (let* ((remote? (file-remote-p file))
  14722. (file-or-data
  14723. (pcase org-display-remote-inline-images
  14724. ((guard (not remote?)) file)
  14725. (`download (with-temp-buffer
  14726. (set-buffer-multibyte nil)
  14727. (insert-file-contents-literally file)
  14728. (buffer-string)))
  14729. (`cache (let ((revert-without-query '(".")))
  14730. (with-current-buffer (find-file-noselect file)
  14731. (buffer-string))))
  14732. (`skip nil)
  14733. (other
  14734. (message "Invalid value of `org-display-remote-inline-images': %S"
  14735. other)
  14736. nil))))
  14737. (when file-or-data
  14738. (create-image file-or-data
  14739. (and (image-type-available-p 'imagemagick)
  14740. width
  14741. 'imagemagick)
  14742. remote?
  14743. :width width :scale 1))))
  14744. (defun org-display-inline-images (&optional include-linked refresh beg end)
  14745. "Display inline images.
  14746. An inline image is a link which follows either of these
  14747. conventions:
  14748. 1. Its path is a file with an extension matching return value
  14749. from `image-file-name-regexp' and it has no contents.
  14750. 2. Its description consists in a single link of the previous
  14751. type. In this case, that link must be a well-formed plain
  14752. or angle link, i.e., it must have an explicit \"file\" type.
  14753. Equip each image with the key-map `image-map'.
  14754. When optional argument INCLUDE-LINKED is non-nil, also links with
  14755. a text description part will be inlined. This can be nice for
  14756. a quick look at those images, but it does not reflect what
  14757. exported files will look like.
  14758. When optional argument REFRESH is non-nil, refresh existing
  14759. images between BEG and END. This will create new image displays
  14760. only if necessary.
  14761. BEG and END define the considered part. They default to the
  14762. buffer boundaries with possible narrowing."
  14763. (interactive "P")
  14764. (when (display-graphic-p)
  14765. (unless refresh
  14766. (org-remove-inline-images)
  14767. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  14768. (let ((end (or end (point-max))))
  14769. (org-with-point-at (or beg (point-min))
  14770. (let* ((case-fold-search t)
  14771. (file-extension-re (image-file-name-regexp))
  14772. (link-abbrevs (mapcar #'car
  14773. (append org-link-abbrev-alist-local
  14774. org-link-abbrev-alist)))
  14775. ;; Check absolute, relative file names and explicit
  14776. ;; "file:" links. Also check link abbreviations since
  14777. ;; some might expand to "file" links.
  14778. (file-types-re
  14779. (format "\\[\\[\\(?:file%s:\\|attachment:\\|[./~]\\)\\|\\]\\[\\(<?file:\\)"
  14780. (if (not link-abbrevs) ""
  14781. (concat "\\|" (regexp-opt link-abbrevs))))))
  14782. (while (re-search-forward file-types-re end t)
  14783. (let* ((link (org-element-lineage
  14784. (save-match-data (org-element-context))
  14785. '(link) t))
  14786. (linktype (org-element-property :type link))
  14787. (inner-start (match-beginning 1))
  14788. (path
  14789. (cond
  14790. ;; No link at point; no inline image.
  14791. ((not link) nil)
  14792. ;; File link without a description. Also handle
  14793. ;; INCLUDE-LINKED here since it should have
  14794. ;; precedence over the next case. I.e., if link
  14795. ;; contains filenames in both the path and the
  14796. ;; description, prioritize the path only when
  14797. ;; INCLUDE-LINKED is non-nil.
  14798. ((or (not (org-element-property :contents-begin link))
  14799. include-linked)
  14800. (and (or (equal "file" linktype)
  14801. (equal "attachment" linktype))
  14802. (org-element-property :path link)))
  14803. ;; Link with a description. Check if description
  14804. ;; is a filename. Even if Org doesn't have syntax
  14805. ;; for those -- clickable image -- constructs, fake
  14806. ;; them, as in `org-export-insert-image-links'.
  14807. ((not inner-start) nil)
  14808. (t
  14809. (org-with-point-at inner-start
  14810. (and (looking-at
  14811. (if (char-equal ?< (char-after inner-start))
  14812. org-link-angle-re
  14813. org-link-plain-re))
  14814. ;; File name must fill the whole
  14815. ;; description.
  14816. (= (org-element-property :contents-end link)
  14817. (match-end 0))
  14818. (match-string 2)))))))
  14819. (when (and path (string-match-p file-extension-re path))
  14820. (let ((file (if (equal "attachment" linktype)
  14821. (progn
  14822. (require 'org-attach)
  14823. (ignore-errors (org-attach-expand path)))
  14824. (expand-file-name path))))
  14825. (when (and file (file-exists-p file))
  14826. (let ((width (org-display-inline-image--width link))
  14827. (old (get-char-property-and-overlay
  14828. (org-element-property :begin link)
  14829. 'org-image-overlay)))
  14830. (if (and (car-safe old) refresh)
  14831. (image-flush (overlay-get (cdr old) 'display))
  14832. (let ((image (org--create-inline-image file width)))
  14833. (when image
  14834. (let ((ov (make-overlay
  14835. (org-element-property :begin link)
  14836. (progn
  14837. (goto-char
  14838. (org-element-property :end link))
  14839. (skip-chars-backward " \t")
  14840. (point)))))
  14841. (overlay-put ov 'display image)
  14842. (overlay-put ov 'face 'default)
  14843. (overlay-put ov 'org-image-overlay t)
  14844. (overlay-put
  14845. ov 'modification-hooks
  14846. (list 'org-display-inline-remove-overlay))
  14847. (when (boundp 'image-map)
  14848. (overlay-put ov 'keymap image-map))
  14849. (push ov org-inline-image-overlays))))))))))))))))
  14850. (defvar visual-fill-column-width) ; Silence compiler warning
  14851. (defun org-display-inline-image--width (link)
  14852. "Determine the display width of the image LINK, in pixels.
  14853. - When `org-image-actual-width' is t, the image's pixel width is used.
  14854. - When `org-image-actual-width' is a number, that value will is used.
  14855. - When `org-image-actual-width' is nil or a list, the first :width attribute
  14856. set (if it exists) is used to set the image width. A width of X% is
  14857. divided by 100.
  14858. If no :width attribute is given and `org-image-actual-width' is a list with
  14859. a number as the car, then that number is used as the default value.
  14860. If the value is a float between 0 and 2, it interpreted as that proportion
  14861. of the text width in the buffer."
  14862. ;; Apply `org-image-actual-width' specifications.
  14863. ;; Support subtree-level property "ORG-IMAGE-ACTUAL-WIDTH" specified
  14864. ;; width.
  14865. (let ((org-image-actual-width (org-property-or-variable-value 'org-image-actual-width)))
  14866. (cond
  14867. ((eq org-image-actual-width t) nil)
  14868. ((listp org-image-actual-width)
  14869. (let* ((case-fold-search t)
  14870. (par (org-element-lineage link '(paragraph)))
  14871. (attr-re "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)")
  14872. (par-end (org-element-property :post-affiliated par))
  14873. ;; Try to find an attribute providing a :width.
  14874. (attr-width
  14875. (when (and par (org-with-point-at
  14876. (org-element-property :begin par)
  14877. (re-search-forward attr-re par-end t)))
  14878. (match-string 1)))
  14879. (width
  14880. (cond
  14881. ;; Treat :width t as if `org-image-actual-width' were t.
  14882. ((string= attr-width "t") nil)
  14883. ;; Fallback to `org-image-actual-width' if no interprable width is given.
  14884. ((or (null attr-width)
  14885. (string-match-p "\\`[^0-9]" attr-width))
  14886. (car org-image-actual-width))
  14887. ;; Convert numeric widths to numbers, converting percentages.
  14888. ((string-match-p "\\`[0-9.]+%" attr-width)
  14889. (/ (string-to-number attr-width) 100.0))
  14890. (t (string-to-number attr-width)))))
  14891. (if (and (floatp width) (<= 0.0 width 2.0))
  14892. ;; A float in [0,2] should be interpereted as this portion of
  14893. ;; the text width in the window. This works well with cases like
  14894. ;; #+attr_latex: :width 0.X\{line,page,column,etc.}width,
  14895. ;; as the "0.X" is pulled out as a float. We use 2 as the upper
  14896. ;; bound as cases such as 1.2\linewidth are feasible.
  14897. (round (* width
  14898. (window-pixel-width)
  14899. (/ (or (and (bound-and-true-p visual-fill-column-mode)
  14900. (or visual-fill-column-width auto-fill-function))
  14901. (when auto-fill-function fill-column)
  14902. (- (window-text-width) (line-number-display-width)))
  14903. (float (window-total-width)))))
  14904. width)))
  14905. ((numberp org-image-actual-width)
  14906. org-image-actual-width)
  14907. (t nil))))
  14908. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  14909. "Remove inline-display overlay if a corresponding region is modified."
  14910. (when (and ov after)
  14911. (delete ov org-inline-image-overlays)
  14912. (delete-overlay ov)))
  14913. (defun org-remove-inline-images ()
  14914. "Remove inline display of images."
  14915. (interactive)
  14916. (mapc #'delete-overlay org-inline-image-overlays)
  14917. (setq org-inline-image-overlays nil))
  14918. (defvar org-self-insert-command-undo-counter 0)
  14919. (defvar org-speed-command nil)
  14920. (defun org-fix-tags-on-the-fly ()
  14921. "Align tags in headline at point.
  14922. Unlike `org-align-tags', this function does nothing if point is
  14923. either not currently on a tagged headline or on a tag."
  14924. (when (and (org-match-line org-tag-line-re)
  14925. (< (point) (match-beginning 1)))
  14926. (org-align-tags)))
  14927. (defun org-self-insert-command (N)
  14928. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  14929. If the cursor is in a table looking at whitespace, the whitespace is
  14930. overwritten, and the table is not marked as requiring realignment."
  14931. (interactive "p")
  14932. (org-fold-check-before-invisible-edit 'insert)
  14933. (cond
  14934. ((and org-use-speed-commands
  14935. (let ((kv (this-command-keys-vector)))
  14936. (setq org-speed-command
  14937. (run-hook-with-args-until-success
  14938. 'org-speed-command-hook
  14939. (make-string 1 (aref kv (1- (length kv))))))))
  14940. (cond
  14941. ((commandp org-speed-command)
  14942. (setq this-command org-speed-command)
  14943. (call-interactively org-speed-command))
  14944. ((functionp org-speed-command)
  14945. (funcall org-speed-command))
  14946. ((consp org-speed-command)
  14947. (eval org-speed-command t))
  14948. (t (let (org-use-speed-commands)
  14949. (call-interactively 'org-self-insert-command)))))
  14950. ((and
  14951. (= N 1)
  14952. (not (org-region-active-p))
  14953. (org-at-table-p)
  14954. (progn
  14955. ;; Check if we blank the field, and if that triggers align.
  14956. (and (featurep 'org-table)
  14957. org-table-auto-blank-field
  14958. (memq last-command
  14959. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  14960. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  14961. ;; Got extra space, this field does not determine
  14962. ;; column width.
  14963. (let (org-table-may-need-update) (org-table-blank-field))
  14964. ;; No extra space, this field may determine column
  14965. ;; width.
  14966. (org-table-blank-field)))
  14967. t)
  14968. (looking-at "[^|\n]* |"))
  14969. ;; There is room for insertion without re-aligning the table.
  14970. (self-insert-command N)
  14971. (org-table-with-shrunk-field
  14972. (save-excursion
  14973. (skip-chars-forward "^|")
  14974. ;; Do not delete last space, which is
  14975. ;; `org-table-separator-space', but the regular space before
  14976. ;; it.
  14977. (delete-region (- (point) 2) (1- (point))))))
  14978. (t
  14979. (setq org-table-may-need-update t)
  14980. (self-insert-command N)
  14981. (org-fix-tags-on-the-fly)
  14982. (when org-self-insert-cluster-for-undo
  14983. (if (not (eq last-command 'org-self-insert-command))
  14984. (setq org-self-insert-command-undo-counter 1)
  14985. (if (>= org-self-insert-command-undo-counter 20)
  14986. (setq org-self-insert-command-undo-counter 1)
  14987. (and (> org-self-insert-command-undo-counter 0)
  14988. buffer-undo-list (listp buffer-undo-list)
  14989. (not (cadr buffer-undo-list)) ; remove nil entry
  14990. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  14991. (setq org-self-insert-command-undo-counter
  14992. (1+ org-self-insert-command-undo-counter))))))))
  14993. (defun org-delete-backward-char (N)
  14994. "Like `delete-backward-char', insert whitespace at field end in tables.
  14995. When deleting backwards, in tables this function will insert whitespace in
  14996. front of the next \"|\" separator, to keep the table aligned. The table will
  14997. still be marked for re-alignment if the field did fill the entire column,
  14998. because, in this case the deletion might narrow the column."
  14999. (interactive "p")
  15000. (save-match-data
  15001. (org-fold-check-before-invisible-edit 'delete-backward)
  15002. (if (and (= N 1)
  15003. (not overwrite-mode)
  15004. (not (org-region-active-p))
  15005. (not (eq (char-before) ?|))
  15006. (save-excursion (skip-chars-backward " \t") (not (bolp)))
  15007. (looking-at-p ".*?|")
  15008. (org-at-table-p))
  15009. (progn (forward-char -1) (org-delete-char 1))
  15010. (backward-delete-char N)
  15011. (org-fix-tags-on-the-fly))))
  15012. (defun org-delete-char (N)
  15013. "Like `delete-char', but insert whitespace at field end in tables.
  15014. When deleting characters, in tables this function will insert whitespace in
  15015. front of the next \"|\" separator, to keep the table aligned. The table will
  15016. still be marked for re-alignment if the field did fill the entire column,
  15017. because, in this case the deletion might narrow the column."
  15018. (interactive "p")
  15019. (save-match-data
  15020. (org-fold-check-before-invisible-edit 'delete)
  15021. (cond
  15022. ((or (/= N 1)
  15023. (eq (char-after) ?|)
  15024. (save-excursion (skip-chars-backward " \t") (bolp))
  15025. (not (org-at-table-p)))
  15026. (delete-char N)
  15027. (org-fix-tags-on-the-fly))
  15028. ((looking-at ".\\(.*?\\)|")
  15029. (let* ((update? org-table-may-need-update)
  15030. (noalign (looking-at-p ".*? |")))
  15031. (delete-char 1)
  15032. (org-table-with-shrunk-field
  15033. (save-excursion
  15034. ;; Last space is `org-table-separator-space', so insert
  15035. ;; a regular one before it instead.
  15036. (goto-char (- (match-end 0) 2))
  15037. (insert " ")))
  15038. ;; If there were two spaces at the end, this field does not
  15039. ;; determine the width of the column.
  15040. (when noalign (setq org-table-may-need-update update?))))
  15041. (t
  15042. (delete-char N)))))
  15043. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  15044. (put 'org-self-insert-command 'delete-selection
  15045. (lambda ()
  15046. (not (run-hook-with-args-until-success
  15047. 'self-insert-uses-region-functions))))
  15048. (put 'orgtbl-self-insert-command 'delete-selection
  15049. (lambda ()
  15050. (not (run-hook-with-args-until-success
  15051. 'self-insert-uses-region-functions))))
  15052. (put 'org-delete-char 'delete-selection 'supersede)
  15053. (put 'org-delete-backward-char 'delete-selection 'supersede)
  15054. (put 'org-yank 'delete-selection 'yank)
  15055. (put 'org-return 'delete-selection t)
  15056. ;; Make `flyspell-mode' delay after some commands
  15057. (put 'org-self-insert-command 'flyspell-delayed t)
  15058. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  15059. (put 'org-delete-char 'flyspell-delayed t)
  15060. (put 'org-delete-backward-char 'flyspell-delayed t)
  15061. ;; Make pabbrev-mode expand after Org mode commands
  15062. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  15063. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  15064. (defun org-transpose-words ()
  15065. "Transpose words for Org.
  15066. This uses the `org-mode-transpose-word-syntax-table' syntax
  15067. table, which interprets characters in `org-emphasis-alist' as
  15068. word constituents."
  15069. (interactive)
  15070. (with-syntax-table org-mode-transpose-word-syntax-table
  15071. (call-interactively 'transpose-words)))
  15072. (defvar org-ctrl-c-ctrl-c-hook nil
  15073. "Hook for functions attaching themselves to `C-c C-c'.
  15074. This can be used to add additional functionality to the `C-c C-c'
  15075. key which executes context-dependent commands. This hook is run
  15076. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  15077. run after the last test.
  15078. Each function will be called with no arguments. The function
  15079. must check if the context is appropriate for it to act. If yes,
  15080. it should do its thing and then return a non-nil value. If the
  15081. context is wrong, just do nothing and return nil.")
  15082. (defvar org-ctrl-c-ctrl-c-final-hook nil
  15083. "Hook for functions attaching themselves to `C-c C-c'.
  15084. This can be used to add additional functionality to the `C-c C-c'
  15085. key which executes context-dependent commands. This hook is run
  15086. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  15087. before the first test.
  15088. Each function will be called with no arguments. The function
  15089. must check if the context is appropriate for it to act. If yes,
  15090. it should do its thing and then return a non-nil value. If the
  15091. context is wrong, just do nothing and return nil.")
  15092. (defvar org-tab-after-check-for-table-hook nil
  15093. "Hook for functions to attach themselves to TAB.
  15094. See `org-ctrl-c-ctrl-c-hook' for more information.
  15095. This hook runs after it has been established that the cursor is not in a
  15096. table, but before checking if the cursor is in a headline or if global cycling
  15097. should be done.
  15098. If any function in this hook returns t, not other actions like visibility
  15099. cycling will be done.")
  15100. (defvar org-tab-after-check-for-cycling-hook nil
  15101. "Hook for functions to attach themselves to TAB.
  15102. See `org-ctrl-c-ctrl-c-hook' for more information.
  15103. This hook runs after it has been established that not table field motion and
  15104. not visibility should be done because of current context. This is probably
  15105. the place where a package like yasnippets can hook in.")
  15106. (defvar org-tab-before-tab-emulation-hook nil
  15107. "Hook for functions to attach themselves to TAB.
  15108. See `org-ctrl-c-ctrl-c-hook' for more information.
  15109. This hook runs after every other options for TAB have been exhausted, but
  15110. before indentation and \t insertion takes place.")
  15111. (defvar org-metaleft-hook nil
  15112. "Hook for functions attaching themselves to `M-left'.
  15113. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15114. (defvar org-metaright-hook nil
  15115. "Hook for functions attaching themselves to `M-right'.
  15116. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15117. (defvar org-metaup-hook nil
  15118. "Hook for functions attaching themselves to `M-up'.
  15119. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15120. (defvar org-metadown-hook nil
  15121. "Hook for functions attaching themselves to `M-down'.
  15122. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15123. (defvar org-shiftmetaleft-hook nil
  15124. "Hook for functions attaching themselves to `M-S-left'.
  15125. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15126. (defvar org-shiftmetaright-hook nil
  15127. "Hook for functions attaching themselves to `M-S-right'.
  15128. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15129. (defvar org-shiftmetaup-hook nil
  15130. "Hook for functions attaching themselves to `M-S-up'.
  15131. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15132. (defvar org-shiftmetadown-hook nil
  15133. "Hook for functions attaching themselves to `M-S-down'.
  15134. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15135. (defvar org-metareturn-hook nil
  15136. "Hook for functions attaching themselves to `M-RET'.
  15137. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15138. (defvar org-shiftup-hook nil
  15139. "Hook for functions attaching themselves to `S-up'.
  15140. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15141. (defvar org-shiftup-final-hook nil
  15142. "Hook for functions attaching themselves to `S-up'.
  15143. This one runs after all other options except shift-select have been excluded.
  15144. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15145. (defvar org-shiftdown-hook nil
  15146. "Hook for functions attaching themselves to `S-down'.
  15147. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15148. (defvar org-shiftdown-final-hook nil
  15149. "Hook for functions attaching themselves to `S-down'.
  15150. This one runs after all other options except shift-select have been excluded.
  15151. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15152. (defvar org-shiftleft-hook nil
  15153. "Hook for functions attaching themselves to `S-left'.
  15154. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15155. (defvar org-shiftleft-final-hook nil
  15156. "Hook for functions attaching themselves to `S-left'.
  15157. This one runs after all other options except shift-select have been excluded.
  15158. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15159. (defvar org-shiftright-hook nil
  15160. "Hook for functions attaching themselves to `S-right'.
  15161. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15162. (defvar org-shiftright-final-hook nil
  15163. "Hook for functions attaching themselves to `S-right'.
  15164. This one runs after all other options except shift-select have been excluded.
  15165. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15166. (defun org-modifier-cursor-error ()
  15167. "Throw an error, a modified cursor command was applied in wrong context."
  15168. (user-error "This command is active in special context like tables, headlines or items"))
  15169. (defun org-shiftselect-error ()
  15170. "Throw an error because Shift-Cursor command was applied in wrong context."
  15171. (if (and (boundp 'shift-select-mode) shift-select-mode)
  15172. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  15173. (user-error "This command works only in special context like headlines or timestamps")))
  15174. (defun org-call-for-shift-select (cmd)
  15175. (let ((this-command-keys-shift-translated t))
  15176. (call-interactively cmd)))
  15177. (defun org-shifttab (&optional arg)
  15178. "Global visibility cycling or move to previous table field.
  15179. Call `org-table-previous-field' within a table.
  15180. When ARG is nil, cycle globally through visibility states.
  15181. When ARG is a numeric prefix, show contents of this level."
  15182. (interactive "P")
  15183. (cond
  15184. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  15185. ((integerp arg)
  15186. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  15187. (message "Content view to level: %d" arg)
  15188. (org-cycle-content (prefix-numeric-value arg2))
  15189. (org-cycle-show-empty-lines t)
  15190. (setq org-cycle-global-status 'overview)
  15191. (run-hook-with-args 'org-cycle-hook 'overview)))
  15192. (t (call-interactively 'org-cycle-global))))
  15193. (defun org-shiftmetaleft ()
  15194. "Promote subtree or delete table column.
  15195. Calls `org-promote-subtree', `org-outdent-item-tree', or
  15196. `org-table-delete-column', depending on context. See the
  15197. individual commands for more information."
  15198. (interactive)
  15199. (cond
  15200. ((and (eq system-type 'darwin)
  15201. (or (eq org-support-shift-select 'always)
  15202. (and org-support-shift-select (org-region-active-p))))
  15203. (org-call-for-shift-select 'backward-char))
  15204. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  15205. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  15206. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  15207. ((if (not (org-region-active-p)) (org-at-item-p)
  15208. (save-excursion (goto-char (region-beginning))
  15209. (org-at-item-p)))
  15210. (call-interactively 'org-outdent-item-tree))
  15211. (t (org-modifier-cursor-error))))
  15212. (defun org-shiftmetaright ()
  15213. "Demote subtree or insert table column.
  15214. Calls `org-demote-subtree', `org-indent-item-tree', or
  15215. `org-table-insert-column', depending on context. See the
  15216. individual commands for more information."
  15217. (interactive)
  15218. (cond
  15219. ((and (eq system-type 'darwin)
  15220. (or (eq org-support-shift-select 'always)
  15221. (and org-support-shift-select (org-region-active-p))))
  15222. (org-call-for-shift-select 'forward-char))
  15223. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  15224. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  15225. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  15226. ((if (not (org-region-active-p)) (org-at-item-p)
  15227. (save-excursion (goto-char (region-beginning))
  15228. (org-at-item-p)))
  15229. (call-interactively 'org-indent-item-tree))
  15230. (t (org-modifier-cursor-error))))
  15231. (defun org-shiftmetaup (&optional _arg)
  15232. "Drag the line at point up.
  15233. In a table, kill the current row.
  15234. On a clock timestamp, update the value of the timestamp like `S-<up>'
  15235. but also adjust the previous clocked item in the clock history.
  15236. Everywhere else, drag the line at point up."
  15237. (interactive "P")
  15238. (cond
  15239. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  15240. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  15241. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15242. (call-interactively 'org-timestamp-up)))
  15243. (t (call-interactively 'org-drag-line-backward))))
  15244. (defun org-shiftmetadown (&optional _arg)
  15245. "Drag the line at point down.
  15246. In a table, insert an empty row at the current line.
  15247. On a clock timestamp, update the value of the timestamp like `S-<down>'
  15248. but also adjust the previous clocked item in the clock history.
  15249. Everywhere else, drag the line at point down."
  15250. (interactive "P")
  15251. (cond
  15252. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  15253. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  15254. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15255. (call-interactively 'org-timestamp-down)))
  15256. (t (call-interactively 'org-drag-line-forward))))
  15257. (defsubst org-hidden-tree-error ()
  15258. (user-error
  15259. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  15260. (defun org-metaleft (&optional _arg)
  15261. "Promote heading, list item at point or move table column left.
  15262. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  15263. depending on context. With no specific context, calls the Emacs
  15264. default `backward-word'. See the individual commands for more
  15265. information.
  15266. This function runs the hook `org-metaleft-hook' as a first step,
  15267. and returns at first non-nil value."
  15268. (interactive "P")
  15269. (cond
  15270. ((run-hook-with-args-until-success 'org-metaleft-hook))
  15271. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  15272. ((org-with-limited-levels
  15273. (or (org-at-heading-p)
  15274. (and (org-region-active-p)
  15275. (save-excursion
  15276. (goto-char (region-beginning))
  15277. (org-at-heading-p)))))
  15278. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15279. (call-interactively 'org-do-promote))
  15280. ;; At an inline task.
  15281. ((org-at-heading-p)
  15282. (call-interactively 'org-inlinetask-promote))
  15283. ((or (org-at-item-p)
  15284. (and (org-region-active-p)
  15285. (save-excursion
  15286. (goto-char (region-beginning))
  15287. (org-at-item-p))))
  15288. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15289. (call-interactively 'org-outdent-item))
  15290. (t (call-interactively 'backward-word))))
  15291. (defun org-metaright (&optional _arg)
  15292. "Demote heading, list item at point or move table column right.
  15293. In front of a drawer or a block keyword, indent it correctly.
  15294. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  15295. `org-indent-drawer' or `org-indent-block' depending on context.
  15296. With no specific context, calls the Emacs default `forward-word'.
  15297. See the individual commands for more information.
  15298. This function runs the hook `org-metaright-hook' as a first step,
  15299. and returns at first non-nil value."
  15300. (interactive "P")
  15301. (cond
  15302. ((run-hook-with-args-until-success 'org-metaright-hook))
  15303. ((org-at-table-p) (call-interactively 'org-table-move-column))
  15304. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  15305. ((org-at-block-p) (call-interactively 'org-indent-block))
  15306. ((org-with-limited-levels
  15307. (or (org-at-heading-p)
  15308. (and (org-region-active-p)
  15309. (save-excursion
  15310. (goto-char (region-beginning))
  15311. (org-at-heading-p)))))
  15312. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15313. (call-interactively 'org-do-demote))
  15314. ;; At an inline task.
  15315. ((org-at-heading-p)
  15316. (call-interactively 'org-inlinetask-demote))
  15317. ((or (org-at-item-p)
  15318. (and (org-region-active-p)
  15319. (save-excursion
  15320. (goto-char (region-beginning))
  15321. (org-at-item-p))))
  15322. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15323. (call-interactively 'org-indent-item))
  15324. (t (call-interactively 'forward-word))))
  15325. (defun org-check-for-hidden (what)
  15326. "Check if there are hidden headlines/items in the current visual line.
  15327. WHAT can be either `headlines' or `items'. If the current line is
  15328. an outline or item heading and it has a folded subtree below it,
  15329. this function returns t, nil otherwise."
  15330. (let ((re (cond
  15331. ((eq what 'headlines) org-outline-regexp-bol)
  15332. ((eq what 'items) (org-item-beginning-re))
  15333. (t (error "This should not happen"))))
  15334. beg end)
  15335. (save-excursion
  15336. (catch 'exit
  15337. (unless (org-region-active-p)
  15338. (setq beg (line-beginning-position))
  15339. (beginning-of-line 2)
  15340. (while (and (not (eobp)) ;; this is like `next-line'
  15341. (org-invisible-p (1- (point))))
  15342. (beginning-of-line 2))
  15343. (setq end (point))
  15344. (goto-char beg)
  15345. (goto-char (line-end-position))
  15346. (setq end (max end (point)))
  15347. (while (re-search-forward re end t)
  15348. (when (org-invisible-p (match-beginning 0))
  15349. (throw 'exit t))))
  15350. nil))))
  15351. (defun org-metaup (&optional _arg)
  15352. "Move subtree up or move table row up.
  15353. Calls `org-move-subtree-up' or `org-table-move-row' or
  15354. `org-move-item-up', depending on context. See the individual commands
  15355. for more information."
  15356. (interactive "P")
  15357. (cond
  15358. ((run-hook-with-args-until-success 'org-metaup-hook))
  15359. ((org-region-active-p)
  15360. (let* ((a (save-excursion
  15361. (goto-char (region-beginning))
  15362. (line-beginning-position)))
  15363. (b (save-excursion
  15364. (goto-char (region-end))
  15365. (if (bolp) (1- (point)) (line-end-position))))
  15366. (c (save-excursion
  15367. (goto-char a)
  15368. (move-beginning-of-line 0)
  15369. (point)))
  15370. (d (save-excursion
  15371. (goto-char a)
  15372. (move-end-of-line 0)
  15373. (point))))
  15374. (transpose-regions a b c d)
  15375. (goto-char c)))
  15376. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  15377. ((and (featurep 'org-inlinetask)
  15378. (org-inlinetask-in-task-p))
  15379. (org-drag-element-backward))
  15380. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  15381. ((org-at-item-p) (call-interactively 'org-move-item-up))
  15382. (t (org-drag-element-backward))))
  15383. (defun org-metadown (&optional _arg)
  15384. "Move subtree down or move table row down.
  15385. Calls `org-move-subtree-down' or `org-table-move-row' or
  15386. `org-move-item-down', depending on context. See the individual
  15387. commands for more information."
  15388. (interactive "P")
  15389. (cond
  15390. ((run-hook-with-args-until-success 'org-metadown-hook))
  15391. ((org-region-active-p)
  15392. (let* ((a (save-excursion
  15393. (goto-char (region-beginning))
  15394. (line-beginning-position)))
  15395. (b (save-excursion
  15396. (goto-char (region-end))
  15397. (if (bolp) (1- (point)) (line-end-position))))
  15398. (c (save-excursion
  15399. (goto-char b)
  15400. (move-beginning-of-line (if (bolp) 1 2))
  15401. (point)))
  15402. (d (save-excursion
  15403. (goto-char b)
  15404. (move-end-of-line (if (bolp) 1 2))
  15405. (point))))
  15406. (transpose-regions a b c d)
  15407. (goto-char d)))
  15408. ((org-at-table-p) (call-interactively 'org-table-move-row))
  15409. ((and (featurep 'org-inlinetask)
  15410. (org-inlinetask-in-task-p))
  15411. (org-drag-element-forward))
  15412. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  15413. ((org-at-item-p) (call-interactively 'org-move-item-down))
  15414. (t (org-drag-element-forward))))
  15415. (defun org-shiftup (&optional arg)
  15416. "Act on current element according to context.
  15417. Call `org-timestamp-up' or `org-priority-up', or
  15418. `org-previous-item', or `org-table-move-cell-up'. See the
  15419. individual commands for more information."
  15420. (interactive "P")
  15421. (cond
  15422. ((run-hook-with-args-until-success 'org-shiftup-hook))
  15423. ((and org-support-shift-select (org-region-active-p))
  15424. (org-call-for-shift-select 'previous-line))
  15425. ((org-at-timestamp-p 'lax)
  15426. (call-interactively (if org-edit-timestamp-down-means-later
  15427. 'org-timestamp-down 'org-timestamp-up)))
  15428. ((and (not (eq org-support-shift-select 'always))
  15429. org-priority-enable-commands
  15430. (org-at-heading-p))
  15431. (call-interactively 'org-priority-up))
  15432. ((and (not org-support-shift-select) (org-at-item-p))
  15433. (call-interactively 'org-previous-item))
  15434. ((org-clocktable-try-shift 'up arg))
  15435. ((and (not (eq org-support-shift-select 'always))
  15436. (org-at-table-p))
  15437. (org-table-move-cell-up))
  15438. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  15439. (org-support-shift-select
  15440. (org-call-for-shift-select 'previous-line))
  15441. (t (org-shiftselect-error))))
  15442. (defun org-shiftdown (&optional arg)
  15443. "Act on current element according to context.
  15444. Call `org-timestamp-down' or `org-priority-down', or
  15445. `org-next-item', or `org-table-move-cell-down'. See the
  15446. individual commands for more information."
  15447. (interactive "P")
  15448. (cond
  15449. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  15450. ((and org-support-shift-select (org-region-active-p))
  15451. (org-call-for-shift-select 'next-line))
  15452. ((org-at-timestamp-p 'lax)
  15453. (call-interactively (if org-edit-timestamp-down-means-later
  15454. 'org-timestamp-up 'org-timestamp-down)))
  15455. ((and (not (eq org-support-shift-select 'always))
  15456. org-priority-enable-commands
  15457. (org-at-heading-p))
  15458. (call-interactively 'org-priority-down))
  15459. ((and (not org-support-shift-select) (org-at-item-p))
  15460. (call-interactively 'org-next-item))
  15461. ((org-clocktable-try-shift 'down arg))
  15462. ((and (not (eq org-support-shift-select 'always))
  15463. (org-at-table-p))
  15464. (org-table-move-cell-down))
  15465. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  15466. (org-support-shift-select
  15467. (org-call-for-shift-select 'next-line))
  15468. (t (org-shiftselect-error))))
  15469. (defun org-shiftright (&optional arg)
  15470. "Act on the current element according to context.
  15471. This does one of the following:
  15472. - switch a timestamp at point one day into the future
  15473. - on a headline, switch to the next TODO keyword
  15474. - on an item, switch entire list to the next bullet type
  15475. - on a property line, switch to the next allowed value
  15476. - on a clocktable definition line, move time block into the future
  15477. - in a table, move a single cell right"
  15478. (interactive "P")
  15479. (cond
  15480. ((run-hook-with-args-until-success 'org-shiftright-hook))
  15481. ((and org-support-shift-select (org-region-active-p))
  15482. (org-call-for-shift-select 'forward-char))
  15483. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  15484. ((and (not (eq org-support-shift-select 'always))
  15485. (org-at-heading-p))
  15486. (let ((org-inhibit-logging
  15487. (not org-treat-S-cursor-todo-selection-as-state-change))
  15488. (org-inhibit-blocking
  15489. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15490. (org-call-with-arg 'org-todo 'right)))
  15491. ((or (and org-support-shift-select
  15492. (not (eq org-support-shift-select 'always))
  15493. (org-at-item-bullet-p))
  15494. (and (not org-support-shift-select) (org-at-item-p)))
  15495. (org-call-with-arg 'org-cycle-list-bullet nil))
  15496. ((and (not (eq org-support-shift-select 'always))
  15497. (org-at-property-p))
  15498. (call-interactively 'org-property-next-allowed-value))
  15499. ((org-clocktable-try-shift 'right arg))
  15500. ((and (not (eq org-support-shift-select 'always))
  15501. (org-at-table-p))
  15502. (org-table-move-cell-right))
  15503. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  15504. (org-support-shift-select
  15505. (org-call-for-shift-select 'forward-char))
  15506. (t (org-shiftselect-error))))
  15507. (defun org-shiftleft (&optional arg)
  15508. "Act on current element according to context.
  15509. This does one of the following:
  15510. - switch a timestamp at point one day into the past
  15511. - on a headline, switch to the previous TODO keyword.
  15512. - on an item, switch entire list to the previous bullet type
  15513. - on a property line, switch to the previous allowed value
  15514. - on a clocktable definition line, move time block into the past
  15515. - in a table, move a single cell left"
  15516. (interactive "P")
  15517. (cond
  15518. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  15519. ((and org-support-shift-select (org-region-active-p))
  15520. (org-call-for-shift-select 'backward-char))
  15521. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  15522. ((and (not (eq org-support-shift-select 'always))
  15523. (org-at-heading-p))
  15524. (let ((org-inhibit-logging
  15525. (not org-treat-S-cursor-todo-selection-as-state-change))
  15526. (org-inhibit-blocking
  15527. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15528. (org-call-with-arg 'org-todo 'left)))
  15529. ((or (and org-support-shift-select
  15530. (not (eq org-support-shift-select 'always))
  15531. (org-at-item-bullet-p))
  15532. (and (not org-support-shift-select) (org-at-item-p)))
  15533. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  15534. ((and (not (eq org-support-shift-select 'always))
  15535. (org-at-property-p))
  15536. (call-interactively 'org-property-previous-allowed-value))
  15537. ((org-clocktable-try-shift 'left arg))
  15538. ((and (not (eq org-support-shift-select 'always))
  15539. (org-at-table-p))
  15540. (org-table-move-cell-left))
  15541. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  15542. (org-support-shift-select
  15543. (org-call-for-shift-select 'backward-char))
  15544. (t (org-shiftselect-error))))
  15545. (defun org-shiftcontrolright ()
  15546. "Switch to next TODO set."
  15547. (interactive)
  15548. (cond
  15549. ((and org-support-shift-select (org-region-active-p))
  15550. (org-call-for-shift-select 'forward-word))
  15551. ((and (not (eq org-support-shift-select 'always))
  15552. (org-at-heading-p))
  15553. (org-call-with-arg 'org-todo 'nextset))
  15554. (org-support-shift-select
  15555. (org-call-for-shift-select 'forward-word))
  15556. (t (org-shiftselect-error))))
  15557. (defun org-shiftcontrolleft ()
  15558. "Switch to previous TODO set."
  15559. (interactive)
  15560. (cond
  15561. ((and org-support-shift-select (org-region-active-p))
  15562. (org-call-for-shift-select 'backward-word))
  15563. ((and (not (eq org-support-shift-select 'always))
  15564. (org-at-heading-p))
  15565. (org-call-with-arg 'org-todo 'previousset))
  15566. (org-support-shift-select
  15567. (org-call-for-shift-select 'backward-word))
  15568. (t (org-shiftselect-error))))
  15569. (defun org-shiftcontrolup (&optional n)
  15570. "Change timestamps synchronously up in CLOCK log lines.
  15571. Optional argument N tells to change by that many units."
  15572. (interactive "P")
  15573. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  15574. (let (org-support-shift-select)
  15575. (org-clock-timestamps-up n))
  15576. (user-error "Not at a clock log")))
  15577. (defun org-shiftcontroldown (&optional n)
  15578. "Change timestamps synchronously down in CLOCK log lines.
  15579. Optional argument N tells to change by that many units."
  15580. (interactive "P")
  15581. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  15582. (let (org-support-shift-select)
  15583. (org-clock-timestamps-down n))
  15584. (user-error "Not at a clock log")))
  15585. (defun org-increase-number-at-point (&optional inc)
  15586. "Increment the number at point.
  15587. With an optional prefix numeric argument INC, increment using
  15588. this numeric value."
  15589. (interactive "p")
  15590. (if (not (number-at-point))
  15591. (user-error "Not on a number")
  15592. (unless inc (setq inc 1))
  15593. (let ((pos (point))
  15594. (beg (skip-chars-backward "-+^/*0-9eE."))
  15595. (end (skip-chars-forward "-+^/*0-9eE.")) nap)
  15596. (setq nap (buffer-substring-no-properties
  15597. (+ pos beg) (+ pos beg end)))
  15598. (delete-region (+ pos beg) (+ pos beg end))
  15599. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  15600. (when (org-at-table-p)
  15601. (org-table-align)
  15602. (org-table-end-of-field 1))))
  15603. (defun org-decrease-number-at-point (&optional inc)
  15604. "Decrement the number at point.
  15605. With an optional prefix numeric argument INC, decrement using
  15606. this numeric value."
  15607. (interactive "p")
  15608. (org-increase-number-at-point (- (or inc 1))))
  15609. (defun org-ctrl-c-ret ()
  15610. "Call `org-table-hline-and-move' or `org-insert-heading'."
  15611. (interactive)
  15612. (cond
  15613. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  15614. (t (call-interactively 'org-insert-heading))))
  15615. (defun org-copy-visible (beg end)
  15616. "Copy the visible parts of the region."
  15617. (interactive "r")
  15618. (let ((result ""))
  15619. (while (/= beg end)
  15620. (if (eq org-fold-core-style 'text-properties)
  15621. (progn
  15622. (while (org-invisible-p beg)
  15623. (setq beg (org-fold-next-visibility-change beg end)))
  15624. (let ((next (org-fold-next-visibility-change beg end)))
  15625. (setq result (concat result (buffer-substring beg next)))
  15626. (setq beg next)))
  15627. (when (invisible-p beg)
  15628. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  15629. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  15630. (setq result (concat result (buffer-substring beg next)))
  15631. (setq beg next))))
  15632. ;; Prevent Emacs from adding full selected text to `kill-ring'
  15633. ;; when `select-enable-primary' is non-nil. This special value of
  15634. ;; `deactivate-mark' only works since Emacs 29.
  15635. (setq deactivate-mark 'dont-save)
  15636. (kill-new result)
  15637. (message "Visible strings have been copied to the kill ring.")))
  15638. (defun org-copy-special ()
  15639. "Copy region in table or copy current subtree.
  15640. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  15641. context. See the individual commands for more information."
  15642. (interactive)
  15643. (call-interactively
  15644. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  15645. (defun org-cut-special ()
  15646. "Cut region in table or cut current subtree.
  15647. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  15648. context. See the individual commands for more information."
  15649. (interactive)
  15650. (call-interactively
  15651. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  15652. (defun org-paste-special (arg)
  15653. "Paste rectangular region into table, or past subtree relative to level.
  15654. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  15655. See the individual commands for more information."
  15656. (interactive "P")
  15657. (if (org-at-table-p)
  15658. (org-table-paste-rectangle)
  15659. (org-paste-subtree arg)))
  15660. (defun org-edit-special (&optional arg)
  15661. "Call a special editor for the element at point.
  15662. When at a table, call the formula editor with `org-table-edit-formulas'.
  15663. When in a source code block, call `org-edit-src-code'.
  15664. When in a fixed-width region, call `org-edit-fixed-width-region'.
  15665. When in an export block, call `org-edit-export-block'.
  15666. When in a comment block, call `org-edit-comment-block'.
  15667. When in a LaTeX environment, call `org-edit-latex-environment'.
  15668. When at an INCLUDE, SETUPFILE or BIBLIOGRAPHY keyword, visit the included file.
  15669. When at a footnote reference, call `org-edit-footnote-reference'.
  15670. When at a planning line call, `org-deadline' and/or `org-schedule'.
  15671. When at an active timestamp, call `org-time-stamp'.
  15672. When at an inactive timestamp, call `org-time-stamp-inactive'.
  15673. On a link, call `ffap' to visit the link at point.
  15674. Otherwise, return a user error."
  15675. (interactive "P")
  15676. (let ((element (org-element-at-point)))
  15677. (barf-if-buffer-read-only)
  15678. (pcase (org-element-type element)
  15679. (`src-block
  15680. (if (not arg) (org-edit-src-code)
  15681. (let* ((info (org-babel-get-src-block-info))
  15682. (lang (nth 0 info))
  15683. (params (nth 2 info))
  15684. (session (cdr (assq :session params))))
  15685. (if (not session) (org-edit-src-code)
  15686. ;; At a source block with a session and function called
  15687. ;; with an ARG: switch to the buffer related to the
  15688. ;; inferior process.
  15689. (switch-to-buffer
  15690. (funcall (intern (concat "org-babel-prep-session:" lang))
  15691. session params))))))
  15692. (`keyword
  15693. (unless (member (org-element-property :key element)
  15694. '("BIBLIOGRAPHY" "INCLUDE" "SETUPFILE"))
  15695. (user-error "No special environment to edit here"))
  15696. (let ((value (org-element-property :value element)))
  15697. (unless (org-string-nw-p value) (user-error "No file to edit"))
  15698. (let ((file (and (string-match "\\`\"\\(.*?\\)\"\\|\\S-+" value)
  15699. (or (match-string 1 value)
  15700. (match-string 0 value)))))
  15701. (when (org-url-p file)
  15702. (user-error "Files located with a URL cannot be edited"))
  15703. (org-link-open-from-string
  15704. (format "[[%s]]" (expand-file-name file))))))
  15705. (`table
  15706. (if (eq (org-element-property :type element) 'table.el)
  15707. (org-edit-table.el)
  15708. (call-interactively 'org-table-edit-formulas)))
  15709. ;; Only Org tables contain `table-row' type elements.
  15710. (`table-row (call-interactively 'org-table-edit-formulas))
  15711. (`example-block (org-edit-src-code))
  15712. (`export-block (org-edit-export-block))
  15713. (`comment-block (org-edit-comment-block))
  15714. (`fixed-width (org-edit-fixed-width-region))
  15715. (`latex-environment (org-edit-latex-environment))
  15716. (`planning
  15717. (let ((proplist (cadr element)))
  15718. (mapc #'call-interactively
  15719. (remq nil
  15720. (list
  15721. (when (plist-get proplist :deadline) #'org-deadline)
  15722. (when (plist-get proplist :scheduled) #'org-schedule))))))
  15723. (_
  15724. ;; No notable element at point. Though, we may be at a link or
  15725. ;; a footnote reference, which are objects. Thus, scan deeper.
  15726. (let ((context (org-element-context element)))
  15727. (pcase (org-element-type context)
  15728. (`footnote-reference (org-edit-footnote-reference))
  15729. (`inline-src-block (org-edit-inline-src-code))
  15730. (`latex-fragment (org-edit-latex-fragment))
  15731. (`timestamp (if (eq 'inactive (org-element-property :type context))
  15732. (call-interactively #'org-time-stamp-inactive)
  15733. (call-interactively #'org-time-stamp)))
  15734. (`link (call-interactively #'ffap))
  15735. (_ (user-error "No special environment to edit here"))))))))
  15736. (defun org-ctrl-c-ctrl-c (&optional arg)
  15737. "Set tags in headline, or update according to changed information at point.
  15738. This command does many different things, depending on context:
  15739. - If column view is active, in agenda or org buffers, quit it.
  15740. - If there are highlights, remove them.
  15741. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  15742. this is what we do.
  15743. - If the cursor is on a statistics cookie, update it.
  15744. - If the cursor is in a headline, in an agenda or an org buffer,
  15745. prompt for tags and insert them into the current line, aligned
  15746. to `org-tags-column'. When called with prefix arg, realign all
  15747. tags in the current buffer.
  15748. - If the cursor is in one of the special #+KEYWORD lines, this
  15749. triggers scanning the buffer for these lines and updating the
  15750. information.
  15751. - If the cursor is inside a table, realign the table. This command
  15752. works even if the automatic table editor has been turned off.
  15753. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  15754. the entire table.
  15755. - If the cursor is at a footnote reference or definition, jump to
  15756. the corresponding definition or references, respectively.
  15757. - If the cursor is a the beginning of a dynamic block, update it.
  15758. - If the current buffer is a capture buffer, close note and file it.
  15759. - If the cursor is on a <<<target>>>, update radio targets and
  15760. corresponding links in this buffer.
  15761. - If the cursor is on a numbered item in a plain list, renumber the
  15762. ordered list.
  15763. - If the cursor is on a checkbox, toggle it.
  15764. - If the cursor is on a code block, evaluate it. The variable
  15765. `org-confirm-babel-evaluate' can be used to control prompting
  15766. before code block evaluation, by default every code block
  15767. evaluation requires confirmation. Code block evaluation can be
  15768. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  15769. (interactive "P")
  15770. (cond
  15771. ((bound-and-true-p org-columns-overlays) (org-columns-quit))
  15772. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  15773. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  15774. (org-remove-occur-highlights)
  15775. (message "Temporary highlights/overlays removed from current buffer"))
  15776. ((and (local-variable-p 'org-finish-function)
  15777. (fboundp org-finish-function))
  15778. (funcall org-finish-function))
  15779. ((org-babel-hash-at-point))
  15780. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  15781. (t
  15782. (let* ((context
  15783. (org-element-lineage
  15784. (org-element-context)
  15785. ;; Limit to supported contexts.
  15786. '(babel-call clock dynamic-block footnote-definition
  15787. footnote-reference inline-babel-call inline-src-block
  15788. inlinetask item keyword node-property paragraph
  15789. plain-list planning property-drawer radio-target
  15790. src-block statistics-cookie table table-cell table-row
  15791. timestamp)
  15792. t))
  15793. (radio-list-p (org-at-radio-list-p))
  15794. (type (org-element-type context)))
  15795. ;; For convenience: at the first line of a paragraph on the same
  15796. ;; line as an item, apply function on that item instead.
  15797. (when (eq type 'paragraph)
  15798. (let ((parent (org-element-property :parent context)))
  15799. (when (and (eq (org-element-type parent) 'item)
  15800. (= (line-beginning-position)
  15801. (org-element-property :begin parent)))
  15802. (setq context parent)
  15803. (setq type 'item))))
  15804. ;; Act according to type of element or object at point.
  15805. ;;
  15806. ;; Do nothing on a blank line, except if it is contained in
  15807. ;; a source block. Hence, we first check if point is in such
  15808. ;; a block and then if it is at a blank line.
  15809. (pcase type
  15810. ((or `inline-src-block `src-block)
  15811. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  15812. (org-babel-eval-wipe-error-buffer)
  15813. (org-babel-execute-src-block
  15814. current-prefix-arg (org-babel-get-src-block-info nil context))))
  15815. ((guard (org-match-line "[ \t]*$"))
  15816. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  15817. (user-error
  15818. (substitute-command-keys
  15819. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  15820. ((or `babel-call `inline-babel-call)
  15821. (let ((info (org-babel-lob-get-info context)))
  15822. (when info (org-babel-execute-src-block nil info nil type))))
  15823. (`clock
  15824. (if (org-at-timestamp-p 'lax)
  15825. ;; Update the timestamp as well. `org-timestamp-change'
  15826. ;; will call `org-clock-update-time-maybe'.
  15827. (org-timestamp-change 0 'day)
  15828. (org-clock-update-time-maybe)))
  15829. (`dynamic-block
  15830. (save-excursion
  15831. (goto-char (org-element-property :post-affiliated context))
  15832. (org-update-dblock)))
  15833. (`footnote-definition
  15834. (goto-char (org-element-property :post-affiliated context))
  15835. (call-interactively 'org-footnote-action))
  15836. (`footnote-reference (call-interactively #'org-footnote-action))
  15837. ((or `headline `inlinetask)
  15838. (save-excursion (goto-char (org-element-property :begin context))
  15839. (call-interactively #'org-set-tags-command)))
  15840. (`item
  15841. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  15842. ;; unconditionally, whereas `C-u' will toggle its presence.
  15843. ;; Without a universal argument, if the item has a checkbox,
  15844. ;; toggle it. Otherwise repair the list.
  15845. (if (or radio-list-p
  15846. (and (boundp org-list-checkbox-radio-mode)
  15847. org-list-checkbox-radio-mode))
  15848. (org-toggle-radio-button arg)
  15849. (let* ((box (org-element-property :checkbox context))
  15850. (struct (org-element-property :structure context))
  15851. (old-struct (copy-tree struct))
  15852. (parents (org-list-parents-alist struct))
  15853. (prevs (org-list-prevs-alist struct))
  15854. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  15855. (org-list-set-checkbox
  15856. (org-element-property :begin context) struct
  15857. (cond ((equal arg '(16)) "[-]")
  15858. ((and (not box) (equal arg '(4))) "[ ]")
  15859. ((or (not box) (equal arg '(4))) nil)
  15860. ((eq box 'on) "[ ]")
  15861. (t "[X]")))
  15862. ;; Mimic `org-list-write-struct' but with grabbing a return
  15863. ;; value from `org-list-struct-fix-box'.
  15864. (org-list-struct-fix-ind struct parents 2)
  15865. (org-list-struct-fix-item-end struct)
  15866. (org-list-struct-fix-bul struct prevs)
  15867. (org-list-struct-fix-ind struct parents)
  15868. (let ((block-item
  15869. (org-list-struct-fix-box struct parents prevs orderedp)))
  15870. (if (and box (equal struct old-struct))
  15871. (if (equal arg '(16))
  15872. (message "Checkboxes already reset")
  15873. (user-error "Cannot toggle this checkbox: %s"
  15874. (if (eq box 'on)
  15875. "all subitems checked"
  15876. "unchecked subitems")))
  15877. (org-list-struct-apply-struct struct old-struct)
  15878. (org-update-checkbox-count-maybe))
  15879. (when block-item
  15880. (message "Checkboxes were removed due to empty box at line %d"
  15881. (org-current-line block-item)))))))
  15882. (`plain-list
  15883. ;; At a plain list, with a double C-u argument, set
  15884. ;; checkboxes of each item to "[-]", whereas a single one
  15885. ;; will toggle their presence according to the state of the
  15886. ;; first item in the list. Without an argument, repair the
  15887. ;; list.
  15888. (if (or radio-list-p
  15889. (and (boundp org-list-checkbox-radio-mode)
  15890. org-list-checkbox-radio-mode))
  15891. (org-toggle-radio-button arg)
  15892. (let* ((begin (org-element-property :contents-begin context))
  15893. (struct (org-element-property :structure context))
  15894. (old-struct (copy-tree struct))
  15895. (first-box (save-excursion
  15896. (goto-char begin)
  15897. (looking-at org-list-full-item-re)
  15898. (match-string-no-properties 3)))
  15899. (new-box (cond ((equal arg '(16)) "[-]")
  15900. ((equal arg '(4)) (unless first-box "[ ]"))
  15901. ((equal first-box "[X]") "[ ]")
  15902. (t "[X]"))))
  15903. (cond
  15904. (arg
  15905. (dolist (pos
  15906. (org-list-get-all-items
  15907. begin struct (org-list-prevs-alist struct)))
  15908. (org-list-set-checkbox pos struct new-box)))
  15909. ((and first-box (eq (point) begin))
  15910. ;; For convenience, when point is at bol on the first
  15911. ;; item of the list and no argument is provided, simply
  15912. ;; toggle checkbox of that item, if any.
  15913. (org-list-set-checkbox begin struct new-box)))
  15914. (when (equal
  15915. (org-list-write-struct
  15916. struct (org-list-parents-alist struct) old-struct)
  15917. old-struct)
  15918. (message "Cannot update this checkbox"))
  15919. (org-update-checkbox-count-maybe))))
  15920. (`keyword
  15921. (let ((org-inhibit-startup-visibility-stuff t)
  15922. (org-startup-align-all-tables nil))
  15923. (when (boundp 'org-table-coordinate-overlays)
  15924. (mapc #'delete-overlay org-table-coordinate-overlays)
  15925. (setq org-table-coordinate-overlays nil))
  15926. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  15927. (message "Local setup has been refreshed"))
  15928. ((or `property-drawer `node-property)
  15929. (call-interactively #'org-property-action))
  15930. (`radio-target
  15931. (call-interactively #'org-update-radio-target-regexp))
  15932. (`statistics-cookie
  15933. (call-interactively #'org-update-statistics-cookies))
  15934. ((or `table `table-cell `table-row)
  15935. ;; At a table, generate a plot if on the #+plot line,
  15936. ;; recalculate every field and align it otherwise. Also
  15937. ;; send the table if necessary.
  15938. (cond
  15939. ((and (org-match-line "[ \t]*#\\+plot:")
  15940. (< (point) (org-element-property :post-affiliated context)))
  15941. (org-plot/gnuplot))
  15942. ;; If the table has a `table.el' type, just give up.
  15943. ((eq (org-element-property :type context) 'table.el)
  15944. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  15945. Use `\\[org-edit-special]' to edit table.el tables")))
  15946. ;; At a table row or cell, maybe recalculate line but always
  15947. ;; align table.
  15948. ((or (eq type 'table)
  15949. ;; Check if point is at a TBLFM line.
  15950. (and (eq type 'table-row)
  15951. (= (point) (org-element-property :end context))))
  15952. (save-excursion
  15953. (if (org-at-TBLFM-p)
  15954. (progn (require 'org-table)
  15955. (org-table-calc-current-TBLFM))
  15956. (goto-char (org-element-property :contents-begin context))
  15957. (org-call-with-arg 'org-table-recalculate (or arg t))
  15958. (orgtbl-send-table 'maybe))))
  15959. (t
  15960. (org-table-maybe-eval-formula)
  15961. (cond (arg (call-interactively #'org-table-recalculate))
  15962. ((org-table-maybe-recalculate-line))
  15963. (t (org-table-align))))))
  15964. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  15965. (org-timestamp-change 0 'day))
  15966. ((and `nil (guard (org-at-heading-p)))
  15967. ;; When point is on an unsupported object type, we can miss
  15968. ;; the fact that it also is at a heading. Handle it here.
  15969. (call-interactively #'org-set-tags-command))
  15970. ((guard
  15971. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  15972. (_
  15973. (user-error
  15974. (substitute-command-keys
  15975. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  15976. (defun org-mode-restart ()
  15977. "Restart `org-mode'."
  15978. (interactive)
  15979. (let ((indent-status (bound-and-true-p org-indent-mode)))
  15980. (funcall major-mode)
  15981. (hack-local-variables)
  15982. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  15983. (org-indent-mode -1))
  15984. (org-reset-file-cache))
  15985. (message "%s restarted" major-mode))
  15986. (defun org-kill-note-or-show-branches ()
  15987. "Abort storing current note, or show just branches."
  15988. (interactive)
  15989. (cond (org-finish-function
  15990. (let ((org-note-abort t)) (funcall org-finish-function)))
  15991. ((org-before-first-heading-p)
  15992. (org-fold-show-branches-buffer)
  15993. (org-fold-hide-archived-subtrees (point-min) (point-max)))
  15994. (t
  15995. (let ((beg (progn (org-back-to-heading) (point)))
  15996. (end (save-excursion (org-end-of-subtree t t) (point))))
  15997. (org-fold-hide-subtree)
  15998. (org-fold-show-branches)
  15999. (org-fold-hide-archived-subtrees beg end)))))
  16000. (defun org-delete-indentation (&optional arg)
  16001. "Join current line to previous and fix whitespace at join.
  16002. If previous line is a headline add to headline title. Otherwise
  16003. the function calls `delete-indentation'.
  16004. I.e. with a non-nil optional argument, join the line with the
  16005. following one. If there is a region then join the lines in that
  16006. region."
  16007. (interactive "*P")
  16008. (if (save-excursion
  16009. (beginning-of-line (if arg 1 0))
  16010. (let ((case-fold-search nil))
  16011. (looking-at org-complex-heading-regexp)))
  16012. ;; At headline.
  16013. (let ((tags-column (when (match-beginning 5)
  16014. (save-excursion (goto-char (match-beginning 5))
  16015. (current-column))))
  16016. (string (concat " " (progn (when arg (forward-line 1))
  16017. (org-trim (delete-and-extract-region
  16018. (line-beginning-position)
  16019. (line-end-position)))))))
  16020. (unless (bobp) (delete-region (point) (1- (point))))
  16021. (goto-char (or (match-end 4)
  16022. (match-beginning 5)
  16023. (match-end 0)))
  16024. (skip-chars-backward " \t")
  16025. (save-excursion (insert string))
  16026. ;; Adjust alignment of tags.
  16027. (cond
  16028. ((not tags-column)) ;no tags
  16029. (org-auto-align-tags (org-align-tags))
  16030. (t (org--align-tags-here tags-column)))) ;preserve tags column
  16031. (let ((current-prefix-arg arg))
  16032. (call-interactively #'delete-indentation))))
  16033. (defun org-open-line (n)
  16034. "Insert a new row in tables, call `open-line' elsewhere.
  16035. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  16036. As a special case, when a document starts with a table, allow to
  16037. call `open-line' on the very first character."
  16038. (interactive "*p")
  16039. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  16040. (org-table-insert-row)
  16041. (open-line n)))
  16042. (defun org--newline (indent arg interactive)
  16043. "Call `newline-and-indent' or just `newline'.
  16044. If INDENT is non-nil, call `newline-and-indent' with ARG to
  16045. indent unconditionally; otherwise, call `newline' with ARG and
  16046. INTERACTIVE, which can trigger indentation if
  16047. `electric-indent-mode' is enabled."
  16048. (if indent
  16049. (org-newline-and-indent arg)
  16050. (newline arg interactive)))
  16051. (defun org-return (&optional indent arg interactive)
  16052. "Goto next table row or insert a newline.
  16053. Calls `org-table-next-row' or `newline', depending on context.
  16054. When optional INDENT argument is non-nil, call
  16055. `newline-and-indent' with ARG, otherwise call `newline' with ARG
  16056. and INTERACTIVE.
  16057. When `org-return-follows-link' is non-nil and point is on
  16058. a timestamp or a link, call `org-open-at-point'. However, it
  16059. will not happen if point is in a table or on a \"dead\"
  16060. object (e.g., within a comment). In these case, you need to use
  16061. `org-open-at-point' directly."
  16062. (interactive "i\nP\np")
  16063. (let* ((context (if org-return-follows-link (org-element-context)
  16064. (org-element-at-point)))
  16065. (element-type (org-element-type context)))
  16066. (cond
  16067. ;; In a table, call `org-table-next-row'. However, before first
  16068. ;; column or after last one, split the table.
  16069. ((or (and (eq 'table element-type)
  16070. (not (eq 'table.el (org-element-property :type context)))
  16071. (>= (point) (org-element-property :contents-begin context))
  16072. (< (point) (org-element-property :contents-end context)))
  16073. (org-element-lineage context '(table-row table-cell) t))
  16074. (if (or (looking-at-p "[ \t]*$")
  16075. (save-excursion (skip-chars-backward " \t") (bolp)))
  16076. (insert "\n")
  16077. (org-table-justify-field-maybe)
  16078. (call-interactively #'org-table-next-row)))
  16079. ;; On a link or a timestamp, call `org-open-at-point' if
  16080. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  16081. ;; locations, e.g., in a comment, as `org-open-at-point'.
  16082. ((and org-return-follows-link
  16083. (or (and (eq 'link element-type)
  16084. ;; Ensure point is not on the white spaces after
  16085. ;; the link.
  16086. (let ((origin (point)))
  16087. (org-with-point-at (org-element-property :end context)
  16088. (skip-chars-backward " \t")
  16089. (> (point) origin))))
  16090. (org-in-regexp org-ts-regexp-both nil t)
  16091. (org-in-regexp org-tsr-regexp-both nil t)
  16092. (org-in-regexp org-link-any-re nil t)))
  16093. (call-interactively #'org-open-at-point))
  16094. ;; Insert newline in heading, but preserve tags.
  16095. ((and (not (bolp))
  16096. (let ((case-fold-search nil))
  16097. (org-match-line org-complex-heading-regexp)))
  16098. ;; At headline. Split line. However, if point is on keyword,
  16099. ;; priority cookie or tags, do not break any of them: add
  16100. ;; a newline after the headline instead.
  16101. (let ((tags-column (and (match-beginning 5)
  16102. (save-excursion (goto-char (match-beginning 5))
  16103. (current-column))))
  16104. (string
  16105. (when (and (match-end 4) (org-point-in-group (point) 4))
  16106. (delete-and-extract-region (point) (match-end 4)))))
  16107. ;; Adjust tag alignment.
  16108. (cond
  16109. ((not (and tags-column string)))
  16110. (org-auto-align-tags (org-align-tags))
  16111. (t (org--align-tags-here tags-column))) ;preserve tags column
  16112. (end-of-line)
  16113. (org-fold-show-entry 'hide-drawers)
  16114. (org--newline indent arg interactive)
  16115. (when string (save-excursion (insert (org-trim string))))))
  16116. ;; In a list, make sure indenting keeps trailing text within.
  16117. ((and (not (eolp))
  16118. (org-element-lineage context '(item)))
  16119. (let ((trailing-data
  16120. (delete-and-extract-region (point) (line-end-position))))
  16121. (org--newline indent arg interactive)
  16122. (save-excursion (insert trailing-data))))
  16123. (t
  16124. ;; Do not auto-fill when point is in an Org property drawer.
  16125. (let ((auto-fill-function (and (not (org-at-property-p))
  16126. auto-fill-function)))
  16127. (org--newline indent arg interactive))))))
  16128. (defun org-return-and-maybe-indent ()
  16129. "Goto next table row, or insert a newline, maybe indented.
  16130. Call `org-table-next-row' or `org-return', depending on context.
  16131. See the individual commands for more information.
  16132. When inserting a newline, if `org-adapt-indentation' is t:
  16133. indent the line if `electric-indent-mode' is disabled, don't
  16134. indent it if it is enabled."
  16135. (interactive)
  16136. (org-return (not electric-indent-mode)))
  16137. (defun org-ctrl-c-tab (&optional arg)
  16138. "Toggle columns width in a table, or show children.
  16139. Call `org-table-toggle-column-width' if point is in a table.
  16140. Otherwise provide a compact view of the children. ARG is the
  16141. level to hide."
  16142. (interactive "p")
  16143. (cond
  16144. ((org-at-table-p)
  16145. (call-interactively #'org-table-toggle-column-width))
  16146. ((org-before-first-heading-p)
  16147. (save-excursion
  16148. (org-fold-flag-above-first-heading)
  16149. (org-fold-hide-sublevels (or arg 1))))
  16150. (t
  16151. (org-fold-hide-subtree)
  16152. (org-fold-show-children arg))))
  16153. (defun org-ctrl-c-star ()
  16154. "Compute table, or change heading status of lines.
  16155. Calls `org-table-recalculate' or `org-toggle-heading',
  16156. depending on context."
  16157. (interactive)
  16158. (cond
  16159. ((org-at-table-p)
  16160. (call-interactively 'org-table-recalculate))
  16161. (t
  16162. ;; Convert all lines in region to list items
  16163. (call-interactively 'org-toggle-heading))))
  16164. (defun org-ctrl-c-minus ()
  16165. "Insert separator line in table or modify bullet status of line.
  16166. Also turns a plain line or a region of lines into list items.
  16167. Calls `org-table-insert-hline', `org-toggle-item', or
  16168. `org-cycle-list-bullet', depending on context."
  16169. (interactive)
  16170. (cond
  16171. ((org-at-table-p)
  16172. (call-interactively 'org-table-insert-hline))
  16173. ((org-region-active-p)
  16174. (call-interactively 'org-toggle-item))
  16175. ((org-in-item-p)
  16176. (call-interactively 'org-cycle-list-bullet))
  16177. (t
  16178. (call-interactively 'org-toggle-item))))
  16179. (defun org-toggle-heading (&optional nstars)
  16180. "Convert headings to normal text, or items or text to headings.
  16181. If there is no active region, only convert the current line.
  16182. With a `\\[universal-argument]' prefix, convert the whole list at
  16183. point into heading.
  16184. In a region:
  16185. - If the first non blank line is a headline, remove the stars
  16186. from all headlines in the region.
  16187. - If it is a normal line, turn each and every normal line (i.e.,
  16188. not an heading or an item) in the region into headings. If you
  16189. want to convert only the first line of this region, use one
  16190. universal prefix argument.
  16191. - If it is a plain list item, turn all plain list items into headings.
  16192. The checkboxes are converted to appropriate TODO or DONE keywords
  16193. (using `car' or `org-done-keywords' and `org-not-done-keywords' when
  16194. available).
  16195. When converting a line into a heading, the number of stars is chosen
  16196. such that the lines become children of the current entry. However,
  16197. when a numeric prefix argument is given, its value determines the
  16198. number of stars to add."
  16199. (interactive "P")
  16200. (let ((skip-blanks
  16201. ;; Return beginning of first non-blank line, starting from
  16202. ;; line at POS.
  16203. (lambda (pos)
  16204. (save-excursion
  16205. (goto-char pos)
  16206. (while (org-at-comment-p) (forward-line))
  16207. (skip-chars-forward " \r\t\n")
  16208. (line-beginning-position))))
  16209. beg end toggled)
  16210. ;; Determine boundaries of changes. If a universal prefix has
  16211. ;; been given, put the list in a region. If region ends at a bol,
  16212. ;; do not consider the last line to be in the region.
  16213. (when (and current-prefix-arg (org-at-item-p))
  16214. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  16215. (org-mark-element))
  16216. (if (org-region-active-p)
  16217. (setq beg (funcall skip-blanks (region-beginning))
  16218. end (copy-marker (save-excursion
  16219. (goto-char (region-end))
  16220. (if (bolp) (point) (line-end-position)))))
  16221. (setq beg (funcall skip-blanks (line-beginning-position))
  16222. end (copy-marker (line-end-position))))
  16223. ;; Ensure inline tasks don't count as headings.
  16224. (org-with-limited-levels
  16225. (save-excursion
  16226. (goto-char beg)
  16227. (cond
  16228. ;; Case 1. Started at an heading: de-star headings.
  16229. ((org-at-heading-p)
  16230. (while (< (point) end)
  16231. (when (org-at-heading-p)
  16232. (looking-at org-outline-regexp) (replace-match "")
  16233. (setq toggled t))
  16234. (forward-line)))
  16235. ;; Case 2. Started at an item: change items into headlines.
  16236. ;; One star will be added by `org-list-to-subtree'.
  16237. ((org-at-item-p)
  16238. (while (< (point) end)
  16239. (when (org-at-item-p)
  16240. ;; Pay attention to cases when region ends before list.
  16241. (let* ((struct (org-list-struct))
  16242. (list-end
  16243. (min (org-list-get-bottom-point struct) (1+ end))))
  16244. (save-restriction
  16245. (narrow-to-region (point) list-end)
  16246. (insert (org-list-to-subtree
  16247. (org-list-to-lisp t)
  16248. (pcase (org-current-level)
  16249. (`nil 1)
  16250. (l (1+ (org-reduced-level l))))
  16251. ;; Keywords to replace checkboxes.
  16252. (list
  16253. ;; [X]
  16254. :cbon (concat (or (car org-done-keywords) "DONE") " ")
  16255. ;; [ ]
  16256. :cboff (concat (or (car org-not-done-keywords) "TODO") " ")
  16257. ;; [-]
  16258. :cbtrans (concat (or (car org-not-done-keywords) "TODO") " ")))
  16259. "\n")))
  16260. (setq toggled t))
  16261. (forward-line)))
  16262. ;; Case 3. Started at normal text: make every line an heading,
  16263. ;; skipping headlines and items.
  16264. (t (let* ((stars
  16265. (make-string
  16266. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  16267. (add-stars
  16268. (cond (nstars "") ; stars from prefix only
  16269. ((equal stars "") "*") ; before first heading
  16270. (org-odd-levels-only "**") ; inside heading, odd
  16271. (t "*"))) ; inside heading, oddeven
  16272. (rpl (concat stars add-stars " "))
  16273. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  16274. (while (< (point) (if (equal nstars '(4)) lend end))
  16275. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  16276. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  16277. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  16278. (forward-line)))))))
  16279. (unless toggled (message "Cannot toggle heading from here"))))
  16280. (defun org-meta-return (&optional arg)
  16281. "Insert a new heading or wrap a region in a table.
  16282. Calls `org-insert-heading', `org-insert-item' or
  16283. `org-table-wrap-region', depending on context. When called with
  16284. an argument, unconditionally call `org-insert-heading'."
  16285. (interactive "P")
  16286. (org-fold-check-before-invisible-edit 'insert)
  16287. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  16288. (call-interactively (cond (arg #'org-insert-heading)
  16289. ((org-at-table-p) #'org-table-wrap-region)
  16290. ((org-in-item-p) #'org-insert-item)
  16291. (t #'org-insert-heading)))))
  16292. ;;; Menu entries
  16293. (defsubst org-in-subtree-not-table-p ()
  16294. "Are we in a subtree and not in a table?"
  16295. (and (not (org-before-first-heading-p))
  16296. (not (org-at-table-p))))
  16297. ;; Define the Org mode menus
  16298. (easy-menu-define org-org-menu org-mode-map "Org menu."
  16299. `("Org"
  16300. ("Show/Hide"
  16301. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  16302. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  16303. ["Sparse Tree..." org-sparse-tree t]
  16304. ["Reveal Context" org-fold-reveal t]
  16305. ["Show All" org-fold-show-all t]
  16306. "--"
  16307. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  16308. "--"
  16309. ["New Heading" org-insert-heading t]
  16310. ("Navigate Headings"
  16311. ["Up" outline-up-heading t]
  16312. ["Next" outline-next-visible-heading t]
  16313. ["Previous" outline-previous-visible-heading t]
  16314. ["Next Same Level" outline-forward-same-level t]
  16315. ["Previous Same Level" outline-backward-same-level t]
  16316. "--"
  16317. ["Jump" org-goto t])
  16318. ("Edit Structure"
  16319. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  16320. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  16321. "--"
  16322. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  16323. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  16324. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  16325. "--"
  16326. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  16327. "--"
  16328. ["Copy visible text" org-copy-visible t]
  16329. "--"
  16330. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  16331. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  16332. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  16333. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  16334. "--"
  16335. ["Sort Region/Children" org-sort t]
  16336. "--"
  16337. ["Convert to odd levels" org-convert-to-odd-levels t]
  16338. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  16339. ("Editing"
  16340. ["Emphasis..." org-emphasize t]
  16341. ["Add block structure" org-insert-structure-template t]
  16342. ["Edit Source Example" org-edit-special t]
  16343. "--"
  16344. ["Footnote new/jump" org-footnote-action t]
  16345. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  16346. ("Archive"
  16347. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  16348. "--"
  16349. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  16350. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  16351. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)])
  16352. "--"
  16353. ("Hyperlinks"
  16354. ["Store Link (Global)" org-store-link t]
  16355. ["Find existing link to here" org-occur-link-in-agenda-files t]
  16356. ["Insert Link" org-insert-link t]
  16357. ["Follow Link" org-open-at-point t]
  16358. "--"
  16359. ["Next link" org-next-link t]
  16360. ["Previous link" org-previous-link t]
  16361. "--"
  16362. ["Descriptive Links"
  16363. org-toggle-link-display
  16364. :style radio
  16365. :selected org-descriptive-links
  16366. ]
  16367. ["Literal Links"
  16368. org-toggle-link-display
  16369. :style radio
  16370. :selected (not org-descriptive-links)])
  16371. "--"
  16372. ("TODO Lists"
  16373. ["TODO/DONE/-" org-todo t]
  16374. ("Select keyword"
  16375. ["Next keyword" org-shiftright (org-at-heading-p)]
  16376. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  16377. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  16378. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  16379. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  16380. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  16381. ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  16382. "--"
  16383. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  16384. :selected org-enforce-todo-dependencies :style toggle :active t]
  16385. "Settings for tree at point"
  16386. ["Do Children sequentially" org-toggle-ordered-property :style radio
  16387. :selected (org-entry-get nil "ORDERED")
  16388. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16389. ["Do Children parallel" org-toggle-ordered-property :style radio
  16390. :selected (not (org-entry-get nil "ORDERED"))
  16391. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16392. "--"
  16393. ["Set Priority" org-priority t]
  16394. ["Priority Up" org-shiftup t]
  16395. ["Priority Down" org-shiftdown t]
  16396. "--"
  16397. ["Get news from all feeds" org-feed-update-all t]
  16398. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  16399. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  16400. ("TAGS and Properties"
  16401. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  16402. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  16403. "--"
  16404. ["Set property" org-set-property (not (org-before-first-heading-p))]
  16405. ["Column view of properties" org-columns t]
  16406. ["Insert Column View DBlock" org-columns-insert-dblock t])
  16407. ("Dates and Scheduling"
  16408. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  16409. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  16410. ("Change Date"
  16411. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  16412. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  16413. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  16414. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  16415. ["Compute Time Range" org-evaluate-time-range t]
  16416. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  16417. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  16418. "--"
  16419. ["Custom time format" org-toggle-time-stamp-overlays
  16420. :style radio :selected org-display-custom-times]
  16421. "--"
  16422. ["Goto Calendar" org-goto-calendar t]
  16423. ["Date from Calendar" org-date-from-calendar t]
  16424. "--"
  16425. ["Start/Restart Timer" org-timer-start t]
  16426. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  16427. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  16428. ["Insert Timer String" org-timer t]
  16429. ["Insert Timer Item" org-timer-item t])
  16430. ("Logging work"
  16431. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  16432. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  16433. ["Clock out" org-clock-out t]
  16434. ["Clock cancel" org-clock-cancel t]
  16435. "--"
  16436. ["Mark as default task" org-clock-mark-default-task t]
  16437. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  16438. ["Goto running clock" org-clock-goto t]
  16439. "--"
  16440. ["Display times" org-clock-display t]
  16441. ["Create clock table" org-clock-report t]
  16442. "--"
  16443. ["Record DONE time"
  16444. (progn (setq org-log-done (not org-log-done))
  16445. (message "Switching to %s will %s record a timestamp"
  16446. (car org-done-keywords)
  16447. (if org-log-done "automatically" "not")))
  16448. :style toggle :selected org-log-done])
  16449. "--"
  16450. ["Agenda Command..." org-agenda t]
  16451. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  16452. ("File List for Agenda")
  16453. ("Special views current file"
  16454. ["TODO Tree" org-show-todo-tree t]
  16455. ["Check Deadlines" org-check-deadlines t]
  16456. ["Tags/Property tree" org-match-sparse-tree t])
  16457. "--"
  16458. ["Export/Publish..." org-export-dispatch t]
  16459. ("LaTeX"
  16460. ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  16461. :style toggle :selected org-cdlatex-mode]
  16462. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  16463. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  16464. ["Modify math symbol" org-cdlatex-math-modify
  16465. (org-inside-LaTeX-fragment-p)]
  16466. ["Insert citation" org-reftex-citation t])
  16467. "--"
  16468. ("Documentation"
  16469. ["Show Version" org-version t]
  16470. ["Info Documentation" org-info t]
  16471. ["Browse Org News" org-browse-news t])
  16472. ("Customize"
  16473. ["Browse Org Group" org-customize t]
  16474. "--"
  16475. ["Expand This Menu" org-create-customize-menu t])
  16476. ["Send bug report" org-submit-bug-report t]
  16477. "--"
  16478. ("Refresh/Reload"
  16479. ["Refresh setup current buffer" org-mode-restart t]
  16480. ["Reload Org (after update)" org-reload t]
  16481. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])))
  16482. (easy-menu-define org-tbl-menu org-mode-map "Org Table menu."
  16483. '("Table"
  16484. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  16485. ["Next Field" org-cycle (org-at-table-p)]
  16486. ["Previous Field" org-shifttab (org-at-table-p)]
  16487. ["Next Row" org-return (org-at-table-p)]
  16488. "--"
  16489. ["Blank Field" org-table-blank-field (org-at-table-p)]
  16490. ["Edit Field" org-table-edit-field (org-at-table-p)]
  16491. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  16492. "--"
  16493. ("Column"
  16494. ["Move Column Left" org-metaleft (org-at-table-p)]
  16495. ["Move Column Right" org-metaright (org-at-table-p)]
  16496. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  16497. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  16498. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  16499. ("Row"
  16500. ["Move Row Up" org-metaup (org-at-table-p)]
  16501. ["Move Row Down" org-metadown (org-at-table-p)]
  16502. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  16503. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  16504. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  16505. "--"
  16506. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  16507. ("Rectangle"
  16508. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  16509. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  16510. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  16511. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  16512. "--"
  16513. ("Calculate"
  16514. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  16515. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  16516. ["Edit Formulas" org-edit-special (org-at-table-p)]
  16517. "--"
  16518. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  16519. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  16520. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  16521. "--"
  16522. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  16523. "--"
  16524. ["Sum Column/Rectangle" org-table-sum
  16525. (or (org-at-table-p) (org-region-active-p))]
  16526. ["Which Column?" org-table-current-column (org-at-table-p)])
  16527. ["Debug Formulas"
  16528. org-table-toggle-formula-debugger
  16529. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  16530. ["Show Col/Row Numbers"
  16531. org-table-toggle-coordinate-overlays
  16532. :style toggle
  16533. :selected (bound-and-true-p org-table-overlay-coordinates)]
  16534. "--"
  16535. ["Create" org-table-create (not (org-at-table-p))]
  16536. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  16537. ["Import from File" org-table-import (not (org-at-table-p))]
  16538. ["Export to File" org-table-export (org-at-table-p)]
  16539. "--"
  16540. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  16541. "--"
  16542. ("Plot"
  16543. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  16544. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  16545. (defun org-info (&optional node)
  16546. "Read documentation for Org in the info system.
  16547. With optional NODE, go directly to that node."
  16548. (interactive)
  16549. (info (format "(org)%s" (or node ""))))
  16550. (defun org-browse-news ()
  16551. "Browse the news for the latest major release."
  16552. (interactive)
  16553. (browse-url "https://orgmode.org/Changes.html"))
  16554. ;;;###autoload
  16555. (defun org-submit-bug-report ()
  16556. "Submit a bug report on Org via mail.
  16557. Don't hesitate to report any problems or inaccurate documentation.
  16558. If you don't have setup sending mail from (X)Emacs, please copy the
  16559. output buffer into your mail program, as it gives us important
  16560. information about your Org version and configuration."
  16561. (interactive)
  16562. (require 'reporter)
  16563. (defvar reporter-prompt-for-summary-p)
  16564. (org-load-modules-maybe)
  16565. (org-require-autoloaded-modules)
  16566. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  16567. (reporter-submit-bug-report
  16568. "emacs-orgmode@gnu.org"
  16569. (org-version nil 'full)
  16570. (let (list)
  16571. (save-window-excursion
  16572. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  16573. (delete-other-windows)
  16574. (erase-buffer)
  16575. (insert "You are about to submit a bug report to the Org mailing list.
  16576. If your report is about Org installation, please read this section:
  16577. https://orgmode.org/org.html#Installation
  16578. Please read https://orgmode.org/org.html#Feedback on how to make
  16579. a good report, it will help Org contributors fixing your problem.
  16580. Search https://lists.gnu.org/archive/html/emacs-orgmode/ to see
  16581. if the issue you are about to raise has already been dealt with.
  16582. We also would like to add your full Org and Outline configuration
  16583. to the bug report. It will help us debugging the issue.
  16584. *HOWEVER*, some variables you have customized may contain private
  16585. information. The names of customers, colleagues, or friends, might
  16586. appear in the form of file names, tags, todo states or search strings.
  16587. If you answer \"yes\" to the prompt, you might want to check and remove
  16588. such private information before sending the email.")
  16589. (add-text-properties (point-min) (point-max) '(face org-warning))
  16590. (when (yes-or-no-p "Include your Org configuration ")
  16591. (mapatoms
  16592. (lambda (v)
  16593. (and (boundp v)
  16594. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  16595. (or (and (symbol-value v)
  16596. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  16597. (and
  16598. (get v 'custom-type) (get v 'standard-value)
  16599. (not (equal (symbol-value v)
  16600. (eval (car (get v 'standard-value)) t)))))
  16601. (push v list)))))
  16602. (kill-buffer (get-buffer "*Warn about privacy*"))
  16603. list))
  16604. nil nil
  16605. "Remember to cover the basics, that is, what you expected to happen and
  16606. what in fact did happen. You don't know how to make a good report? See
  16607. https://orgmode.org/manual/Feedback.html#Feedback
  16608. Your bug report will be posted to the Org mailing list.
  16609. ------------------------------------------------------------------------")
  16610. (save-excursion
  16611. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  16612. (replace-match "\\1[BUG] \\3 [\\2]")))))
  16613. (defun org-install-agenda-files-menu ()
  16614. "Install agenda file menu."
  16615. (let ((bl (buffer-list)))
  16616. (save-excursion
  16617. (while bl
  16618. (set-buffer (pop bl))
  16619. (when (derived-mode-p 'org-mode) (setq bl nil)))
  16620. (when (derived-mode-p 'org-mode)
  16621. (easy-menu-change
  16622. '("Org") "File List for Agenda"
  16623. (append
  16624. (list
  16625. ["Edit File List" (org-edit-agenda-file-list) t]
  16626. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  16627. ["Remove Current File from List" org-remove-file t]
  16628. ["Cycle through agenda files" org-cycle-agenda-files t]
  16629. ["Occur in all agenda files" org-occur-in-agenda-files t]
  16630. "--")
  16631. (mapcar 'org-file-menu-entry
  16632. ;; Prevent initialization from failing.
  16633. (ignore-errors (org-agenda-files t)))))))))
  16634. ;;;; Documentation
  16635. (defun org-require-autoloaded-modules ()
  16636. (interactive)
  16637. (mapc #'require
  16638. '(org-agenda org-archive org-attach org-clock org-colview org-id
  16639. org-table org-timer)))
  16640. ;;;###autoload
  16641. (defun org-reload (&optional uncompiled)
  16642. "Reload all Org Lisp files.
  16643. With prefix arg UNCOMPILED, load the uncompiled versions."
  16644. (interactive "P")
  16645. (require 'loadhist)
  16646. (let* ((org-dir (org-find-library-dir "org"))
  16647. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  16648. (feature-re "^\\(org\\|ob\\|ox\\|ol\\|oc\\)\\(-.*\\)?")
  16649. (remove-re (format "\\`%s\\'"
  16650. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  16651. (feats (delete-dups
  16652. (mapcar 'file-name-sans-extension
  16653. (mapcar 'file-name-nondirectory
  16654. (delq nil
  16655. (mapcar 'feature-file
  16656. features))))))
  16657. (lfeat (append
  16658. (sort
  16659. (setq feats
  16660. (delq nil (mapcar
  16661. (lambda (f)
  16662. (if (and (string-match feature-re f)
  16663. (not (string-match remove-re f)))
  16664. f nil))
  16665. feats)))
  16666. 'string-lessp)
  16667. (list "org-version" "org")))
  16668. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  16669. load-uncore load-misses)
  16670. (setq load-misses
  16671. (delq t
  16672. (mapcar (lambda (f)
  16673. (or (org-load-noerror-mustsuffix (concat org-dir f))
  16674. (and (string= org-dir contrib-dir)
  16675. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  16676. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  16677. (push f load-uncore)
  16678. t)
  16679. f))
  16680. lfeat)))
  16681. (when load-uncore
  16682. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  16683. (if (> (length load-uncore) 1) "s were" " was")
  16684. (reverse load-uncore)))
  16685. (if load-misses
  16686. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  16687. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  16688. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  16689. ;;;###autoload
  16690. (defun org-customize ()
  16691. "Call the customize function with org as argument."
  16692. (interactive)
  16693. (org-load-modules-maybe)
  16694. (org-require-autoloaded-modules)
  16695. (customize-browse 'org))
  16696. (defun org-create-customize-menu ()
  16697. "Create a full customization menu for Org mode, insert it into the menu."
  16698. (interactive)
  16699. (org-load-modules-maybe)
  16700. (org-require-autoloaded-modules)
  16701. (easy-menu-change
  16702. '("Org") "Customize"
  16703. `(["Browse Org group" org-customize t]
  16704. "--"
  16705. ,(customize-menu-create 'org)
  16706. ["Set" Custom-set t]
  16707. ["Save" Custom-save t]
  16708. ["Reset to Current" Custom-reset-current t]
  16709. ["Reset to Saved" Custom-reset-saved t]
  16710. ["Reset to Standard Settings" Custom-reset-standard t]))
  16711. (message "\"Org\"-menu now contains full customization menu"))
  16712. ;;;; Miscellaneous stuff
  16713. ;;; Generally useful functions
  16714. (defun org-in-clocktable-p ()
  16715. "Check if the cursor is in a clocktable."
  16716. (let ((pos (point)) start)
  16717. (save-excursion
  16718. (end-of-line 1)
  16719. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  16720. (setq start (match-beginning 0))
  16721. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  16722. (>= (match-end 0) pos)
  16723. start))))
  16724. (defun org-in-verbatim-emphasis ()
  16725. (save-match-data
  16726. (and (org-in-regexp org-verbatim-re 2)
  16727. (>= (point) (match-beginning 3))
  16728. (<= (point) (match-end 4)))))
  16729. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  16730. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  16731. (if (and marker (marker-buffer marker)
  16732. (buffer-live-p (marker-buffer marker)))
  16733. (progn
  16734. (pop-to-buffer-same-window (marker-buffer marker))
  16735. (when (or (> marker (point-max)) (< marker (point-min)))
  16736. (widen))
  16737. (goto-char marker)
  16738. (org-fold-show-context 'org-goto))
  16739. (if bookmark
  16740. (bookmark-jump bookmark)
  16741. (error "Cannot find location"))))
  16742. (defun org-quote-csv-field (s)
  16743. "Quote field for inclusion in CSV material."
  16744. (if (string-match "[\",]" s)
  16745. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  16746. s))
  16747. (defun org-force-self-insert (N)
  16748. "Needed to enforce self-insert under remapping."
  16749. (interactive "p")
  16750. (self-insert-command N))
  16751. (defun org-quote-vert (s)
  16752. "Replace \"|\" with \"\\vert\"."
  16753. (while (string-match "|" s)
  16754. (setq s (replace-match "\\vert" t t s)))
  16755. s)
  16756. (defun org-uuidgen-p (s)
  16757. "Is S an ID created by UUIDGEN?"
  16758. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  16759. (defun org-in-src-block-p (&optional inside element)
  16760. "Whether point is in a code source block.
  16761. When INSIDE is non-nil, don't consider we are within a source
  16762. block when point is at #+BEGIN_SRC or #+END_SRC.
  16763. When ELEMENT is provided, it is considered to be element at point."
  16764. (save-match-data (setq element (or element (org-element-at-point))))
  16765. (when (eq 'src-block (org-element-type element))
  16766. (or (not inside)
  16767. (not (or (= (line-beginning-position)
  16768. (org-element-property :post-affiliated element))
  16769. (= (1+ (line-end-position))
  16770. (- (org-element-property :end element)
  16771. (org-element-property :post-blank element))))))))
  16772. (defun org-context ()
  16773. "Return a list of contexts of the current cursor position.
  16774. If several contexts apply, all are returned.
  16775. Each context entry is a list with a symbol naming the context, and
  16776. two positions indicating start and end of the context. Possible
  16777. contexts are:
  16778. :headline anywhere in a headline
  16779. :headline-stars on the leading stars in a headline
  16780. :todo-keyword on a TODO keyword (including DONE) in a headline
  16781. :tags on the TAGS in a headline
  16782. :priority on the priority cookie in a headline
  16783. :item on the first line of a plain list item
  16784. :item-bullet on the bullet/number of a plain list item
  16785. :checkbox on the checkbox in a plain list item
  16786. :table in an Org table
  16787. :table-special on a special filed in a table
  16788. :table-table in a table.el table
  16789. :clocktable in a clocktable
  16790. :src-block in a source block
  16791. :link on a hyperlink
  16792. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  16793. :latex-fragment on a LaTeX fragment
  16794. :latex-preview on a LaTeX fragment with overlaid preview image
  16795. This function expects the position to be visible because it uses font-lock
  16796. faces as a help to recognize the following contexts: :table-special, :link,
  16797. and :keyword."
  16798. (let* ((f (get-text-property (point) 'face))
  16799. (faces (if (listp f) f (list f)))
  16800. (case-fold-search t)
  16801. (p (point)) clist o)
  16802. ;; First the large context
  16803. (cond
  16804. ((org-at-heading-p)
  16805. (push (list :headline (line-beginning-position)
  16806. (line-end-position))
  16807. clist)
  16808. (when (progn
  16809. (beginning-of-line 1)
  16810. (looking-at org-todo-line-tags-regexp))
  16811. (push (org-point-in-group p 1 :headline-stars) clist)
  16812. (push (org-point-in-group p 2 :todo-keyword) clist)
  16813. (push (org-point-in-group p 4 :tags) clist))
  16814. (goto-char p)
  16815. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  16816. (when (looking-at "\\[#[A-Z0-9]\\]")
  16817. (push (org-point-in-group p 0 :priority) clist)))
  16818. ((org-at-item-p)
  16819. (push (org-point-in-group p 2 :item-bullet) clist)
  16820. (push (list :item (line-beginning-position)
  16821. (save-excursion (org-end-of-item) (point)))
  16822. clist)
  16823. (and (org-at-item-checkbox-p)
  16824. (push (org-point-in-group p 0 :checkbox) clist)))
  16825. ((org-at-table-p)
  16826. (push (list :table (org-table-begin) (org-table-end)) clist)
  16827. (when (memq 'org-formula faces)
  16828. (push (list :table-special
  16829. (previous-single-property-change p 'face)
  16830. (next-single-property-change p 'face))
  16831. clist)))
  16832. ((org-at-table-p 'any)
  16833. (push (list :table-table) clist)))
  16834. (goto-char p)
  16835. (let ((case-fold-search t))
  16836. ;; New the "medium" contexts: clocktables, source blocks
  16837. (cond ((org-in-clocktable-p)
  16838. (push (list :clocktable
  16839. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  16840. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  16841. (match-beginning 1))
  16842. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  16843. (match-end 0)))
  16844. clist))
  16845. ((org-in-src-block-p)
  16846. (push (list :src-block
  16847. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  16848. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  16849. (match-beginning 1))
  16850. (and (search-forward "#+END_SRC" nil t)
  16851. (match-beginning 0)))
  16852. clist))))
  16853. (goto-char p)
  16854. ;; Now the small context
  16855. (cond
  16856. ((org-at-timestamp-p)
  16857. (push (org-point-in-group p 0 :timestamp) clist))
  16858. ((memq 'org-link faces)
  16859. (push (list :link
  16860. (previous-single-property-change p 'face)
  16861. (next-single-property-change p 'face))
  16862. clist))
  16863. ((memq 'org-special-keyword faces)
  16864. (push (list :keyword
  16865. (previous-single-property-change p 'face)
  16866. (next-single-property-change p 'face))
  16867. clist))
  16868. ((setq o (cl-some
  16869. (lambda (o)
  16870. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  16871. o))
  16872. (overlays-at (point))))
  16873. (push (list :latex-fragment
  16874. (overlay-start o) (overlay-end o))
  16875. clist)
  16876. (push (list :latex-preview
  16877. (overlay-start o) (overlay-end o))
  16878. clist))
  16879. ((org-inside-LaTeX-fragment-p)
  16880. ;; FIXME: positions wrong.
  16881. (push (list :latex-fragment (point) (point)) clist)))
  16882. (setq clist (nreverse (delq nil clist)))
  16883. clist))
  16884. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  16885. "Non-nil when point is between matches of START-RE and END-RE.
  16886. Also return a non-nil value when point is on one of the matches.
  16887. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  16888. buffer positions. Default values are the positions of headlines
  16889. surrounding the point.
  16890. The functions returns a cons cell whose car (resp. cdr) is the
  16891. position before START-RE (resp. after END-RE)."
  16892. (save-match-data
  16893. (let ((pos (point))
  16894. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  16895. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  16896. beg end)
  16897. (save-excursion
  16898. ;; Point is on a block when on START-RE or if START-RE can be
  16899. ;; found before it...
  16900. (and (or (org-in-regexp start-re)
  16901. (re-search-backward start-re limit-up t))
  16902. (setq beg (match-beginning 0))
  16903. ;; ... and END-RE after it...
  16904. (goto-char (match-end 0))
  16905. (re-search-forward end-re limit-down t)
  16906. (> (setq end (match-end 0)) pos)
  16907. ;; ... without another START-RE in-between.
  16908. (goto-char (match-beginning 0))
  16909. (not (re-search-backward start-re (1+ beg) t))
  16910. ;; Return value.
  16911. (cons beg end))))))
  16912. (defun org-in-block-p (names)
  16913. "Non-nil when point belongs to a block whose name belongs to NAMES.
  16914. NAMES is a list of strings containing names of blocks.
  16915. Return first block name matched, or nil. Beware that in case of
  16916. nested blocks, the returned name may not belong to the closest
  16917. block from point."
  16918. (save-match-data
  16919. (catch 'exit
  16920. (let ((case-fold-search t)
  16921. (lim-up (save-excursion (outline-previous-heading)))
  16922. (lim-down (save-excursion (outline-next-heading))))
  16923. (dolist (name names)
  16924. (let ((n (regexp-quote name)))
  16925. (when (org-between-regexps-p
  16926. (concat "^[ \t]*#\\+begin_" n)
  16927. (concat "^[ \t]*#\\+end_" n)
  16928. lim-up lim-down)
  16929. (throw 'exit n)))))
  16930. nil)))
  16931. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  16932. "Call `multi-occur' with buffers for all agenda files."
  16933. (interactive "sOrg-files matching: ")
  16934. (let* ((files (org-agenda-files))
  16935. (tnames (mapcar #'file-truename files))
  16936. (extra org-agenda-text-search-extra-files))
  16937. (when (eq (car extra) 'agenda-archives)
  16938. (setq extra (cdr extra))
  16939. (setq files (org-add-archive-files files)))
  16940. (dolist (f extra)
  16941. (unless (member (file-truename f) tnames)
  16942. (unless (member f files) (setq files (append files (list f))))
  16943. (setq tnames (append tnames (list (file-truename f))))))
  16944. (multi-occur
  16945. (mapcar (lambda (x)
  16946. (with-current-buffer
  16947. ;; FIXME: Why not just (find-file-noselect x)?
  16948. ;; Is it to avoid the "revert buffer" prompt?
  16949. (or (get-file-buffer x) (find-file-noselect x))
  16950. (widen)
  16951. (current-buffer)))
  16952. files)
  16953. regexp)))
  16954. (add-hook 'occur-mode-find-occurrence-hook
  16955. (lambda () (when (derived-mode-p 'org-mode) (org-fold-reveal))))
  16956. (defun org-occur-link-in-agenda-files ()
  16957. "Create a link and search for it in the agendas.
  16958. The link is not stored in `org-stored-links', it is just created
  16959. for the search purpose."
  16960. (interactive)
  16961. (let ((link (condition-case nil
  16962. (org-store-link nil)
  16963. (error "Unable to create a link to here"))))
  16964. (org-occur-in-agenda-files (regexp-quote link))))
  16965. (defun org-back-over-empty-lines ()
  16966. "Move backwards over whitespace, to the beginning of the first empty line.
  16967. Returns the number of empty lines passed."
  16968. (let ((pos (point)))
  16969. (if (cdr (assq 'heading org-blank-before-new-entry))
  16970. (skip-chars-backward " \t\n\r")
  16971. (unless (eobp)
  16972. (forward-line -1)))
  16973. (beginning-of-line 2)
  16974. (goto-char (min (point) pos))
  16975. (count-lines (point) pos)))
  16976. ;;; TODO: Only called once, from ox-odt which should probably use
  16977. ;;; org-export-inline-image-p or something.
  16978. (defun org-file-image-p (file)
  16979. "Return non-nil if FILE is an image."
  16980. (save-match-data
  16981. (string-match (image-file-name-regexp) file)))
  16982. (defun org-get-cursor-date (&optional with-time)
  16983. "Return the date at cursor in as a time.
  16984. This works in the calendar and in the agenda, anywhere else it just
  16985. returns the current time.
  16986. If WITH-TIME is non-nil, returns the time of the event at point (in
  16987. the agenda) or the current time of the day; otherwise returns the
  16988. earliest time on the cursor date that Org treats as that date
  16989. (bearing in mind `org-extend-today-until')."
  16990. (let (date day defd tp hod mod)
  16991. (when with-time
  16992. (setq tp (get-text-property (point) 'time))
  16993. (when (and tp (string-match "\\([0-2]?[0-9]\\):\\([0-5][0-9]\\)" tp))
  16994. (setq hod (string-to-number (match-string 1 tp))
  16995. mod (string-to-number (match-string 2 tp))))
  16996. (or tp (let ((now (decode-time)))
  16997. (setq hod (nth 2 now)
  16998. mod (nth 1 now)))))
  16999. (cond
  17000. ((eq major-mode 'calendar-mode)
  17001. (setq date (calendar-cursor-to-date)
  17002. defd (org-encode-time 0 (or mod 0) (or hod org-extend-today-until)
  17003. (nth 1 date) (nth 0 date) (nth 2 date))))
  17004. ((eq major-mode 'org-agenda-mode)
  17005. (setq day (get-text-property (point) 'day))
  17006. (when day
  17007. (setq date (calendar-gregorian-from-absolute day)
  17008. defd (org-encode-time 0 (or mod 0) (or hod org-extend-today-until)
  17009. (nth 1 date) (nth 0 date) (nth 2 date))))))
  17010. (or defd (current-time))))
  17011. (defun org-mark-subtree (&optional up)
  17012. "Mark the current subtree.
  17013. This puts point at the start of the current subtree, and mark at
  17014. the end. If a numeric prefix UP is given, move up into the
  17015. hierarchy of headlines by UP levels before marking the subtree."
  17016. (interactive "P")
  17017. (org-with-limited-levels
  17018. (cond ((org-at-heading-p) (beginning-of-line))
  17019. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  17020. (t (outline-previous-visible-heading 1))))
  17021. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  17022. (if (called-interactively-p 'any)
  17023. (call-interactively 'org-mark-element)
  17024. (org-mark-element)))
  17025. ;;; Indentation
  17026. (defun org--at-headline-data-p (&optional beg element)
  17027. "Return non-nil when `point' or BEG is inside headline metadata.
  17028. Metadata is planning line, properties drawer, logbook drawer right
  17029. after property drawer, or clock log line immediately following
  17030. properties drawer/planning line/ heading.
  17031. Optional argument ELEMENT contains element at BEG."
  17032. (org-with-wide-buffer
  17033. (when beg (goto-char beg))
  17034. (setq element (or element (org-element-at-point)))
  17035. (if (not (org-element-lineage element '(headline inlinetask)))
  17036. nil ; Not inside heading.
  17037. ;; Skip to top-level parent in section.
  17038. (while (not (eq 'section (org-element-type (org-element-property :parent element))))
  17039. (setq element (org-element-property :parent element)))
  17040. (pcase (org-element-type element)
  17041. ((or `planning `property-drawer)
  17042. t)
  17043. (`drawer
  17044. ;; LOGBOOK drawer with appropriate name.
  17045. (equal
  17046. (org-log-into-drawer)
  17047. (org-element-property :drawer-name element)))
  17048. (`clock
  17049. ;; Previous element must be headline metadata or headline.
  17050. (goto-char (1- (org-element-property :begin element)))
  17051. (or (org-at-heading-p)
  17052. (org--at-headline-data-p)))))))
  17053. (defvar org-element-greater-elements)
  17054. (defun org--get-expected-indentation (element contentsp)
  17055. "Expected indentation column for current line, according to ELEMENT.
  17056. ELEMENT is an element containing point. CONTENTSP is non-nil
  17057. when indentation is to be computed according to contents of
  17058. ELEMENT."
  17059. (let ((type (org-element-type element))
  17060. (start (org-element-property :begin element))
  17061. (post-affiliated (org-element-property :post-affiliated element)))
  17062. (org-with-wide-buffer
  17063. (cond
  17064. (contentsp
  17065. (cl-case type
  17066. ((diary-sexp footnote-definition) 0)
  17067. (section
  17068. (org--get-expected-indentation
  17069. (org-element-property :parent element)
  17070. t))
  17071. ((headline inlinetask nil)
  17072. (if (not org-adapt-indentation) 0
  17073. (let ((level (org-current-level)))
  17074. (if level (1+ level) 0))))
  17075. ((item plain-list) (org-list-item-body-column post-affiliated))
  17076. (t
  17077. (goto-char start)
  17078. (current-indentation))))
  17079. ((memq type '(headline inlinetask nil))
  17080. (if (org-match-line "[ \t]*$")
  17081. (org--get-expected-indentation element t)
  17082. 0))
  17083. ((memq type '(diary-sexp footnote-definition)) 0)
  17084. ;; First paragraph of a footnote definition or an item.
  17085. ;; Indent like parent.
  17086. ((< (line-beginning-position) start)
  17087. (org--get-expected-indentation
  17088. (org-element-property :parent element) t))
  17089. ;; At first line: indent according to previous sibling, if any,
  17090. ;; ignoring footnote definitions and inline tasks, or parent's
  17091. ;; contents. If `org-adapt-indentation' is `headline-data', ignore
  17092. ;; previous headline data siblings.
  17093. ((= (line-beginning-position) start)
  17094. (catch 'exit
  17095. (while t
  17096. (if (= (point-min) start) (throw 'exit 0)
  17097. (goto-char (1- start))
  17098. (let* ((previous (org-element-at-point))
  17099. (parent previous))
  17100. (while (and parent (<= (org-element-property :end parent) start))
  17101. (setq previous parent
  17102. parent (org-element-property :parent parent)))
  17103. (cond
  17104. ((not previous) (throw 'exit 0))
  17105. ((> (org-element-property :end previous) start)
  17106. (throw 'exit (org--get-expected-indentation previous t)))
  17107. ((memq (org-element-type previous)
  17108. '(footnote-definition inlinetask))
  17109. (setq start (org-element-property :begin previous)))
  17110. ;; Do not indent like previous when the previous
  17111. ;; element is headline data and `org-adapt-indentation'
  17112. ;; is set to `headline-data'.
  17113. ((and (eq 'headline-data org-adapt-indentation)
  17114. (not (org--at-headline-data-p start element))
  17115. (or (org-at-heading-p)
  17116. (org--at-headline-data-p (1- start) previous)))
  17117. (throw 'exit 0))
  17118. (t (goto-char (org-element-property :begin previous))
  17119. (throw 'exit
  17120. (if (bolp) (current-indentation)
  17121. ;; At first paragraph in an item or
  17122. ;; a footnote definition.
  17123. (org--get-expected-indentation
  17124. (org-element-property :parent previous) t))))))))))
  17125. ;; Otherwise, move to the first non-blank line above.
  17126. (t
  17127. (beginning-of-line)
  17128. (let ((pos (point)))
  17129. (skip-chars-backward " \r\t\n")
  17130. (cond
  17131. ;; Two blank lines end a footnote definition or a plain
  17132. ;; list. When we indent an empty line after them, the
  17133. ;; containing list or footnote definition is over, so it
  17134. ;; qualifies as a previous sibling. Therefore, we indent
  17135. ;; like its first line.
  17136. ((and (memq type '(footnote-definition plain-list))
  17137. (> (count-lines (point) pos) 2))
  17138. (goto-char start)
  17139. (current-indentation))
  17140. ;; Line above is the first one of a paragraph at the
  17141. ;; beginning of an item or a footnote definition. Indent
  17142. ;; like parent.
  17143. ((< (line-beginning-position) start)
  17144. (org--get-expected-indentation
  17145. (org-element-property :parent element) t))
  17146. ;; Line above is the beginning of an element, i.e., point
  17147. ;; was originally on the blank lines between element's start
  17148. ;; and contents.
  17149. ((= (line-beginning-position) post-affiliated)
  17150. (org--get-expected-indentation element t))
  17151. ;; POS is after contents in a greater element. Indent like
  17152. ;; the beginning of the element.
  17153. ((and (memq type org-element-greater-elements)
  17154. (let ((cend (org-element-property :contents-end element)))
  17155. (and cend (<= cend pos))))
  17156. ;; As a special case, if point is at the end of a footnote
  17157. ;; definition or an item, indent like the very last element
  17158. ;; within. If that last element is an item, indent like
  17159. ;; its contents.
  17160. (if (memq type '(footnote-definition item plain-list))
  17161. (let ((last (org-element-at-point)))
  17162. (goto-char pos)
  17163. (org--get-expected-indentation
  17164. last (eq (org-element-type last) 'item)))
  17165. (goto-char start)
  17166. (current-indentation)))
  17167. ;; In any other case, indent like the current line.
  17168. (t (current-indentation)))))
  17169. ;; Finally, no indentation is needed, fall back to 0.
  17170. (t (current-indentation))))))
  17171. (defun org--align-node-property ()
  17172. "Align node property at point.
  17173. Alignment is done according to `org-property-format', which see."
  17174. (when (save-excursion
  17175. (beginning-of-line)
  17176. (looking-at org-property-re))
  17177. (combine-change-calls (match-beginning 0) (match-end 0)
  17178. (let ((newtext (concat (match-string 4)
  17179. (org-trim
  17180. (format org-property-format (match-string 1) (match-string 3))))))
  17181. ;; Do not use `replace-match' here as we want to inherit folding
  17182. ;; properties if inside fold.
  17183. (delete-region (match-beginning 0) (match-end 0))
  17184. (insert-and-inherit newtext)))))
  17185. (defun org-indent-line ()
  17186. "Indent line depending on context.
  17187. Indentation is done according to the following rules:
  17188. - Footnote definitions, diary sexps, headlines and inline tasks
  17189. have to start at column 0.
  17190. - On the very first line of an element, consider, in order, the
  17191. next rules until one matches:
  17192. 1. If there's a sibling element before, ignoring footnote
  17193. definitions and inline tasks, indent like its first line.
  17194. 2. If element has a parent, indent like its contents. More
  17195. precisely, if parent is an item, indent after the bullet.
  17196. Else, indent like parent's first line.
  17197. 3. Otherwise, indent relatively to current level, if
  17198. `org-adapt-indentation' is t, or to left margin.
  17199. - On a blank line at the end of an element, indent according to
  17200. the type of the element. More precisely
  17201. 1. If element is a plain list, an item, or a footnote
  17202. definition, indent like the very last element within.
  17203. 2. If element is a paragraph, indent like its last non blank
  17204. line.
  17205. 3. Otherwise, indent like its very first line.
  17206. - In the code part of a source block, use language major mode
  17207. to indent current line if `org-src-tab-acts-natively' is
  17208. non-nil. If it is nil, do nothing.
  17209. - Otherwise, indent like the first non-blank line above.
  17210. The function doesn't indent an item as it could break the whole
  17211. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  17212. `\\[org-shiftmetaright]'.
  17213. Also align node properties according to `org-property-format'."
  17214. (interactive)
  17215. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point-no-context)))
  17216. (type (org-element-type element)))
  17217. (unless (or (org-at-heading-p)
  17218. (and (eq org-adapt-indentation 'headline-data)
  17219. (not (org--at-headline-data-p nil element))
  17220. (save-excursion
  17221. (goto-char (1- (org-element-property :begin element)))
  17222. (or (org-at-heading-p)
  17223. (org--at-headline-data-p)))))
  17224. (cond ((and (memq type '(plain-list item))
  17225. (= (line-beginning-position)
  17226. (org-element-property :post-affiliated element)))
  17227. nil)
  17228. ((and (eq type 'latex-environment)
  17229. (>= (point) (org-element-property :post-affiliated element))
  17230. (< (point)
  17231. (org-with-point-at (org-element-property :end element)
  17232. (skip-chars-backward " \t\n")
  17233. (line-beginning-position 2))))
  17234. nil)
  17235. ((and (eq type 'src-block)
  17236. org-src-tab-acts-natively
  17237. (> (line-beginning-position)
  17238. (org-element-property :post-affiliated element))
  17239. (< (line-beginning-position)
  17240. (org-with-point-at (org-element-property :end element)
  17241. (skip-chars-backward " \t\n")
  17242. (line-beginning-position))))
  17243. ;; At the beginning of a blank line, do some preindentation. This
  17244. ;; signals org-src--edit-element to preserve the indentation on exit
  17245. (when (and (looking-at-p "^[[:space:]]*$")
  17246. (not org-src-preserve-indentation))
  17247. (let ((element (org-element-at-point))
  17248. block-content-ind some-ind)
  17249. (org-with-point-at (org-element-property :begin element)
  17250. (setq block-content-ind (+ (org-current-text-indentation)
  17251. org-edit-src-content-indentation))
  17252. (forward-line)
  17253. (save-match-data (re-search-forward "^[ \t]*\\S-" nil t))
  17254. (backward-char)
  17255. (setq some-ind (if (looking-at-p "#\\+end_src")
  17256. block-content-ind (org-current-text-indentation))))
  17257. (indent-line-to (min block-content-ind some-ind))))
  17258. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  17259. (t
  17260. (let ((column (org--get-expected-indentation element nil)))
  17261. ;; Preserve current column.
  17262. (if (<= (current-column) (current-indentation))
  17263. (indent-line-to column)
  17264. (save-excursion (indent-line-to column))))
  17265. ;; Align node property. Also preserve current column.
  17266. (when (eq type 'node-property)
  17267. (let ((column (current-column)))
  17268. (org--align-node-property)
  17269. (org-move-to-column column))))))))
  17270. (defun org-indent-region (start end)
  17271. "Indent each non-blank line in the region.
  17272. Called from a program, START and END specify the region to
  17273. indent. The function will not indent contents of example blocks,
  17274. verse blocks and export blocks as leading white spaces are
  17275. assumed to be significant there."
  17276. (interactive "r")
  17277. (save-excursion
  17278. (goto-char start)
  17279. (skip-chars-forward " \r\t\n")
  17280. (unless (eobp) (beginning-of-line))
  17281. (let ((indent-to
  17282. (lambda (ind pos)
  17283. ;; Set IND as indentation for all lines between point and
  17284. ;; POS. Blank lines are ignored. Leave point after POS
  17285. ;; once done.
  17286. (let ((limit (copy-marker pos)))
  17287. (while (< (point) limit)
  17288. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  17289. (forward-line))
  17290. (set-marker limit nil))))
  17291. (end (copy-marker end)))
  17292. (while (< (point) end)
  17293. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  17294. (let* ((element (org-element-at-point))
  17295. (type (org-element-type element))
  17296. (element-end (copy-marker (org-element-property :end element)))
  17297. (ind (org--get-expected-indentation element nil)))
  17298. (cond
  17299. ;; Element indented as a single block. Example blocks
  17300. ;; preserving indentation are a special case since the
  17301. ;; "contents" must not be indented whereas the block
  17302. ;; boundaries can.
  17303. ((or (memq type '(export-block latex-environment))
  17304. (and (eq type 'example-block)
  17305. (not
  17306. (or org-src-preserve-indentation
  17307. (org-element-property :preserve-indent element)))))
  17308. (let ((offset (- ind (current-indentation))))
  17309. (unless (zerop offset)
  17310. (indent-rigidly (org-element-property :begin element)
  17311. (org-element-property :end element)
  17312. offset)))
  17313. (goto-char element-end))
  17314. ;; Elements indented line wise. Be sure to exclude
  17315. ;; example blocks (preserving indentation) and source
  17316. ;; blocks from this category as they are treated
  17317. ;; specially later.
  17318. ((or (memq type '(paragraph table table-row))
  17319. (not (or (org-element-property :contents-begin element)
  17320. (memq type '(example-block src-block)))))
  17321. (when (eq type 'node-property)
  17322. (org--align-node-property)
  17323. (beginning-of-line))
  17324. (funcall indent-to ind (min element-end end)))
  17325. ;; Elements consisting of three parts: before the
  17326. ;; contents, the contents, and after the contents. The
  17327. ;; contents are treated specially, according to the
  17328. ;; element type, or not indented at all. Other parts are
  17329. ;; indented as a single block.
  17330. (t
  17331. (let* ((post (copy-marker
  17332. (org-element-property :post-affiliated element)))
  17333. (cbeg
  17334. (copy-marker
  17335. (cond
  17336. ((not (org-element-property :contents-begin element))
  17337. ;; Fake contents for source blocks.
  17338. (org-with-wide-buffer
  17339. (goto-char post)
  17340. (line-beginning-position 2)))
  17341. ((memq type '(footnote-definition item plain-list))
  17342. ;; Contents in these elements could start on
  17343. ;; the same line as the beginning of the
  17344. ;; element. Make sure we start indenting
  17345. ;; from the second line.
  17346. (org-with-wide-buffer
  17347. (goto-char post)
  17348. (end-of-line)
  17349. (skip-chars-forward " \r\t\n")
  17350. (if (eobp) (point) (line-beginning-position))))
  17351. (t (org-element-property :contents-begin element)))))
  17352. (cend (copy-marker
  17353. (or (org-element-property :contents-end element)
  17354. ;; Fake contents for source blocks.
  17355. (org-with-wide-buffer
  17356. (goto-char element-end)
  17357. (skip-chars-backward " \r\t\n")
  17358. (line-beginning-position)))
  17359. t)))
  17360. ;; Do not change items indentation individually as it
  17361. ;; might break the list as a whole. On the other
  17362. ;; hand, when at a plain list, indent it as a whole.
  17363. (cond ((eq type 'plain-list)
  17364. (let ((offset (- ind (org-current-text-indentation))))
  17365. (unless (zerop offset)
  17366. (indent-rigidly (org-element-property :begin element)
  17367. (org-element-property :end element)
  17368. offset))
  17369. (goto-char cbeg)))
  17370. ((eq type 'item) (goto-char cbeg))
  17371. (t (funcall indent-to ind (min cbeg end))))
  17372. (when (< (point) end)
  17373. (cl-case type
  17374. ((example-block verse-block))
  17375. (src-block
  17376. ;; In a source block, indent source code
  17377. ;; according to language major mode, but only if
  17378. ;; `org-src-tab-acts-natively' is non-nil.
  17379. (when (and (< (point) end) org-src-tab-acts-natively)
  17380. (ignore-errors
  17381. (org-babel-do-in-edit-buffer
  17382. (indent-region (point-min) (point-max))))))
  17383. (t (org-indent-region (point) (min cend end))))
  17384. (goto-char (min cend end))
  17385. (when (< (point) end)
  17386. (funcall indent-to ind (min element-end end))))
  17387. (set-marker post nil)
  17388. (set-marker cbeg nil)
  17389. (set-marker cend nil))))
  17390. (set-marker element-end nil))))
  17391. (set-marker end nil))))
  17392. (defun org-indent-drawer ()
  17393. "Indent the drawer at point."
  17394. (interactive)
  17395. (unless (save-excursion
  17396. (beginning-of-line)
  17397. (looking-at-p org-drawer-regexp))
  17398. (user-error "Not at a drawer"))
  17399. (let ((element (org-element-at-point-no-context)))
  17400. (unless (memq (org-element-type element) '(drawer property-drawer))
  17401. (user-error "Not at a drawer"))
  17402. (org-with-wide-buffer
  17403. (org-indent-region (org-element-property :begin element)
  17404. (org-element-property :end element))))
  17405. (message "Drawer at point indented"))
  17406. (defun org-indent-block ()
  17407. "Indent the block at point."
  17408. (interactive)
  17409. (unless (save-excursion
  17410. (beginning-of-line)
  17411. (let ((case-fold-search t))
  17412. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  17413. (user-error "Not at a block"))
  17414. (let ((element (org-element-at-point-no-context)))
  17415. (unless (memq (org-element-type element)
  17416. '(comment-block center-block dynamic-block example-block
  17417. export-block quote-block special-block
  17418. src-block verse-block))
  17419. (user-error "Not at a block"))
  17420. (org-with-wide-buffer
  17421. (org-indent-region (org-element-property :begin element)
  17422. (org-element-property :end element))))
  17423. (message "Block at point indented"))
  17424. ;;; Filling
  17425. ;; We use our own fill-paragraph and auto-fill functions.
  17426. ;; `org-fill-paragraph' relies on adaptive filling and context
  17427. ;; checking. Appropriate `fill-prefix' is computed with
  17428. ;; `org-adaptive-fill-function'.
  17429. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  17430. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  17431. ;; `org-adaptive-fill-function' value. Internally,
  17432. ;; `org-comment-line-break-function' breaks the line.
  17433. ;; `org-setup-filling' installs filling and auto-filling related
  17434. ;; variables during `org-mode' initialization.
  17435. (defvar org--single-lines-list-is-paragraph) ; defined later
  17436. (defun org-setup-filling ()
  17437. (require 'org-element)
  17438. ;; Prevent auto-fill from inserting unwanted new items.
  17439. (setq-local fill-nobreak-predicate
  17440. (org-uniquify
  17441. (append fill-nobreak-predicate
  17442. '(org-fill-line-break-nobreak-p
  17443. org-fill-n-macro-as-item-nobreak-p
  17444. org-fill-paragraph-with-timestamp-nobreak-p))))
  17445. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  17446. (setq-local paragraph-start paragraph-ending)
  17447. (setq-local paragraph-separate paragraph-ending))
  17448. (setq-local fill-paragraph-function 'org-fill-paragraph)
  17449. (setq-local fill-forward-paragraph-function
  17450. (lambda (&optional arg)
  17451. (let ((org--single-lines-list-is-paragraph nil))
  17452. (org-forward-paragraph arg))))
  17453. (setq-local auto-fill-inhibit-regexp nil)
  17454. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  17455. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  17456. (setq-local comment-line-break-function 'org-comment-line-break-function))
  17457. (defun org-fill-line-break-nobreak-p ()
  17458. "Non-nil when a new line at point would create an Org line break."
  17459. (save-excursion
  17460. (skip-chars-backward " \t")
  17461. (skip-chars-backward "\\\\")
  17462. (looking-at "\\\\\\\\\\($\\|[^\\]\\)")))
  17463. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  17464. "Non-nil when a new line at point would split a timestamp."
  17465. (and (org-at-timestamp-p 'lax)
  17466. (not (looking-at org-ts-regexp-both))))
  17467. (defun org-fill-n-macro-as-item-nobreak-p ()
  17468. "Non-nil when a new line at point would create a new list."
  17469. ;; During export, a "n" macro followed by a dot or a closing
  17470. ;; parenthesis can end up being parsed as a new list item.
  17471. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  17472. (defun org-adaptive-fill-function ()
  17473. "Compute a fill prefix for the current line.
  17474. Return fill prefix, as a string, or nil if current line isn't
  17475. meant to be filled. For convenience, if `adaptive-fill-regexp'
  17476. matches in paragraphs or comments, use it."
  17477. (org-with-wide-buffer
  17478. (unless (org-at-heading-p)
  17479. (let* ((p (line-beginning-position))
  17480. (element (save-excursion
  17481. (beginning-of-line)
  17482. (org-element-at-point)))
  17483. (type (org-element-type element))
  17484. (post-affiliated (org-element-property :post-affiliated element)))
  17485. (unless (< p post-affiliated)
  17486. (cl-case type
  17487. (comment
  17488. (save-excursion
  17489. (beginning-of-line)
  17490. (looking-at "[ \t]*")
  17491. (concat (match-string 0) "# ")))
  17492. (footnote-definition "")
  17493. ((item plain-list)
  17494. (make-string (org-list-item-body-column post-affiliated) ?\s))
  17495. (paragraph
  17496. ;; Fill prefix is usually the same as the current line,
  17497. ;; unless the paragraph is at the beginning of an item.
  17498. (let ((parent (org-element-property :parent element)))
  17499. (save-excursion
  17500. (beginning-of-line)
  17501. (cond ((eq (org-element-type parent) 'item)
  17502. (make-string (org-list-item-body-column
  17503. (org-element-property :begin parent))
  17504. ?\s))
  17505. ((and adaptive-fill-regexp
  17506. ;; Locally disable
  17507. ;; `adaptive-fill-function' to let
  17508. ;; `fill-context-prefix' handle
  17509. ;; `adaptive-fill-regexp' variable.
  17510. (let (adaptive-fill-function)
  17511. (fill-context-prefix
  17512. post-affiliated
  17513. (org-element-property :end element)))))
  17514. ((looking-at "[ \t]+") (match-string 0))
  17515. (t "")))))
  17516. (comment-block
  17517. ;; Only fill contents if P is within block boundaries.
  17518. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  17519. (forward-line)
  17520. (point)))
  17521. (cend (save-excursion
  17522. (goto-char (org-element-property :end element))
  17523. (skip-chars-backward " \r\t\n")
  17524. (line-beginning-position))))
  17525. (when (and (>= p cbeg) (< p cend))
  17526. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  17527. (match-string 0)
  17528. ""))))))))))
  17529. (defun org-fill-element (&optional justify)
  17530. "Fill element at point, when applicable.
  17531. This function only applies to comment blocks, comments, example
  17532. blocks and paragraphs. Also, as a special case, re-align table
  17533. when point is at one.
  17534. If JUSTIFY is non-nil (interactively, with prefix argument),
  17535. justify as well. If `sentence-end-double-space' is non-nil, then
  17536. period followed by one space does not end a sentence, so don't
  17537. break a line there. The variable `fill-column' controls the
  17538. width for filling.
  17539. For convenience, when point is at a plain list, an item or
  17540. a footnote definition, try to fill the first paragraph within."
  17541. (with-syntax-table org-mode-transpose-word-syntax-table
  17542. ;; Move to end of line in order to get the first paragraph within
  17543. ;; a plain list or a footnote definition.
  17544. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  17545. ;; First check if point is in a blank line at the beginning of
  17546. ;; the buffer. In that case, ignore filling.
  17547. (cl-case (org-element-type element)
  17548. ;; Use major mode filling function is source blocks.
  17549. (src-block
  17550. (let ((regionp (region-active-p)))
  17551. (org-babel-do-in-edit-buffer
  17552. ;; `org-babel-do-in-edit-buffer' will preserve region if it
  17553. ;; is within src block contents. Otherwise, the region
  17554. ;; crosses src block boundaries. We re-fill the whole src
  17555. ;; block in such scenario.
  17556. (when (and regionp (not (region-active-p)))
  17557. (push-mark (point-min))
  17558. (goto-char (point-max))
  17559. (setq mark-active t))
  17560. (funcall-interactively #'fill-paragraph justify 'region))))
  17561. ;; Align Org tables, leave table.el tables as-is.
  17562. (table-row (org-table-align) t)
  17563. (table
  17564. (when (eq (org-element-property :type element) 'org)
  17565. (save-excursion
  17566. (goto-char (org-element-property :post-affiliated element))
  17567. (org-table-align)))
  17568. t)
  17569. (paragraph
  17570. ;; Paragraphs may contain `line-break' type objects.
  17571. (let ((beg (max (point-min)
  17572. (org-element-property :contents-begin element)))
  17573. (end (min (point-max)
  17574. (org-element-property :contents-end element))))
  17575. ;; Do nothing if point is at an affiliated keyword.
  17576. (if (< (line-end-position) beg) t
  17577. ;; Fill paragraph, taking line breaks into account.
  17578. (save-excursion
  17579. (goto-char beg)
  17580. (let ((cuts (list beg)))
  17581. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  17582. (when (eq 'line-break
  17583. (org-element-type
  17584. (save-excursion (backward-char)
  17585. (org-element-context))))
  17586. (push (point) cuts)))
  17587. (dolist (c (delq end cuts))
  17588. (fill-region-as-paragraph c end justify)
  17589. (setq end c))))
  17590. t)))
  17591. ;; Contents of `comment-block' type elements should be
  17592. ;; filled as plain text, but only if point is within block
  17593. ;; markers.
  17594. (comment-block
  17595. (let* ((case-fold-search t)
  17596. (beg (save-excursion
  17597. (goto-char (org-element-property :begin element))
  17598. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  17599. (forward-line)
  17600. (point)))
  17601. (end (save-excursion
  17602. (goto-char (org-element-property :end element))
  17603. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  17604. (line-beginning-position))))
  17605. (if (or (< (point) beg) (> (point) end)) t
  17606. (fill-region-as-paragraph
  17607. (save-excursion (end-of-line)
  17608. (re-search-backward "^[ \t]*$" beg 'move)
  17609. (line-beginning-position))
  17610. (save-excursion (beginning-of-line)
  17611. (re-search-forward "^[ \t]*$" end 'move)
  17612. (line-beginning-position))
  17613. justify))))
  17614. ;; Fill comments.
  17615. (comment
  17616. (let ((begin (org-element-property :post-affiliated element))
  17617. (end (org-element-property :end element)))
  17618. (when (and (>= (point) begin) (<= (point) end))
  17619. (let ((begin (save-excursion
  17620. (end-of-line)
  17621. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  17622. (progn (forward-line) (point))
  17623. begin)))
  17624. (end (save-excursion
  17625. (end-of-line)
  17626. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  17627. (1- (line-beginning-position))
  17628. (skip-chars-backward " \r\t\n")
  17629. (line-end-position)))))
  17630. ;; Do not fill comments when at a blank line.
  17631. (when (> end begin)
  17632. (let ((fill-prefix
  17633. (save-excursion
  17634. (beginning-of-line)
  17635. (looking-at "[ \t]*#")
  17636. (let ((comment-prefix (match-string 0)))
  17637. (goto-char (match-end 0))
  17638. (if (looking-at adaptive-fill-regexp)
  17639. (concat comment-prefix (match-string 0))
  17640. (concat comment-prefix " "))))))
  17641. (save-excursion
  17642. (fill-region-as-paragraph begin end justify))))))
  17643. t))
  17644. ;; Ignore every other element.
  17645. (otherwise t)))))
  17646. (defun org-fill-paragraph (&optional justify region)
  17647. "Fill element at point, when applicable.
  17648. This function only applies to comment blocks, comments, example
  17649. blocks and paragraphs. Also, as a special case, re-align table
  17650. when point is at one.
  17651. For convenience, when point is at a plain list, an item or
  17652. a footnote definition, try to fill the first paragraph within.
  17653. If JUSTIFY is non-nil (interactively, with prefix argument),
  17654. justify as well. If `sentence-end-double-space' is non-nil, then
  17655. period followed by one space does not end a sentence, so don't
  17656. break a line there. The variable `fill-column' controls the
  17657. width for filling.
  17658. The REGION argument is non-nil if called interactively; in that
  17659. case, if Transient Mark mode is enabled and the mark is active,
  17660. fill each of the elements in the active region, instead of just
  17661. filling the current element."
  17662. (interactive (progn
  17663. (barf-if-buffer-read-only)
  17664. (list (when current-prefix-arg 'full) t)))
  17665. (let ((hash (and (not (buffer-modified-p))
  17666. (org-buffer-hash))))
  17667. (cond
  17668. ((and region transient-mark-mode mark-active
  17669. (not (eq (region-beginning) (region-end))))
  17670. (let ((origin (point-marker))
  17671. (start (region-beginning)))
  17672. (unwind-protect
  17673. (progn
  17674. (goto-char (region-end))
  17675. (skip-chars-backward " \t\n")
  17676. (let ((org--single-lines-list-is-paragraph nil))
  17677. (while (> (point) start)
  17678. (org-fill-element justify)
  17679. (org-backward-paragraph)
  17680. (skip-chars-backward " \t\n"))))
  17681. (goto-char origin)
  17682. (set-marker origin nil))))
  17683. (t
  17684. (save-excursion
  17685. (when (org-match-line "[ \t]*$")
  17686. (skip-chars-forward " \t\n"))
  17687. (org-fill-element justify))))
  17688. ;; If we didn't change anything in the buffer (and the buffer was
  17689. ;; previously unmodified), then flip the modification status back
  17690. ;; to "unchanged".
  17691. (when (and hash (equal hash (org-buffer-hash)))
  17692. (set-buffer-modified-p nil))
  17693. ;; Return non-nil.
  17694. t))
  17695. (defun org-auto-fill-function ()
  17696. "Auto-fill function."
  17697. ;; Check if auto-filling is meaningful.
  17698. (let ((fc (current-fill-column)))
  17699. (when (and fc (> (current-column) fc))
  17700. (let* ((fill-prefix (org-adaptive-fill-function))
  17701. ;; Enforce empty fill prefix, if required. Otherwise, it
  17702. ;; will be computed again.
  17703. (adaptive-fill-mode (not (equal fill-prefix ""))))
  17704. (when fill-prefix (do-auto-fill))))))
  17705. (defun org-comment-line-break-function (&optional soft)
  17706. "Break line at point and indent, continuing comment if within one.
  17707. The inserted newline is marked hard if variable
  17708. `use-hard-newlines' is true, unless optional argument SOFT is
  17709. non-nil.
  17710. This function is a simplified version of `comment-indent-new-line'
  17711. that bypasses the complex Emacs machinery dealing with comments.
  17712. We instead rely on Org parser, utilizing `org-adaptive-fill-function'"
  17713. (let ((fill-prefix (org-adaptive-fill-function)))
  17714. (if soft (insert-and-inherit ?\n) (newline 1))
  17715. (save-excursion (forward-char -1) (delete-horizontal-space))
  17716. (delete-horizontal-space)
  17717. (indent-to-left-margin)
  17718. (when fill-prefix
  17719. (insert-before-markers-and-inherit fill-prefix))))
  17720. ;;; Fixed Width Areas
  17721. (defun org-toggle-fixed-width ()
  17722. "Toggle fixed-width markup.
  17723. Add or remove fixed-width markup on current line, whenever it
  17724. makes sense. Return an error otherwise.
  17725. If a region is active and if it contains only fixed-width areas
  17726. or blank lines, remove all fixed-width markup in it. If the
  17727. region contains anything else, convert all non-fixed-width lines
  17728. to fixed-width ones.
  17729. Blank lines at the end of the region are ignored unless the
  17730. region only contains such lines."
  17731. (interactive)
  17732. (if (not (org-region-active-p))
  17733. ;; No region:
  17734. ;;
  17735. ;; Remove fixed width marker only in a fixed-with element.
  17736. ;;
  17737. ;; Add fixed width maker in paragraphs, in blank lines after
  17738. ;; elements or at the beginning of a headline or an inlinetask,
  17739. ;; and before any one-line elements (e.g., a clock).
  17740. (progn
  17741. (beginning-of-line)
  17742. (let* ((element (org-element-at-point))
  17743. (type (org-element-type element)))
  17744. (cond
  17745. ((and (eq type 'fixed-width)
  17746. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  17747. (replace-match
  17748. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  17749. ((and (memq type '(babel-call clock comment diary-sexp headline
  17750. horizontal-rule keyword paragraph
  17751. planning))
  17752. (<= (org-element-property :post-affiliated element) (point)))
  17753. (skip-chars-forward " \t")
  17754. (insert ": "))
  17755. ((and (looking-at-p "[ \t]*$")
  17756. (or (eq type 'inlinetask)
  17757. (save-excursion
  17758. (skip-chars-forward " \r\t\n")
  17759. (<= (org-element-property :end element) (point)))))
  17760. (delete-region (point) (line-end-position))
  17761. (org-indent-line)
  17762. (insert ": "))
  17763. (t (user-error "Cannot insert a fixed-width line here")))))
  17764. ;; Region active.
  17765. (let* ((begin (save-excursion
  17766. (goto-char (region-beginning))
  17767. (line-beginning-position)))
  17768. (end (copy-marker
  17769. (save-excursion
  17770. (goto-char (region-end))
  17771. (unless (eolp) (beginning-of-line))
  17772. (if (save-excursion (re-search-backward "\\S-" begin t))
  17773. (progn (skip-chars-backward " \r\t\n") (point))
  17774. (point)))))
  17775. (all-fixed-width-p
  17776. (catch 'not-all-p
  17777. (save-excursion
  17778. (goto-char begin)
  17779. (skip-chars-forward " \r\t\n")
  17780. (when (eobp) (throw 'not-all-p nil))
  17781. (while (< (point) end)
  17782. (let ((element (org-element-at-point)))
  17783. (if (eq (org-element-type element) 'fixed-width)
  17784. (goto-char (org-element-property :end element))
  17785. (throw 'not-all-p nil))))
  17786. t))))
  17787. (if all-fixed-width-p
  17788. (save-excursion
  17789. (goto-char begin)
  17790. (while (< (point) end)
  17791. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  17792. (replace-match
  17793. "" nil nil nil
  17794. (if (= (line-end-position) (match-end 0)) 0 1)))
  17795. (forward-line)))
  17796. (let ((min-ind (point-max)))
  17797. ;; Find minimum indentation across all lines.
  17798. (save-excursion
  17799. (goto-char begin)
  17800. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  17801. (setq min-ind 0)
  17802. (catch 'zerop
  17803. (while (< (point) end)
  17804. (unless (looking-at-p "[ \t]*$")
  17805. (let ((ind (org-current-text-indentation)))
  17806. (setq min-ind (min min-ind ind))
  17807. (when (zerop ind) (throw 'zerop t))))
  17808. (forward-line)))))
  17809. ;; Loop over all lines and add fixed-width markup everywhere
  17810. ;; but in fixed-width lines.
  17811. (save-excursion
  17812. (goto-char begin)
  17813. (while (< (point) end)
  17814. (cond
  17815. ((org-at-heading-p)
  17816. (insert ": ")
  17817. (forward-line)
  17818. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  17819. (insert ":")
  17820. (forward-line)))
  17821. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  17822. (let* ((element (org-element-at-point))
  17823. (element-end (org-element-property :end element)))
  17824. (if (eq (org-element-type element) 'fixed-width)
  17825. (progn (goto-char element-end)
  17826. (skip-chars-backward " \r\t\n")
  17827. (forward-line))
  17828. (let ((limit (min end element-end)))
  17829. (while (< (point) limit)
  17830. (org-move-to-column min-ind t)
  17831. (insert ": ")
  17832. (forward-line))))))
  17833. (t
  17834. (org-move-to-column min-ind t)
  17835. (insert ": ")
  17836. (forward-line)))))))
  17837. (set-marker end nil))))
  17838. ;;; Blocks
  17839. (defun org-block-map (function &optional start end)
  17840. "Call FUNCTION at the head of all source blocks in the current buffer.
  17841. Optional arguments START and END can be used to limit the range."
  17842. (let ((start (or start (point-min)))
  17843. (end (or end (point-max))))
  17844. (save-excursion
  17845. (goto-char start)
  17846. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  17847. (save-excursion
  17848. (save-match-data
  17849. (goto-char (match-beginning 0))
  17850. (funcall function)))))))
  17851. (defun org-next-block (arg &optional backward block-regexp)
  17852. "Jump to the next block.
  17853. With a prefix argument ARG, jump forward ARG many blocks.
  17854. When BACKWARD is non-nil, jump to the previous block.
  17855. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  17856. Match data is set according to this regexp when the function
  17857. returns.
  17858. Return point at beginning of the opening line of found block.
  17859. Throw an error if no block is found."
  17860. (interactive "p")
  17861. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  17862. (case-fold-search t)
  17863. (search-fn (if backward #'re-search-backward #'re-search-forward))
  17864. (count (or arg 1))
  17865. (origin (point))
  17866. last-element)
  17867. (if backward (beginning-of-line) (end-of-line))
  17868. (while (and (> count 0) (funcall search-fn re nil t))
  17869. (let ((element (save-excursion
  17870. (goto-char (match-beginning 0))
  17871. (save-match-data (org-element-at-point)))))
  17872. (when (and (memq (org-element-type element)
  17873. '(center-block comment-block dynamic-block
  17874. example-block export-block quote-block
  17875. special-block src-block verse-block))
  17876. (<= (match-beginning 0)
  17877. (org-element-property :post-affiliated element)))
  17878. (setq last-element element)
  17879. (cl-decf count))))
  17880. (if (= count 0)
  17881. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  17882. (save-match-data (org-fold-show-context)))
  17883. (goto-char origin)
  17884. (user-error "No %s code blocks" (if backward "previous" "further")))))
  17885. (defun org-previous-block (arg &optional block-regexp)
  17886. "Jump to the previous block.
  17887. With a prefix argument ARG, jump backward ARG many source blocks.
  17888. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  17889. (interactive "p")
  17890. (org-next-block arg t block-regexp))
  17891. ;;; Comments
  17892. ;; Org comments syntax is quite complex. It requires the entire line
  17893. ;; to be just a comment. Also, even with the right syntax at the
  17894. ;; beginning of line, some elements (e.g., verse-block or
  17895. ;; example-block) don't accept comments. Usual Emacs comment commands
  17896. ;; cannot cope with those requirements. Therefore, Org replaces them.
  17897. ;; Org still relies on 'comment-dwim', but cannot trust
  17898. ;; 'comment-only-p'. So, 'comment-region-function' and
  17899. ;; 'uncomment-region-function' both point
  17900. ;; to 'org-comment-or-uncomment-region'. Eventually,
  17901. ;; 'org-insert-comment' takes care of insertion of comments at the
  17902. ;; beginning of line.
  17903. ;; 'org-setup-comments-handling' install comments related variables
  17904. ;; during 'org-mode' initialization.
  17905. (defun org-setup-comments-handling ()
  17906. (interactive)
  17907. (setq-local comment-use-syntax nil)
  17908. (setq-local comment-start "# ")
  17909. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  17910. (setq-local comment-insert-comment-function 'org-insert-comment)
  17911. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  17912. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  17913. (defun org-insert-comment ()
  17914. "Insert an empty comment above current line.
  17915. If the line is empty, insert comment at its beginning. When
  17916. point is within a source block, comment according to the related
  17917. major mode."
  17918. (if (let ((element (org-element-at-point)))
  17919. (and (eq (org-element-type element) 'src-block)
  17920. (< (save-excursion
  17921. (goto-char (org-element-property :post-affiliated element))
  17922. (line-end-position))
  17923. (point))
  17924. (> (save-excursion
  17925. (goto-char (org-element-property :end element))
  17926. (skip-chars-backward " \r\t\n")
  17927. (line-beginning-position))
  17928. (point))))
  17929. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  17930. (beginning-of-line)
  17931. (if (looking-at "\\s-*$") (delete-region (point) (line-end-position))
  17932. (open-line 1))
  17933. (org-indent-line)
  17934. (insert "# ")))
  17935. (defvar comment-empty-lines) ; From newcomment.el.
  17936. (defun org-comment-or-uncomment-region (beg end &rest _)
  17937. "Comment or uncomment each non-blank line in the region.
  17938. Uncomment each non-blank line between BEG and END if it only
  17939. contains commented lines. Otherwise, comment them. If region is
  17940. strictly within a source block, use appropriate comment syntax."
  17941. (if (let ((element (org-element-at-point)))
  17942. (and (eq (org-element-type element) 'src-block)
  17943. (< (save-excursion
  17944. (goto-char (org-element-property :post-affiliated element))
  17945. (line-end-position))
  17946. beg)
  17947. (>= (save-excursion
  17948. (goto-char (org-element-property :end element))
  17949. (skip-chars-backward " \r\t\n")
  17950. (line-beginning-position))
  17951. end)))
  17952. ;; Translate region boundaries for the Org buffer to the source
  17953. ;; buffer.
  17954. (let ((offset (- end beg)))
  17955. (save-excursion
  17956. (goto-char beg)
  17957. (org-babel-do-in-edit-buffer
  17958. (comment-or-uncomment-region (point) (+ offset (point))))))
  17959. (save-restriction
  17960. ;; Restrict region
  17961. (narrow-to-region (save-excursion (goto-char beg)
  17962. (skip-chars-forward " \r\t\n" end)
  17963. (line-beginning-position))
  17964. (save-excursion (goto-char end)
  17965. (skip-chars-backward " \r\t\n" beg)
  17966. (line-end-position)))
  17967. (let ((uncommentp
  17968. ;; UNCOMMENTP is non-nil when every non blank line between
  17969. ;; BEG and END is a comment.
  17970. (save-excursion
  17971. (goto-char (point-min))
  17972. (while (and (not (eobp))
  17973. (let ((element (org-element-at-point)))
  17974. (and (eq (org-element-type element) 'comment)
  17975. (goto-char (min (point-max)
  17976. (org-element-property
  17977. :end element)))))))
  17978. (eobp))))
  17979. (if uncommentp
  17980. ;; Only blank lines and comments in region: uncomment it.
  17981. (save-excursion
  17982. (goto-char (point-min))
  17983. (while (not (eobp))
  17984. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  17985. (replace-match "" nil nil nil 1))
  17986. (forward-line)))
  17987. ;; Comment each line in region.
  17988. (let ((min-indent (point-max)))
  17989. ;; First find the minimum indentation across all lines.
  17990. (save-excursion
  17991. (goto-char (point-min))
  17992. (while (and (not (eobp)) (not (zerop min-indent)))
  17993. (unless (looking-at "[ \t]*$")
  17994. (setq min-indent (min min-indent (org-current-text-indentation))))
  17995. (forward-line)))
  17996. ;; Then loop over all lines.
  17997. (save-excursion
  17998. (goto-char (point-min))
  17999. (while (not (eobp))
  18000. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  18001. ;; Don't get fooled by invisible text (e.g. link path)
  18002. ;; when moving to column MIN-INDENT.
  18003. (let ((buffer-invisibility-spec nil))
  18004. (org-move-to-column min-indent t))
  18005. (insert comment-start))
  18006. (forward-line)))))))))
  18007. (defun org-comment-dwim (_arg)
  18008. "Call the comment command you mean.
  18009. Call `org-toggle-comment' if on a heading, otherwise call
  18010. `comment-dwim', within a source edit buffer if needed."
  18011. (interactive "*P")
  18012. (cond ((org-at-heading-p)
  18013. (call-interactively #'org-toggle-comment))
  18014. ((org-in-src-block-p)
  18015. (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
  18016. (t (call-interactively #'comment-dwim))))
  18017. ;;; Timestamps API
  18018. ;; This section contains tools to operate on, or create, timestamp
  18019. ;; objects, as returned by, e.g. `org-element-context'.
  18020. (defun org-timestamp-from-string (s)
  18021. "Convert Org timestamp S, as a string, into a timestamp object.
  18022. Return nil if S is not a valid timestamp string."
  18023. (when (org-string-nw-p s)
  18024. (with-temp-buffer
  18025. (save-excursion (insert s))
  18026. (org-element-timestamp-parser))))
  18027. (defun org-timestamp-from-time (time &optional with-time inactive)
  18028. "Convert a time value into a timestamp object.
  18029. TIME is an Emacs internal time representation, as returned, e.g.,
  18030. by `current-time'.
  18031. When optional argument WITH-TIME is non-nil, return a timestamp
  18032. object with a time part, i.e., with hours and minutes.
  18033. Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
  18034. return an active timestamp."
  18035. (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
  18036. (org-element-create 'timestamp
  18037. (list :type (if inactive 'inactive 'active)
  18038. :year-start year
  18039. :month-start month
  18040. :day-start day
  18041. :hour-start (and with-time hour)
  18042. :minute-start (and with-time minute)))))
  18043. (defun org-timestamp-to-time (timestamp &optional end)
  18044. "Convert TIMESTAMP object into an Emacs internal time value.
  18045. Use end of date range or time range when END is non-nil.
  18046. Otherwise, use its start."
  18047. (org-encode-time
  18048. (append '(0)
  18049. (mapcar
  18050. (lambda (prop) (or (org-element-property prop timestamp) 0))
  18051. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  18052. '(:minute-start :hour-start :day-start :month-start
  18053. :year-start)))
  18054. '(nil -1 nil))))
  18055. (defun org-timestamp-has-time-p (timestamp)
  18056. "Non-nil when TIMESTAMP has a time specified."
  18057. (org-element-property :hour-start timestamp))
  18058. (defun org-timestamp-format (timestamp format &optional end utc)
  18059. "Format a TIMESTAMP object into a string.
  18060. FORMAT is a format specifier to be passed to
  18061. `format-time-string'.
  18062. When optional argument END is non-nil, use end of date-range or
  18063. time-range, if possible.
  18064. When optional argument UTC is non-nil, time is be expressed as
  18065. Universal Time."
  18066. (format-time-string format (org-timestamp-to-time timestamp end)
  18067. (and utc t)))
  18068. (defun org-timestamp-split-range (timestamp &optional end)
  18069. "Extract a TIMESTAMP object from a date or time range.
  18070. END, when non-nil, means extract the end of the range.
  18071. Otherwise, extract its start.
  18072. Return a new timestamp object."
  18073. (let ((type (org-element-property :type timestamp)))
  18074. (if (memq type '(active inactive diary)) timestamp
  18075. (let ((split-ts (org-element-copy timestamp)))
  18076. ;; Set new type.
  18077. (org-element-put-property
  18078. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  18079. ;; Copy start properties over end properties if END is
  18080. ;; non-nil. Otherwise, copy end properties over `start' ones.
  18081. (let ((p-alist '((:minute-start . :minute-end)
  18082. (:hour-start . :hour-end)
  18083. (:day-start . :day-end)
  18084. (:month-start . :month-end)
  18085. (:year-start . :year-end))))
  18086. (dolist (p-cell p-alist)
  18087. (org-element-put-property
  18088. split-ts
  18089. (funcall (if end #'car #'cdr) p-cell)
  18090. (org-element-property
  18091. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  18092. ;; Eventually refresh `:raw-value'.
  18093. (org-element-put-property split-ts :raw-value nil)
  18094. (org-element-put-property
  18095. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  18096. (defun org-timestamp-translate (timestamp &optional boundary)
  18097. "Translate TIMESTAMP object to custom format.
  18098. Format string is defined in `org-time-stamp-custom-formats',
  18099. which see.
  18100. When optional argument BOUNDARY is non-nil, it is either the
  18101. symbol `start' or `end'. In this case, only translate the
  18102. starting or ending part of TIMESTAMP if it is a date or time
  18103. range. Otherwise, translate both parts.
  18104. Return timestamp as-is if `org-display-custom-times' is nil or if
  18105. it has a `diary' type."
  18106. (let ((type (org-element-property :type timestamp)))
  18107. (if (or (not org-display-custom-times) (eq type 'diary))
  18108. (org-element-interpret-data timestamp)
  18109. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  18110. org-time-stamp-custom-formats)))
  18111. (if (and (not boundary) (memq type '(active-range inactive-range)))
  18112. (concat (org-timestamp-format timestamp fmt)
  18113. "--"
  18114. (org-timestamp-format timestamp fmt t))
  18115. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  18116. ;;; Other stuff
  18117. (defvar reftex-docstruct-symbol)
  18118. (defvar org--rds)
  18119. (defun org-reftex-citation ()
  18120. "Use `reftex-citation' to insert a citation into the buffer.
  18121. This looks for a line like
  18122. #+BIBLIOGRAPHY: foo plain option:-d
  18123. and derives from it that foo.bib is the bibliography file relevant
  18124. for this document. It then installs the necessary environment for RefTeX
  18125. to work in this buffer and calls `reftex-citation' to insert a citation
  18126. into the buffer.
  18127. Export of such citations to both LaTeX and HTML is handled by the contributed
  18128. package ox-bibtex by Taru Karttunen."
  18129. (interactive)
  18130. (let ((reftex-docstruct-symbol 'org--rds)
  18131. org--rds bib)
  18132. (org-with-wide-buffer
  18133. (let ((case-fold-search t)
  18134. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  18135. (if (not (save-excursion
  18136. (or (re-search-forward re nil t)
  18137. (re-search-backward re nil t))))
  18138. (user-error "No bibliography defined in file")
  18139. (setq bib (concat (match-string 1) ".bib")
  18140. org--rds (list (list 'bib bib))))))
  18141. (call-interactively 'reftex-citation)))
  18142. ;;;; Functions extending outline functionality
  18143. (defun org-beginning-of-line (&optional n)
  18144. "Go to the beginning of the current visible line.
  18145. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18146. symbol `reversed', on the first attempt move to where the
  18147. headline text starts, and only move to beginning of line when the
  18148. cursor is already before the start of the text of the headline.
  18149. If `org-special-ctrl-a/e' is symbol `reversed' then go to the
  18150. start of the text on the second attempt.
  18151. With argument N not nil or 1, move forward N - 1 lines first."
  18152. (interactive "^p")
  18153. (let ((origin (point))
  18154. (special (pcase org-special-ctrl-a/e
  18155. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  18156. deactivate-mark)
  18157. ;; First move to a visible line.
  18158. (if (bound-and-true-p visual-line-mode)
  18159. (beginning-of-visual-line n)
  18160. (move-beginning-of-line n)
  18161. ;; `move-beginning-of-line' may leave point after invisible
  18162. ;; characters if line starts with such of these (e.g., with
  18163. ;; a link at column 0). Really move to the beginning of the
  18164. ;; current visible line.
  18165. (beginning-of-line))
  18166. (cond
  18167. ;; No special behavior. Point is already at the beginning of
  18168. ;; a line, logical or visual.
  18169. ((not special))
  18170. ;; `beginning-of-visual-line' left point before logical beginning
  18171. ;; of line: point is at the beginning of a visual line. Bail
  18172. ;; out.
  18173. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  18174. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  18175. ;; At a headline, special position is before the title, but
  18176. ;; after any TODO keyword or priority cookie.
  18177. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  18178. (line-end-position)))
  18179. (bol (point)))
  18180. (if (eq special 'reversed)
  18181. (when (and (= origin bol) (eq last-command this-command))
  18182. (goto-char refpos))
  18183. (when (or (> origin refpos) (= origin bol))
  18184. (goto-char refpos)))))
  18185. ((and (looking-at org-list-full-item-re)
  18186. (memq (org-element-type (save-match-data (org-element-at-point)))
  18187. '(item plain-list)))
  18188. ;; Set special position at first white space character after
  18189. ;; bullet, and check-box, if any.
  18190. (let ((after-bullet
  18191. (let ((box (match-end 3)))
  18192. (cond ((not box) (match-end 1))
  18193. ((eq (char-after box) ?\s) (1+ box))
  18194. (t box)))))
  18195. (if (eq special 'reversed)
  18196. (when (and (= (point) origin) (eq last-command this-command))
  18197. (goto-char after-bullet))
  18198. (when (or (> origin after-bullet) (= (point) origin))
  18199. (goto-char after-bullet)))))
  18200. ;; No special context. Point is already at beginning of line.
  18201. (t nil))))
  18202. (defun org-end-of-line (&optional n)
  18203. "Go to the end of the line, but before ellipsis, if any.
  18204. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18205. symbol `reversed', ignore tags on the first attempt, and only
  18206. move to after the tags when the cursor is already beyond the end
  18207. of the headline.
  18208. If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
  18209. on the second attempt.
  18210. With argument N not nil or 1, move forward N - 1 lines first."
  18211. (interactive "^p")
  18212. (let ((origin (point))
  18213. (special (pcase org-special-ctrl-a/e
  18214. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  18215. deactivate-mark)
  18216. ;; First move to a visible line.
  18217. (if (bound-and-true-p visual-line-mode)
  18218. (beginning-of-visual-line n)
  18219. (move-beginning-of-line n))
  18220. (cond
  18221. ;; At a headline, with tags.
  18222. ((and special
  18223. (save-excursion
  18224. (beginning-of-line)
  18225. (let ((case-fold-search nil))
  18226. (looking-at org-complex-heading-regexp)))
  18227. (match-end 5))
  18228. (let ((tags (save-excursion
  18229. (goto-char (match-beginning 5))
  18230. (skip-chars-backward " \t")
  18231. (point)))
  18232. (visual-end (and (bound-and-true-p visual-line-mode)
  18233. (save-excursion
  18234. (end-of-visual-line)
  18235. (point)))))
  18236. ;; If `end-of-visual-line' brings us before end of line or
  18237. ;; even tags, i.e., the headline spans over multiple visual
  18238. ;; lines, move there.
  18239. (cond ((and visual-end
  18240. (< visual-end tags)
  18241. (<= origin visual-end))
  18242. (goto-char visual-end))
  18243. ((eq special 'reversed)
  18244. (if (and (= origin (line-end-position))
  18245. (eq this-command last-command))
  18246. (goto-char tags)
  18247. (end-of-line)))
  18248. (t
  18249. (if (or (< origin tags) (= origin (line-end-position)))
  18250. (goto-char tags)
  18251. (end-of-line))))))
  18252. ((bound-and-true-p visual-line-mode)
  18253. (let ((bol (line-beginning-position)))
  18254. (end-of-visual-line)
  18255. ;; If `end-of-visual-line' gets us past the ellipsis at the
  18256. ;; end of a line, backtrack and use `end-of-line' instead.
  18257. (when (/= bol (line-beginning-position))
  18258. (goto-char bol)
  18259. (end-of-line))))
  18260. (t (end-of-line)))))
  18261. (defun org-backward-sentence (&optional _arg)
  18262. "Go to beginning of sentence, or beginning of table field.
  18263. This will call `backward-sentence' or `org-table-beginning-of-field',
  18264. depending on context."
  18265. (interactive)
  18266. (let* ((element (org-element-at-point))
  18267. (contents-begin (org-element-property :contents-begin element))
  18268. (table (org-element-lineage element '(table) t)))
  18269. (if (and table
  18270. (> (point) contents-begin)
  18271. (<= (point) (org-element-property :contents-end table)))
  18272. (call-interactively #'org-table-beginning-of-field)
  18273. (save-restriction
  18274. (when (and contents-begin
  18275. (< (point-min) contents-begin)
  18276. (> (point) contents-begin))
  18277. (narrow-to-region contents-begin
  18278. (org-element-property :contents-end element)))
  18279. (call-interactively #'backward-sentence)))))
  18280. (defun org-forward-sentence (&optional _arg)
  18281. "Go to end of sentence, or end of table field.
  18282. This will call `forward-sentence' or `org-table-end-of-field',
  18283. depending on context."
  18284. (interactive)
  18285. (if (and (org-at-heading-p)
  18286. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  18287. (save-restriction
  18288. (narrow-to-region (line-beginning-position) (line-end-position))
  18289. (call-interactively #'forward-sentence))
  18290. (let* ((element (org-element-at-point))
  18291. (contents-end (org-element-property :contents-end element))
  18292. (table (org-element-lineage element '(table) t)))
  18293. (if (and table
  18294. (>= (point) (org-element-property :contents-begin table))
  18295. (< (point) contents-end))
  18296. (call-interactively #'org-table-end-of-field)
  18297. (save-restriction
  18298. (when (and contents-end
  18299. (> (point-max) contents-end)
  18300. ;; Skip blank lines between elements.
  18301. (< (org-element-property :end element)
  18302. (save-excursion (goto-char contents-end)
  18303. (skip-chars-forward " \r\t\n"))))
  18304. (narrow-to-region (org-element-property :contents-begin element)
  18305. contents-end))
  18306. ;; End of heading is considered as the end of a sentence.
  18307. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  18308. (call-interactively #'forward-sentence)))))))
  18309. (defun org-kill-line (&optional _arg)
  18310. "Kill line, to tags or end of line.
  18311. The behavior of this command depends on the user options
  18312. `org-special-ctrl-k' and `org-ctrl-k-protect-subtree' (which
  18313. see)."
  18314. (interactive)
  18315. (cond
  18316. ((or (not org-special-ctrl-k)
  18317. (bolp)
  18318. (not (org-at-heading-p)))
  18319. (when (and (org-invisible-p (line-end-position))
  18320. org-ctrl-k-protect-subtree
  18321. (or (eq org-ctrl-k-protect-subtree 'error)
  18322. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  18323. (user-error
  18324. (substitute-command-keys
  18325. "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
  18326. (call-interactively
  18327. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  18328. ((org-match-line org-tag-line-re)
  18329. (let ((end (save-excursion
  18330. (goto-char (match-beginning 1))
  18331. (skip-chars-backward " \t")
  18332. (point))))
  18333. (if (<= end (point)) ;on tags part
  18334. (kill-region (point) (line-end-position))
  18335. (kill-region (point) end)))
  18336. ;; Only align tags when we are still on a heading:
  18337. (if (org-at-heading-p) (org-align-tags)))
  18338. (t (kill-region (point) (line-end-position)))))
  18339. (defun org-yank (&optional arg)
  18340. "Yank. If the kill is a subtree, treat it specially.
  18341. This command will look at the current kill and check if is a single
  18342. subtree, or a series of subtrees[1]. If it passes the test, and if the
  18343. cursor is at the beginning of a line or after the stars of a currently
  18344. empty headline, then the yank is handled specially. How exactly depends
  18345. on the value of the following variables.
  18346. `org-yank-folded-subtrees'
  18347. By default, this variable is non-nil, which results in
  18348. subtree(s) being folded after insertion, except if doing so
  18349. would swallow text after the yanked text.
  18350. `org-yank-adjusted-subtrees'
  18351. When non-nil (the default value is nil), the subtree will be
  18352. promoted or demoted in order to fit into the local outline tree
  18353. structure, which means that the level will be adjusted so that it
  18354. becomes the smaller one of the two *visible* surrounding headings.
  18355. Any prefix to this command will cause `yank' to be called directly with
  18356. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  18357. will just
  18358. plainly yank the text as it is.
  18359. \[1] The test checks if the first non-white line is a heading
  18360. and if there are no other headings with fewer stars."
  18361. (interactive "P")
  18362. (org-yank-generic 'yank arg))
  18363. (defun org-yank-generic (command arg)
  18364. "Perform some yank-like command.
  18365. This function implements the behavior described in the `org-yank'
  18366. documentation. However, it has been generalized to work for any
  18367. interactive command with similar behavior."
  18368. ;; pretend to be command COMMAND
  18369. (setq this-command command)
  18370. (if arg
  18371. (call-interactively command)
  18372. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  18373. (and (org-kill-is-subtree-p)
  18374. (or (bolp)
  18375. (and (looking-at "[ \t]*$")
  18376. (string-match
  18377. "\\`\\*+\\'"
  18378. (buffer-substring (line-beginning-position) (point)))))))
  18379. swallowp)
  18380. (cond
  18381. ((and subtreep org-yank-folded-subtrees)
  18382. (let ((beg (point))
  18383. end)
  18384. (if (and subtreep org-yank-adjusted-subtrees)
  18385. (org-paste-subtree nil nil 'for-yank)
  18386. (call-interactively command))
  18387. (setq end (point))
  18388. (goto-char beg)
  18389. (when (and (bolp) subtreep
  18390. (not (setq swallowp
  18391. (org-yank-folding-would-swallow-text beg end))))
  18392. (org-with-limited-levels
  18393. (or (looking-at org-outline-regexp)
  18394. (re-search-forward org-outline-regexp-bol end t))
  18395. (while (and (< (point) end) (looking-at org-outline-regexp))
  18396. (org-fold-subtree t)
  18397. (org-cycle-show-empty-lines 'folded)
  18398. (condition-case nil
  18399. (outline-forward-same-level 1)
  18400. (error (goto-char end))))))
  18401. (when swallowp
  18402. (message
  18403. "Inserted text not folded because that would swallow text"))
  18404. (goto-char end)
  18405. (skip-chars-forward " \t\n\r")
  18406. (beginning-of-line 1)
  18407. (push-mark beg 'nomsg)))
  18408. ((and subtreep org-yank-adjusted-subtrees)
  18409. (let ((beg (line-beginning-position)))
  18410. (org-paste-subtree nil nil 'for-yank)
  18411. (push-mark beg 'nomsg)))
  18412. (t
  18413. (call-interactively command))))))
  18414. (defun org-yank-folding-would-swallow-text (beg end)
  18415. "Would `hide-subtree' at BEG swallow any text after END?"
  18416. (let (level)
  18417. (org-with-limited-levels
  18418. (save-excursion
  18419. (goto-char beg)
  18420. (when (or (looking-at org-outline-regexp)
  18421. (re-search-forward org-outline-regexp-bol end t))
  18422. (setq level (org-outline-level)))
  18423. (goto-char end)
  18424. (skip-chars-forward " \t\r\n\v\f")
  18425. (not (or (eobp)
  18426. (and (bolp) (looking-at-p org-outline-regexp)
  18427. (<= (org-outline-level) level))))))))
  18428. (defun org-back-to-heading (&optional invisible-ok)
  18429. "Go back to beginning of heading."
  18430. (beginning-of-line)
  18431. (or (org-at-heading-p (not invisible-ok))
  18432. (if (org-element--cache-active-p)
  18433. (let ((heading (org-element-lineage (org-element-at-point)
  18434. '(headline inlinetask)
  18435. 'include-self)))
  18436. (when heading
  18437. (goto-char (org-element-property :begin heading)))
  18438. (while (and (not invisible-ok)
  18439. heading
  18440. (org-fold-folded-p))
  18441. (goto-char (org-fold-core-previous-visibility-change))
  18442. (setq heading (org-element-lineage (org-element-at-point)
  18443. '(headline inlinetask)
  18444. 'include-self))
  18445. (when heading
  18446. (goto-char (org-element-property :begin heading))))
  18447. (unless heading
  18448. (user-error "Before first headline at position %d in buffer %s"
  18449. (point) (current-buffer)))
  18450. (point))
  18451. (let (found)
  18452. (save-excursion
  18453. ;; At inlinetask end. Move to bol, so that the following
  18454. ;; search goes to the beginning of the inlinetask.
  18455. (when (and (featurep 'org-inlinetask)
  18456. (fboundp 'org-inlinetask-end-p)
  18457. (org-inlinetask-end-p))
  18458. (goto-char (line-beginning-position)))
  18459. (while (not found)
  18460. (or (re-search-backward (concat "^\\(?:" outline-regexp "\\)")
  18461. nil t)
  18462. (user-error "Before first headline at position %d in buffer %s"
  18463. (point) (current-buffer)))
  18464. ;; Skip inlinetask end.
  18465. (if (and (featurep 'org-inlinetask)
  18466. (fboundp 'org-inlinetask-end-p)
  18467. (org-inlinetask-end-p))
  18468. (org-inlinetask-goto-beginning)
  18469. (setq found (and (or invisible-ok (not (org-fold-folded-p)))
  18470. (point))))))
  18471. (goto-char found)
  18472. found))))
  18473. (defun org-back-to-heading-or-point-min (&optional invisible-ok)
  18474. "Go back to heading or first point in buffer.
  18475. If point is before first heading go to first point in buffer
  18476. instead of back to heading."
  18477. (if (org-before-first-heading-p)
  18478. (goto-char (point-min))
  18479. (org-back-to-heading invisible-ok)))
  18480. (defun org-before-first-heading-p ()
  18481. "Before first heading?
  18482. Respect narrowing."
  18483. (let ((cached (org-element-at-point nil 'cached)))
  18484. (if cached
  18485. (let ((cached-headline (org-element-lineage cached '(headline) t)))
  18486. (or (not cached-headline)
  18487. (< (org-element-property :begin cached-headline) (point-min))))
  18488. (org-with-limited-levels
  18489. (save-excursion
  18490. (end-of-line)
  18491. (null (re-search-backward org-outline-regexp-bol nil t)))))))
  18492. (defun org-at-heading-p (&optional invisible-not-ok)
  18493. "Return t if point is on a (possibly invisible) heading line.
  18494. If INVISIBLE-NOT-OK is non-nil, an invisible heading line is not ok."
  18495. (save-excursion
  18496. (beginning-of-line)
  18497. (and (bolp) (or (not invisible-not-ok) (not (org-fold-folded-p)))
  18498. (looking-at outline-regexp))))
  18499. (defun org-in-commented-heading-p (&optional no-inheritance element)
  18500. "Non-nil if point is under a commented heading.
  18501. This function also checks ancestors of the current headline,
  18502. unless optional argument NO-INHERITANCE is non-nil.
  18503. Optional argument ELEMENT contains element at point."
  18504. (save-match-data
  18505. (let ((el (or element
  18506. (org-element-at-point nil 'cached)
  18507. (org-with-wide-buffer
  18508. (org-back-to-heading-or-point-min t)
  18509. (org-element-at-point)))))
  18510. (catch :found
  18511. (setq el (org-element-lineage el '(headline inlinetask) 'include-self))
  18512. (if no-inheritance
  18513. (org-element-property :commentedp el)
  18514. (while el
  18515. (when (org-element-property :commentedp el)
  18516. (throw :found t))
  18517. (setq el (org-element-property :parent el))))))))
  18518. (defun org-in-archived-heading-p (&optional no-inheritance element)
  18519. "Non-nil if point is under an archived heading.
  18520. This function also checks ancestors of the current headline,
  18521. unless optional argument NO-INHERITANCE is non-nil.
  18522. Optional argument ELEMENT contains element at point."
  18523. (cond
  18524. ((and (not element) (org-before-first-heading-p)) nil)
  18525. ((if element
  18526. (org-element-property :archivedp element)
  18527. (let ((tags (org-get-tags element 'local)))
  18528. (and tags
  18529. (cl-some (apply-partially #'string= org-archive-tag) tags)))))
  18530. (no-inheritance nil)
  18531. (t
  18532. (if (or element (org-element--cache-active-p))
  18533. (catch :archived
  18534. (unless element (setq element (org-element-at-point)))
  18535. (while element
  18536. (when (org-element-property :archivedp element)
  18537. (throw :archived t))
  18538. (setq element (org-element-property :parent element))))
  18539. (save-excursion (and (org-up-heading-safe) (org-in-archived-heading-p)))))))
  18540. (defun org-at-comment-p nil
  18541. "Return t if cursor is in a commented line."
  18542. (save-excursion
  18543. (save-match-data
  18544. (beginning-of-line)
  18545. (looking-at org-comment-regexp))))
  18546. (defun org-at-keyword-p nil
  18547. "Return t if cursor is at a keyword-line."
  18548. (save-excursion
  18549. (move-beginning-of-line 1)
  18550. (looking-at org-keyword-regexp)))
  18551. (defun org-at-drawer-p nil
  18552. "Return t if cursor is at a drawer keyword."
  18553. (save-excursion
  18554. (move-beginning-of-line 1)
  18555. (looking-at org-drawer-regexp)))
  18556. (defun org-at-block-p nil
  18557. "Return t if cursor is at a block keyword."
  18558. (save-excursion
  18559. (move-beginning-of-line 1)
  18560. (looking-at org-block-regexp)))
  18561. (defun org-point-at-end-of-empty-headline ()
  18562. "If point is at the end of an empty headline, return t, else nil.
  18563. If the heading only contains a TODO keyword, it is still considered
  18564. empty."
  18565. (let ((case-fold-search nil))
  18566. (and (looking-at "[ \t]*$")
  18567. org-todo-line-regexp
  18568. (save-excursion
  18569. (beginning-of-line)
  18570. (looking-at org-todo-line-regexp)
  18571. (string= (match-string 3) "")))))
  18572. (defun org-at-heading-or-item-p ()
  18573. (or (org-at-heading-p) (org-at-item-p)))
  18574. (defun org-up-heading-all (arg)
  18575. "Move to the heading line of which the present line is a subheading.
  18576. This function considers both visible and invisible heading lines.
  18577. With argument, move up ARG levels."
  18578. (outline-up-heading arg t))
  18579. (defvar-local org--up-heading-cache nil
  18580. "Buffer-local `org-up-heading-safe' cache.")
  18581. (defvar-local org--up-heading-cache-tick nil
  18582. "Buffer `buffer-chars-modified-tick' in `org--up-heading-cache'.")
  18583. (defun org-up-heading-safe ()
  18584. "Move to the heading line of which the present line is a subheading.
  18585. This version will not throw an error. It will return the level of the
  18586. headline found, or nil if no higher level is found.
  18587. Also, this function will be a lot faster than `outline-up-heading',
  18588. because it relies on stars being the outline starters. This can really
  18589. make a significant difference in outlines with very many siblings."
  18590. (let ((element (and (org-element--cache-active-p)
  18591. (org-element-at-point nil t))))
  18592. (if element
  18593. (let* ((current-heading (org-element-lineage element '(headline inlinetask) 'with-self))
  18594. (parent (org-element-lineage current-heading '(headline))))
  18595. (if (and parent
  18596. (<= (point-min) (org-element-property :begin parent)))
  18597. (progn
  18598. (goto-char (org-element-property :begin parent))
  18599. (org-element-property :level parent))
  18600. (when (and current-heading
  18601. (<= (point-min) (org-element-property :begin current-heading)))
  18602. (goto-char (org-element-property :begin current-heading))
  18603. nil)))
  18604. (when (ignore-errors (org-back-to-heading t))
  18605. (let (level-cache)
  18606. (unless org--up-heading-cache
  18607. (setq org--up-heading-cache (make-hash-table)))
  18608. (if (and (eq (buffer-chars-modified-tick) org--up-heading-cache-tick)
  18609. (setq level-cache (gethash (point) org--up-heading-cache)))
  18610. (when (<= (point-min) (car level-cache) (point-max))
  18611. ;; Parent is inside accessible part of the buffer.
  18612. (progn (goto-char (car level-cache))
  18613. (cdr level-cache)))
  18614. ;; Buffer modified. Invalidate cache.
  18615. (unless (eq (buffer-chars-modified-tick) org--up-heading-cache-tick)
  18616. (setq-local org--up-heading-cache-tick
  18617. (buffer-chars-modified-tick))
  18618. (clrhash org--up-heading-cache))
  18619. (let* ((level-up (1- (funcall outline-level)))
  18620. (pos (point))
  18621. (result (and (> level-up 0)
  18622. (re-search-backward
  18623. (format "^\\*\\{1,%d\\} " level-up) nil t)
  18624. (funcall outline-level))))
  18625. (when result (puthash pos (cons (point) result) org--up-heading-cache))
  18626. result)))))))
  18627. (defun org-up-heading-or-point-min ()
  18628. "Move to the heading line of which the present is a subheading, or point-min.
  18629. This version is needed to make point-min behave like a virtual
  18630. heading of level 0 for property-inheritance. It will return the
  18631. level of the headline found (down to 0) or nil if already at a
  18632. point before the first headline or at point-min."
  18633. (when (ignore-errors (org-back-to-heading t))
  18634. (if (< 1 (funcall outline-level))
  18635. (or (org-up-heading-safe)
  18636. ;; The first heading may not be level 1 heading.
  18637. (goto-char (point-min)))
  18638. (unless (= (point) (point-min)) (goto-char (point-min))))))
  18639. (defun org-first-sibling-p ()
  18640. "Is this heading the first child of its parents?"
  18641. (interactive)
  18642. (let ((re org-outline-regexp-bol)
  18643. level l)
  18644. (unless (org-at-heading-p t)
  18645. (user-error "Not at a heading"))
  18646. (setq level (funcall outline-level))
  18647. (save-excursion
  18648. (if (not (re-search-backward re nil t))
  18649. t
  18650. (setq l (funcall outline-level))
  18651. (< l level)))))
  18652. (defun org-goto-sibling (&optional previous)
  18653. "Goto the next sibling, even if it is invisible.
  18654. When PREVIOUS is set, go to the previous sibling instead. Returns t
  18655. when a sibling was found. When none is found, return nil and don't
  18656. move point."
  18657. (let ((fun (if previous 're-search-backward 're-search-forward))
  18658. (pos (point))
  18659. (re org-outline-regexp-bol)
  18660. level l)
  18661. (when (ignore-errors (org-back-to-heading t))
  18662. (setq level (funcall outline-level))
  18663. (catch 'exit
  18664. (or previous (forward-char 1))
  18665. (while (funcall fun re nil t)
  18666. (setq l (funcall outline-level))
  18667. (when (< l level) (goto-char pos) (throw 'exit nil))
  18668. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  18669. (goto-char pos)
  18670. nil))))
  18671. (defun org-goto-first-child (&optional element)
  18672. "Goto the first child, even if it is invisible.
  18673. Return t when a child was found. Otherwise don't move point and
  18674. return nil."
  18675. (if (org-element--cache-active-p)
  18676. (let ((heading (org-element-lineage
  18677. (or element (org-element-at-point))
  18678. '(headline inlinetask org-data)
  18679. t)))
  18680. (when heading
  18681. (unless (or (eq 'inlinetask (org-element-type heading))
  18682. (not (org-element-property :contents-begin heading)))
  18683. (let ((pos (point)))
  18684. (goto-char (org-element-property :contents-begin heading))
  18685. (if (re-search-forward
  18686. org-outline-regexp-bol
  18687. (org-element-property :end heading)
  18688. t)
  18689. (progn (goto-char (match-beginning 0)) t)
  18690. (goto-char pos) nil)))))
  18691. (let (level (pos (point)) (re org-outline-regexp-bol))
  18692. (when (org-back-to-heading-or-point-min t)
  18693. (setq level (org-outline-level))
  18694. (forward-char 1)
  18695. (if (and (re-search-forward re nil t) (> (org-outline-level) level))
  18696. (progn (goto-char (match-beginning 0)) t)
  18697. (goto-char pos) nil)))))
  18698. (defun org-get-next-sibling ()
  18699. "Move to next heading of the same level, and return point.
  18700. If there is no such heading, return nil.
  18701. This is like outline-next-sibling, but invisible headings are ok."
  18702. (let ((level (funcall outline-level)))
  18703. (outline-next-heading)
  18704. (while (and (not (eobp)) (> (funcall outline-level) level))
  18705. (outline-next-heading))
  18706. (unless (or (eobp) (< (funcall outline-level) level))
  18707. (point))))
  18708. (defun org-get-previous-sibling ()
  18709. "Move to previous heading of the same level, and return point.
  18710. If there is no such heading, return nil."
  18711. (let ((opoint (point))
  18712. (level (funcall outline-level)))
  18713. (outline-previous-heading)
  18714. (when (and (/= (point) opoint) (outline-on-heading-p t))
  18715. (while (and (> (funcall outline-level) level)
  18716. (not (bobp)))
  18717. (outline-previous-heading))
  18718. (unless (< (funcall outline-level) level)
  18719. (point)))))
  18720. (defun org-end-of-subtree (&optional invisible-ok to-heading element)
  18721. "Goto to the end of a subtree at point or for ELEMENT heading."
  18722. ;; This contains an exact copy of the original function, but it uses
  18723. ;; `org-back-to-heading-or-point-min', to make it work also in invisible
  18724. ;; trees and before first headline. And is uses an invisible-ok argument.
  18725. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  18726. ;; Furthermore, when used inside Org, finding the end of a large subtree
  18727. ;; with many children and grandchildren etc, this can be much faster
  18728. ;; than the outline version.
  18729. (if element
  18730. (setq element (org-element-lineage element '(headline inlinetask) 'include-self))
  18731. (org-back-to-heading-or-point-min invisible-ok))
  18732. (unless (and (org-element--cache-active-p)
  18733. (let ((cached (or element (org-element-at-point nil t))))
  18734. (and cached
  18735. (eq 'headline (org-element-type cached))
  18736. (goto-char (org-element-property
  18737. :end cached)))))
  18738. (let ((first t)
  18739. (level (funcall outline-level)))
  18740. (cond ((= level 0)
  18741. (goto-char (point-max)))
  18742. ((and (derived-mode-p 'org-mode) (< level 1000))
  18743. ;; A true heading (not a plain list item), in Org
  18744. ;; This means we can easily find the end by looking
  18745. ;; only for the right number of stars. Using a regexp to do
  18746. ;; this is so much faster than using a Lisp loop.
  18747. (let ((re (concat "^\\*\\{1," (number-to-string level) "\\} ")))
  18748. (forward-char 1)
  18749. (and (re-search-forward re nil 'move) (beginning-of-line 1))))
  18750. (t
  18751. ;; something else, do it the slow way
  18752. (while (and (not (eobp))
  18753. (or first (> (funcall outline-level) level)))
  18754. (setq first nil)
  18755. (outline-next-heading))))))
  18756. (unless to-heading
  18757. (when (memq (preceding-char) '(?\n ?\^M))
  18758. ;; Go to end of line before heading
  18759. (forward-char -1)
  18760. (when (memq (preceding-char) '(?\n ?\^M))
  18761. ;; leave blank line before heading
  18762. (forward-char -1))))
  18763. (point))
  18764. (defun org-end-of-meta-data (&optional full)
  18765. "Skip planning line and properties drawer in current entry.
  18766. When optional argument FULL is t, also skip planning information,
  18767. clocking lines and any kind of drawer.
  18768. When FULL is non-nil but not t, skip planning information,
  18769. properties, clocking lines and logbook drawers."
  18770. (org-back-to-heading t)
  18771. (forward-line)
  18772. ;; Skip planning information.
  18773. (when (looking-at-p org-planning-line-re) (forward-line))
  18774. ;; Skip property drawer.
  18775. (when (looking-at org-property-drawer-re)
  18776. (goto-char (match-end 0))
  18777. (forward-line))
  18778. ;; When FULL is not nil, skip more.
  18779. (when (and full (not (org-at-heading-p)))
  18780. (catch 'exit
  18781. (let ((end (save-excursion (outline-next-heading) (point)))
  18782. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  18783. (while (not (eobp))
  18784. (cond ;; Skip clock lines.
  18785. ((looking-at-p re) (forward-line))
  18786. ;; Skip logbook drawer.
  18787. ((looking-at-p org-logbook-drawer-re)
  18788. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  18789. (forward-line)
  18790. (throw 'exit t)))
  18791. ;; When FULL is t, skip regular drawer too.
  18792. ((and (eq full t) (looking-at-p org-drawer-regexp))
  18793. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  18794. (forward-line)
  18795. (throw 'exit t)))
  18796. (t (throw 'exit t))))))))
  18797. (defun org--line-fully-invisible-p ()
  18798. "Return non-nil if the current line is fully invisible."
  18799. (let ((line-beg (line-beginning-position))
  18800. (line-pos (1- (line-end-position)))
  18801. (is-invisible t))
  18802. (while (and (< line-beg line-pos) is-invisible)
  18803. (setq is-invisible (org-invisible-p line-pos))
  18804. (setq line-pos (1- line-pos)))
  18805. is-invisible))
  18806. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  18807. "Move forward to the ARG'th subheading at same level as this one.
  18808. Stop at the first and last subheadings of a superior heading.
  18809. Normally this only looks at visible headings, but when INVISIBLE-OK is
  18810. non-nil it will also look at invisible ones."
  18811. (interactive "p")
  18812. (let ((backward? (and arg (< arg 0))))
  18813. (if (org-before-first-heading-p)
  18814. (if backward? (goto-char (point-min)) (outline-next-heading))
  18815. (org-back-to-heading invisible-ok)
  18816. (unless backward? (end-of-line)) ;do not match current headline
  18817. (let ((level (- (match-end 0) (match-beginning 0) 1))
  18818. (f (if backward? #'re-search-backward #'re-search-forward))
  18819. (count (if arg (abs arg) 1))
  18820. (result (point)))
  18821. (while (and (> count 0)
  18822. (funcall f org-outline-regexp-bol nil 'move))
  18823. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  18824. (cond ((< l level) (setq count 0))
  18825. ((and (= l level)
  18826. (or invisible-ok
  18827. ;; FIXME: See commit a700fadd72 and the
  18828. ;; related discussion on why using
  18829. ;; `org--line-fully-invisible-p' is needed
  18830. ;; here, which is to serve the needs of an
  18831. ;; external package. If the change is
  18832. ;; wrong regarding Org itself, it should
  18833. ;; be removed.
  18834. (not (org--line-fully-invisible-p))))
  18835. (cl-decf count)
  18836. (when (= l level) (setq result (point)))))))
  18837. (goto-char result))
  18838. (beginning-of-line))))
  18839. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  18840. "Move backward to the ARG'th subheading at same level as this one.
  18841. Stop at the first and last subheadings of a superior heading."
  18842. (interactive "p")
  18843. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  18844. (defun org-next-visible-heading (arg)
  18845. "Move to the next visible heading line.
  18846. With ARG, repeats or can move backward if negative."
  18847. (interactive "p")
  18848. (let ((regexp (concat "^" (org-get-limited-outline-regexp))))
  18849. (if (< arg 0)
  18850. (beginning-of-line)
  18851. (end-of-line))
  18852. (while (and (< arg 0) (re-search-backward regexp nil :move))
  18853. (unless (bobp)
  18854. (when (org-fold-folded-p)
  18855. (goto-char (org-fold-previous-visibility-change))
  18856. (unless (looking-at-p regexp)
  18857. (re-search-backward regexp nil :mode))))
  18858. (cl-incf arg))
  18859. (while (and (> arg 0) (re-search-forward regexp nil :move))
  18860. (when (org-fold-folded-p)
  18861. (goto-char (org-fold-next-visibility-change))
  18862. (skip-chars-forward " \t\n")
  18863. (end-of-line))
  18864. (cl-decf arg))
  18865. (if (> arg 0) (goto-char (point-max)) (beginning-of-line))))
  18866. (defun org-previous-visible-heading (arg)
  18867. "Move to the previous visible heading.
  18868. With ARG, repeats or can move forward if negative."
  18869. (interactive "p")
  18870. (org-next-visible-heading (- arg)))
  18871. (defun org-forward-paragraph (&optional arg)
  18872. "Move forward by a paragraph, or equivalent, unit.
  18873. With argument ARG, do it ARG times;
  18874. a negative argument ARG = -N means move backward N paragraphs.
  18875. The function moves point between two structural
  18876. elements (paragraphs, tables, lists, etc.).
  18877. It also provides the following special moves for convenience:
  18878. - on a table or a property drawer, move to its beginning;
  18879. - on comment, example, export, source and verse blocks, stop
  18880. at blank lines;
  18881. - skip consecutive clocks, diary S-exps, and keywords."
  18882. (interactive "^p")
  18883. (unless arg (setq arg 1))
  18884. (if (< arg 0) (org-backward-paragraph (- arg))
  18885. (while (and (> arg 0) (not (eobp)))
  18886. (org--forward-paragraph-once)
  18887. (cl-decf arg))
  18888. ;; Return moves left.
  18889. arg))
  18890. (defun org-backward-paragraph (&optional arg)
  18891. "Move backward by a paragraph, or equivalent, unit.
  18892. With argument ARG, do it ARG times;
  18893. a negative argument ARG = -N means move forward N paragraphs.
  18894. The function moves point between two structural
  18895. elements (paragraphs, tables, lists, etc.).
  18896. It also provides the following special moves for convenience:
  18897. - on a table or a property drawer, move to its beginning;
  18898. - on comment, example, export, source and verse blocks, stop
  18899. at blank lines;
  18900. - skip consecutive clocks, diary S-exps, and keywords."
  18901. (interactive "^p")
  18902. (unless arg (setq arg 1))
  18903. (if (< arg 0) (org-forward-paragraph (- arg))
  18904. (while (and (> arg 0) (not (bobp)))
  18905. (org--backward-paragraph-once)
  18906. (cl-decf arg))
  18907. ;; Return moves left.
  18908. arg))
  18909. (defvar org--single-lines-list-is-paragraph t
  18910. "Treat plain lists with single line items as a whole paragraph")
  18911. (defun org--paragraph-at-point ()
  18912. "Return paragraph, or equivalent, element at point.
  18913. Paragraph element at point is the element at point, with the
  18914. following special cases:
  18915. - treat table rows (resp. node properties) as the table
  18916. \(resp. property drawer) containing them.
  18917. - treat plain lists with an item every line as a whole.
  18918. - treat consecutive keywords, clocks, and diary-sexps as a single
  18919. block.
  18920. Function may return a real element, or a pseudo-element with type
  18921. `pseudo-paragraph'."
  18922. (let* ((e (org-element-at-point))
  18923. (type (org-element-type e))
  18924. ;; If we need to fake a new pseudo-element, triplet is
  18925. ;;
  18926. ;; (BEG END PARENT)
  18927. ;;
  18928. ;; where BEG and END are element boundaries, and PARENT the
  18929. ;; element containing it, or nil.
  18930. (triplet
  18931. (cond
  18932. ((memq type '(table property-drawer))
  18933. (list (org-element-property :begin e)
  18934. (org-element-property :end e)
  18935. (org-element-property :parent e)))
  18936. ((memq type '(node-property table-row))
  18937. (let ((e (org-element-property :parent e)))
  18938. (list (org-element-property :begin e)
  18939. (org-element-property :end e)
  18940. (org-element-property :parent e))))
  18941. ((memq type '(clock diary-sexp keyword))
  18942. (let* ((regexp (pcase type
  18943. (`clock org-clock-line-re)
  18944. (`diary-sexp "%%(")
  18945. (_ org-keyword-regexp)))
  18946. (end (if (< 0 (org-element-property :post-blank e))
  18947. (org-element-property :end e)
  18948. (org-with-wide-buffer
  18949. (forward-line)
  18950. (while (looking-at regexp) (forward-line))
  18951. (skip-chars-forward " \t\n")
  18952. (line-beginning-position))))
  18953. (begin (org-with-point-at (org-element-property :begin e)
  18954. (while (and (not (bobp)) (looking-at regexp))
  18955. (forward-line -1))
  18956. ;; We may have gotten one line too far.
  18957. (if (looking-at regexp)
  18958. (point)
  18959. (line-beginning-position 2)))))
  18960. (list begin end (org-element-property :parent e))))
  18961. ;; Find the full plain list containing point, the check it
  18962. ;; contains exactly one line per item.
  18963. ((let ((l (org-element-lineage e '(plain-list) t)))
  18964. (while (memq (org-element-type (org-element-property :parent l))
  18965. '(item plain-list))
  18966. (setq l (org-element-property :parent l)))
  18967. (and l org--single-lines-list-is-paragraph
  18968. (org-with-point-at (org-element-property :post-affiliated l)
  18969. (forward-line (length (org-element-property :structure l)))
  18970. (= (point) (org-element-property :contents-end l)))
  18971. ;; Return value.
  18972. (list (org-element-property :begin l)
  18973. (org-element-property :end l)
  18974. (org-element-property :parent l)))))
  18975. (t nil)))) ;no triplet: return element
  18976. (pcase triplet
  18977. (`(,b ,e ,p)
  18978. (org-element-create
  18979. 'pseudo-paragraph
  18980. (list :begin b :end e :parent p :post-blank 0 :post-affiliated b)))
  18981. (_ e))))
  18982. (defun org--forward-paragraph-once ()
  18983. "Move forward to end of paragraph or equivalent, once.
  18984. See `org-forward-paragraph'."
  18985. (interactive)
  18986. (save-restriction
  18987. (widen)
  18988. (skip-chars-forward " \t\n")
  18989. (cond
  18990. ((eobp) nil)
  18991. ;; When inside a folded part, move out of it.
  18992. ((when (org-invisible-p nil t)
  18993. (goto-char (cdr (org-fold-get-region-at-point)))
  18994. (forward-line)
  18995. t))
  18996. (t
  18997. (let* ((element (org--paragraph-at-point))
  18998. (type (org-element-type element))
  18999. (contents-begin (org-element-property :contents-begin element))
  19000. (end (org-element-property :end element))
  19001. (post-affiliated (org-element-property :post-affiliated element)))
  19002. (cond
  19003. ((eq type 'plain-list)
  19004. (forward-char)
  19005. (org--forward-paragraph-once))
  19006. ;; If the element is folded, skip it altogether.
  19007. ((when (org-with-point-at post-affiliated (org-invisible-p (line-end-position) t))
  19008. (goto-char (cdr (org-fold-get-region-at-point
  19009. nil
  19010. (org-with-point-at post-affiliated
  19011. (line-end-position)))))
  19012. (forward-line)
  19013. t))
  19014. ;; At a greater element, move inside.
  19015. ((and contents-begin
  19016. (> contents-begin (point))
  19017. (not (eq type 'paragraph)))
  19018. (goto-char contents-begin)
  19019. ;; Items and footnote definitions contents may not start at
  19020. ;; the beginning of the line. In this case, skip until the
  19021. ;; next paragraph.
  19022. (cond
  19023. ((not (bolp)) (org--forward-paragraph-once))
  19024. ((org-previous-line-empty-p) (forward-line -1))
  19025. (t nil)))
  19026. ;; Move between empty lines in some blocks.
  19027. ((memq type '(comment-block example-block export-block src-block
  19028. verse-block))
  19029. (let ((contents-start
  19030. (org-with-point-at post-affiliated
  19031. (line-beginning-position 2))))
  19032. (if (< (point) contents-start)
  19033. (goto-char contents-start)
  19034. (let ((contents-end
  19035. (org-with-point-at end
  19036. (skip-chars-backward " \t\n")
  19037. (line-beginning-position))))
  19038. (cond
  19039. ((>= (point) contents-end)
  19040. (goto-char end)
  19041. (skip-chars-backward " \t\n")
  19042. (forward-line))
  19043. ((re-search-forward "^[ \t]*\n" contents-end :move)
  19044. (forward-line -1))
  19045. (t nil))))))
  19046. (t
  19047. ;; Move to element's end.
  19048. (goto-char end)
  19049. (skip-chars-backward " \t\n")
  19050. (forward-line))))))))
  19051. (defun org--backward-paragraph-once ()
  19052. "Move backward to start of paragraph or equivalent, once.
  19053. See `org-backward-paragraph'."
  19054. (interactive)
  19055. (save-restriction
  19056. (widen)
  19057. (cond
  19058. ((bobp) nil)
  19059. ;; Blank lines at the beginning of the buffer.
  19060. ((and (org-match-line "^[ \t]*$")
  19061. (save-excursion (skip-chars-backward " \t\n") (bobp)))
  19062. (goto-char (point-min)))
  19063. ;; When inside a folded part, move out of it.
  19064. ((when (org-invisible-p (1- (point)) t)
  19065. (goto-char (1- (car (org-fold-get-region-at-point nil (1- (point))))))
  19066. (org--backward-paragraph-once)
  19067. t))
  19068. (t
  19069. (let* ((element (org--paragraph-at-point))
  19070. (type (org-element-type element))
  19071. (begin (org-element-property :begin element))
  19072. (post-affiliated (org-element-property :post-affiliated element))
  19073. (contents-end (org-element-property :contents-end element))
  19074. (end (org-element-property :end element))
  19075. (parent (org-element-property :parent element))
  19076. (reach
  19077. ;; Move to the visible empty line above position P, or
  19078. ;; to position P. Return t.
  19079. (lambda (p)
  19080. (goto-char p)
  19081. (when (and (org-previous-line-empty-p)
  19082. (let ((end (line-end-position 0)))
  19083. (or (= end (point-min))
  19084. (not (org-invisible-p (1- end))))))
  19085. (forward-line -1))
  19086. t)))
  19087. (cond
  19088. ;; Already at the beginning of an element.
  19089. ((= begin (point))
  19090. (cond
  19091. ;; There is a blank line above. Move there.
  19092. ((and (org-previous-line-empty-p)
  19093. (not (org-invisible-p (1- (line-end-position 0)))))
  19094. (forward-line -1))
  19095. ;; At the beginning of the first element within a greater
  19096. ;; element. Move to the beginning of the greater element.
  19097. ((and parent
  19098. (not (eq 'section (org-element-type parent)))
  19099. (= begin (org-element-property :contents-begin parent)))
  19100. (funcall reach (org-element-property :begin parent)))
  19101. ;; Since we have to move anyway, find the beginning
  19102. ;; position of the element above.
  19103. (t
  19104. (forward-char -1)
  19105. (org--backward-paragraph-once))))
  19106. ;; Skip paragraphs at the very beginning of footnote
  19107. ;; definitions or items.
  19108. ((and (eq type 'paragraph)
  19109. (org-with-point-at begin (not (bolp))))
  19110. (funcall reach (progn (goto-char begin) (line-beginning-position))))
  19111. ;; If the element is folded, skip it altogether.
  19112. ((org-with-point-at post-affiliated (org-invisible-p (line-end-position) t))
  19113. (funcall reach begin))
  19114. ;; At the end of a greater element, move inside.
  19115. ((and contents-end
  19116. (<= contents-end (point))
  19117. (not (eq type 'paragraph)))
  19118. (cond
  19119. ((memq type '(footnote-definition plain-list))
  19120. (skip-chars-backward " \t\n")
  19121. (org--backward-paragraph-once))
  19122. ((= contents-end (point))
  19123. (forward-char -1)
  19124. (org--backward-paragraph-once))
  19125. (t
  19126. (goto-char contents-end))))
  19127. ;; Move between empty lines in some blocks.
  19128. ((and (memq type '(comment-block example-block export-block src-block
  19129. verse-block))
  19130. (let ((contents-start
  19131. (org-with-point-at post-affiliated
  19132. (line-beginning-position 2))))
  19133. (when (> (point) contents-start)
  19134. (let ((contents-end
  19135. (org-with-point-at end
  19136. (skip-chars-backward " \t\n")
  19137. (line-beginning-position))))
  19138. (if (> (point) contents-end)
  19139. (progn (goto-char contents-end) t)
  19140. (skip-chars-backward " \t\n" begin)
  19141. (re-search-backward "^[ \t]*\n" contents-start :move)
  19142. t))))))
  19143. ;; Move to element's start.
  19144. (t
  19145. (funcall reach begin))))))))
  19146. (defun org-forward-element ()
  19147. "Move forward by one element.
  19148. Move to the next element at the same level, when possible."
  19149. (interactive)
  19150. (cond ((eobp) (user-error "Cannot move further down"))
  19151. ((org-with-limited-levels (org-at-heading-p))
  19152. (let ((origin (point)))
  19153. (goto-char (org-end-of-subtree nil t))
  19154. (unless (org-with-limited-levels (org-at-heading-p))
  19155. (goto-char origin)
  19156. (user-error "Cannot move further down"))))
  19157. (t
  19158. (let* ((elem (org-element-at-point))
  19159. (end (org-element-property :end elem))
  19160. (parent (org-element-property :parent elem)))
  19161. (cond ((and parent (= (org-element-property :contents-end parent) end))
  19162. (goto-char (org-element-property :end parent)))
  19163. ((integer-or-marker-p end) (goto-char end))
  19164. (t (message "No element at point")))))))
  19165. (defun org-backward-element ()
  19166. "Move backward by one element.
  19167. Move to the previous element at the same level, when possible."
  19168. (interactive)
  19169. (cond ((bobp) (user-error "Cannot move further up"))
  19170. ((org-with-limited-levels (org-at-heading-p))
  19171. ;; At a headline, move to the previous one, if any, or stay
  19172. ;; here.
  19173. (let ((origin (point)))
  19174. (org-with-limited-levels (org-backward-heading-same-level 1))
  19175. ;; When current headline has no sibling above, move to its
  19176. ;; parent.
  19177. (when (= (point) origin)
  19178. (or (org-with-limited-levels (org-up-heading-safe))
  19179. (progn (goto-char origin)
  19180. (user-error "Cannot move further up"))))))
  19181. (t
  19182. (let* ((elem (org-element-at-point))
  19183. (beg (org-element-property :begin elem)))
  19184. (cond
  19185. ;; Move to beginning of current element if point isn't
  19186. ;; there already.
  19187. ((null beg) (message "No element at point"))
  19188. ((/= (point) beg) (goto-char beg))
  19189. (t (goto-char beg)
  19190. (skip-chars-backward " \r\t\n")
  19191. (unless (bobp)
  19192. (let ((prev (org-element-at-point)))
  19193. (goto-char (org-element-property :begin prev))
  19194. (while (and (setq prev (org-element-property :parent prev))
  19195. (<= (org-element-property :end prev) beg))
  19196. (goto-char (org-element-property :begin prev)))))))))))
  19197. (defun org-up-element ()
  19198. "Move to upper element."
  19199. (interactive)
  19200. (if (org-with-limited-levels (org-at-heading-p))
  19201. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  19202. (let* ((elem (org-element-at-point))
  19203. (parent (org-element-property :parent elem)))
  19204. ;; Skip sections
  19205. (when (eq 'section (org-element-type parent))
  19206. (setq parent (org-element-property :parent parent)))
  19207. (if (and parent
  19208. (not (eq (org-element-type parent) 'org-data)))
  19209. (goto-char (org-element-property :begin parent))
  19210. (if (org-with-limited-levels (org-before-first-heading-p))
  19211. (user-error "No surrounding element")
  19212. (org-with-limited-levels (org-back-to-heading)))))))
  19213. (defun org-down-element ()
  19214. "Move to inner element."
  19215. (interactive)
  19216. (let ((element (org-element-at-point)))
  19217. (cond
  19218. ((memq (org-element-type element) '(plain-list table))
  19219. (goto-char (org-element-property :contents-begin element))
  19220. (forward-char))
  19221. ((memq (org-element-type element) org-element-greater-elements)
  19222. ;; If contents are hidden, first disclose them.
  19223. (when (org-invisible-p (line-end-position)) (org-cycle))
  19224. (goto-char (or (org-element-property :contents-begin element)
  19225. (user-error "No content for this element"))))
  19226. (t (user-error "No inner element")))))
  19227. (defun org-drag-element-backward ()
  19228. "Move backward element at point."
  19229. (interactive)
  19230. (let ((elem (or (org-element-at-point)
  19231. (user-error "No element at point"))))
  19232. (if (eq (org-element-type elem) 'headline)
  19233. ;; Preserve point when moving a whole tree, even if point was
  19234. ;; on blank lines below the headline.
  19235. (let ((offset (skip-chars-backward " \t\n")))
  19236. (unwind-protect (org-move-subtree-up)
  19237. (forward-char (- offset))))
  19238. (let ((prev-elem
  19239. (save-excursion
  19240. (goto-char (org-element-property :begin elem))
  19241. (skip-chars-backward " \r\t\n")
  19242. (unless (bobp)
  19243. (let* ((beg (org-element-property :begin elem))
  19244. (prev (org-element-at-point))
  19245. (up prev))
  19246. (while (and (setq up (org-element-property :parent up))
  19247. (<= (org-element-property :end up) beg))
  19248. (setq prev up))
  19249. prev)))))
  19250. ;; Error out if no previous element or previous element is
  19251. ;; a parent of the current one.
  19252. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  19253. (user-error "Cannot drag element backward")
  19254. (let ((pos (point)))
  19255. (org-element-swap-A-B prev-elem elem)
  19256. (goto-char (+ (org-element-property :begin prev-elem)
  19257. (- pos (org-element-property :begin elem))))))))))
  19258. (defun org-drag-element-forward ()
  19259. "Move forward element at point."
  19260. (interactive)
  19261. (let* ((pos (point))
  19262. (elem (or (org-element-at-point)
  19263. (user-error "No element at point"))))
  19264. (when (= (point-max) (org-element-property :end elem))
  19265. (user-error "Cannot drag element forward"))
  19266. (goto-char (org-element-property :end elem))
  19267. (let ((next-elem (org-element-at-point)))
  19268. (when (or (org-element-nested-p elem next-elem)
  19269. (and (eq (org-element-type next-elem) 'headline)
  19270. (not (eq (org-element-type elem) 'headline))))
  19271. (goto-char pos)
  19272. (user-error "Cannot drag element forward"))
  19273. ;; Compute new position of point: it's shifted by NEXT-ELEM
  19274. ;; body's length (without final blanks) and by the length of
  19275. ;; blanks between ELEM and NEXT-ELEM.
  19276. (let ((size-next (- (save-excursion
  19277. (goto-char (org-element-property :end next-elem))
  19278. (skip-chars-backward " \r\t\n")
  19279. (forward-line)
  19280. ;; Small correction if buffer doesn't end
  19281. ;; with a newline character.
  19282. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  19283. (org-element-property :begin next-elem)))
  19284. (size-blank (- (org-element-property :end elem)
  19285. (save-excursion
  19286. (goto-char (org-element-property :end elem))
  19287. (skip-chars-backward " \r\t\n")
  19288. (forward-line)
  19289. (point)))))
  19290. (org-element-swap-A-B elem next-elem)
  19291. (goto-char (+ pos size-next size-blank))))))
  19292. (defun org-drag-line-forward (arg)
  19293. "Drag the line at point ARG lines forward."
  19294. (interactive "p")
  19295. (dotimes (_ (abs arg))
  19296. (let ((c (current-column)))
  19297. (if (< 0 arg)
  19298. (progn
  19299. (beginning-of-line 2)
  19300. (transpose-lines 1)
  19301. (beginning-of-line 0))
  19302. (transpose-lines 1)
  19303. (beginning-of-line -1))
  19304. (org-move-to-column c))))
  19305. (defun org-drag-line-backward (arg)
  19306. "Drag the line at point ARG lines backward."
  19307. (interactive "p")
  19308. (org-drag-line-forward (- arg)))
  19309. (defun org-mark-element ()
  19310. "Put point at beginning of this element, mark at end.
  19311. Interactively, if this command is repeated or (in Transient Mark
  19312. mode) if the mark is active, it marks the next element after the
  19313. ones already marked."
  19314. (interactive)
  19315. (let (deactivate-mark)
  19316. (if (and (called-interactively-p 'any)
  19317. (or (and (eq last-command this-command) (mark t))
  19318. (and transient-mark-mode mark-active)))
  19319. (set-mark
  19320. (save-excursion
  19321. (goto-char (mark))
  19322. (goto-char (org-element-property :end (org-element-at-point)))
  19323. (point)))
  19324. (let ((element (org-element-at-point)))
  19325. (end-of-line)
  19326. (push-mark (min (point-max) (org-element-property :end element)) t t)
  19327. (goto-char (org-element-property :begin element))))))
  19328. (defun org-narrow-to-element ()
  19329. "Narrow buffer to current element."
  19330. (interactive)
  19331. (let ((elem (org-element-at-point)))
  19332. (cond
  19333. ((eq (car elem) 'headline)
  19334. (narrow-to-region
  19335. (org-element-property :begin elem)
  19336. (org-element-property :end elem)))
  19337. ((memq (car elem) org-element-greater-elements)
  19338. (narrow-to-region
  19339. (org-element-property :contents-begin elem)
  19340. (org-element-property :contents-end elem)))
  19341. (t
  19342. (narrow-to-region
  19343. (org-element-property :begin elem)
  19344. (org-element-property :end elem))))))
  19345. (defun org-transpose-element ()
  19346. "Transpose current and previous elements, keeping blank lines between.
  19347. Point is moved after both elements."
  19348. (interactive)
  19349. (org-skip-whitespace)
  19350. (let ((end (org-element-property :end (org-element-at-point))))
  19351. (org-drag-element-backward)
  19352. (goto-char end)))
  19353. (defun org-unindent-buffer ()
  19354. "Un-indent the visible part of the buffer.
  19355. Relative indentation (between items, inside blocks, etc.) isn't
  19356. modified."
  19357. (interactive)
  19358. (unless (eq major-mode 'org-mode)
  19359. (user-error "Cannot un-indent a buffer not in Org mode"))
  19360. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  19361. (unindent-tree
  19362. (lambda (contents)
  19363. (dolist (element (reverse contents))
  19364. (if (memq (org-element-type element) '(headline section))
  19365. (funcall unindent-tree (org-element-contents element))
  19366. (save-excursion
  19367. (save-restriction
  19368. (narrow-to-region
  19369. (org-element-property :begin element)
  19370. (org-element-property :end element))
  19371. (org-do-remove-indentation))))))))
  19372. (funcall unindent-tree (org-element-contents parse-tree))))
  19373. (defun org-make-options-regexp (kwds &optional extra)
  19374. "Make a regular expression for keyword lines.
  19375. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  19376. when non-nil, is a regexp matching keywords names."
  19377. (concat "^[ \t]*#\\+\\("
  19378. (regexp-opt kwds)
  19379. (and extra (concat (and kwds "\\|") extra))
  19380. "\\):[ \t]*\\(.*\\)"))
  19381. ;;; Conveniently switch to Info nodes
  19382. (defun org-info-find-node (&optional nodename)
  19383. "Find Info documentation NODENAME or Org documentation according context.
  19384. Started from `gnus-info-find-node'."
  19385. (interactive)
  19386. (Info-goto-node
  19387. (or nodename
  19388. (let ((default-org-info-node "(org) Top"))
  19389. (cond
  19390. ((eq 'org-agenda-mode major-mode) "(org) Agenda Views")
  19391. ((eq 'org-mode major-mode)
  19392. (let* ((context (org-element-at-point))
  19393. (element-info-nodes ; compare to `org-element-all-elements'.
  19394. `((babel-call . "(org) Evaluating Code Blocks")
  19395. (center-block . "(org) Paragraphs")
  19396. (clock . ,default-org-info-node)
  19397. (comment . "(org) Comment Lines")
  19398. (comment-block . "(org) Comment Lines")
  19399. (diary-sexp . ,default-org-info-node)
  19400. (drawer . "(org) Drawers")
  19401. (dynamic-block . "(org) Dynamic Blocks")
  19402. (example-block . "(org) Literal Examples")
  19403. (export-block . "(org) ASCII/Latin-1/UTF-8 export")
  19404. (fixed-width . ,default-org-info-node)
  19405. (footnote-definition . "(org) Creating Footnotes")
  19406. (headline . "(org) Document Structure")
  19407. (horizontal-rule . "(org) Built-in Table Editor")
  19408. (inlinetask . ,default-org-info-node)
  19409. (item . "(org) Plain Lists")
  19410. (keyword . "(org) Per-file keywords")
  19411. (latex-environment . "(org) LaTeX Export")
  19412. (node-property . "(org) Properties and Columns")
  19413. (paragraph . "(org) Paragraphs")
  19414. (plain-list . "(org) Plain Lists")
  19415. (planning . "(org) Deadlines and Scheduling")
  19416. (property-drawer . "(org) Properties and Columns")
  19417. (quote-block . "(org) Paragraphs")
  19418. (section . ,default-org-info-node)
  19419. (special-block . ,default-org-info-node)
  19420. (src-block . "(org) Working with Source Code")
  19421. (table . "(org) Tables")
  19422. (table-row . "(org) Tables")
  19423. (verse-block . "(org) Paragraphs"))))
  19424. (or (cdr (assoc (car context) element-info-nodes))
  19425. default-org-info-node)))
  19426. (t default-org-info-node))))))
  19427. ;;; Finish up
  19428. (add-hook 'org-mode-hook ;remove folds when changing major mode
  19429. (lambda () (add-hook 'change-major-mode-hook
  19430. 'org-fold-show-all 'append 'local)))
  19431. (provide 'org)
  19432. (run-hooks 'org-load-hook)
  19433. ;;; org.el ends here